BOROUGH OF STRATFORD · CAMDEN COUNTY, NJEmergency Operations Center
--:--LOCAL
`; } async function saveFile(filename, data){ if(!downloads){ toast('Saving files isn\'t available here. Use Copy instead.'); return; } try{ const r=await downloads.save({filename, data}); if(r&&r.status==='saved') toast('Saved'); } catch(e){ if(e&&e.code==='unavailable'){ downloads=null; render(); } toast("The file wasn't saved."); } } /* ---------- small sheets ---------- */ function levelSheet(){ const cur=(S.status&&S.status.level)||'3'; openEditor({title:'EOC activation level', saveLabel:'Set level', fields:[ {k:'level',l:'Level',t:'select',o:Object.entries(LV).map(([k,v])=>[k,`${v.t} — ${v.d}`])}, {k:'reason',l:'Reason (goes in the log)',t:'textarea',rows:2,ph:'e.g. Winter Storm Warning issued; partial activation with FD, DPW and OEM'}], data:{level:cur}, onSave: async v=>{ await setSingleton('status',{level:v.level}); if(v.level!==cur) addLog(`EOC activation set to ${LV[v.level].t} (${LV[v.level].d})${v.reason?': '+v.reason:''}`,{auto:1,sig:1}); }}); } function opSheet(){ const st=S.status||{}; const now=new Date(); const def12=new Date(now.getTime()+12*3600e3).toISOString(); openEditor({title:'Operational period', fields:[{k:'opFrom',l:'From',t:'datetime',half:1},{k:'opTo',l:'To',t:'datetime',half:1}], data:{opFrom:st.opFrom||now.toISOString(), opTo:st.opTo||def12}, onSave: async v=>{ await setSingleton('status',v); addLog(`Operational period set: ${fmt(v.opFrom,{full:1})} – ${fmt(v.opTo,{full:1})}`,{auto:1}); }}); } function agencySheet(k){ const a=(S.status&&S.status.agencies&&S.status.agencies[k])||{}; openEditor({title:`${AG[k].n} status`, saveLabel:'Update status', fields:[ {k:'state',l:'Status',t:'select',o:Object.keys(AGSTATE),d:'Normal'},{k:'note',l:'Status note',t:'textarea',rows:3,ph:'Units committed, staffing, problems, needs'}], data:a, onSave: async v=>{ const ag=Object.assign({}, (S.status&&S.status.agencies)||{}); ag[k]={state:v.state,note:v.note,at:nowISO(),by:uid}; await setSingleton('status',{agencies:ag}); addLog(`${AG[k].n} status: ${v.state}${v.note?' — '+v.note:''}`,{auto:1,agency:k,sig:v.state==='Overwhelmed'}); }}); } function wxSheet(){ const w=S.weather||{}; openEditor({title:'Forecast & impact window', fields:[ {k:'headline',l:'Headline',ph:'e.g. Coastal low brings heavy rain and damaging gusts Thursday night'}, {k:'windowStart',l:'Impacts begin',t:'datetime',half:1},{k:'windowEnd',l:'Impacts end',t:'datetime',half:1}, {k:'rain',l:'Rain',ph:'e.g. 2–3 in',half:1},{k:'snow',l:'Snow / ice',ph:'e.g. 6–10 in',half:1},{k:'gust',l:'Peak gusts',ph:'e.g. 50 mph',half:1}], data:w, onSave: v=>setSingleton('weather',v)}); } function productSheet(i){ const prods=[...((S.weather&&S.weather.products)||[])]; const p = i!=null? prods[i] : null; openEditor({title:p?'Edit NWS product':'Add NWS product', fields:[ {k:'product',l:'Product',t:'select',o:NWS_PRODUCTS,d:'Winter Storm Warning'}, {k:'issued',l:'Issued',t:'datetime',half:1},{k:'expires',l:'Expires',t:'datetime',half:1}, {k:'notes',l:'Key details',t:'textarea',rows:3,ph:'Totals, timing and impacts from the product text'}], data:p||{issued:nowISO()}, onSave: async v=>{ if(p) prods[i]=v; else prods.unshift(v); await setSingleton('weather',{products:prods}); if(!p) addLog(`NWS ${v.product} in effect${v.expires?' until '+fmt(v.expires,{full:1}):''}${v.notes?': '+v.notes:''}`,{auto:1,sig:/Warning/.test(v.product)}); }, onDelete: p? ()=>{ prods.splice(i,1); return setSingleton('weather',{products:prods}); }:null}); } function briefSheet(){ const w=S.weather||{}; openEditor({title:'New briefing', saveLabel:'Save & log', fields:[{k:'briefing',l:'Briefing notes',t:'textarea',rows:9,req:1,ph:'Source (NWS Mount Holly webinar, County OEM call), timing, confidence, expected local impacts, decisions'}], data:{briefing:w.briefing||''}, onSave: async v=>{ await setSingleton('weather',{briefing:v.briefing, briefedAt:nowISO(), briefedBy:uid}); addLog(`Weather briefing recorded: ${v.briefing.split('\n')[0].slice(0,140)}`,{auto:1}); }}); } /* ---------- Claude ---------- */ async function aiSitrep(btn){ btn.disabled=true; const box=$('#sitrep-ai'); box.textContent='Thinking…'; const prompt=`You write executive summaries for a small New Jersey borough's Emergency Operations Center. Using ONLY the situation report below, write a plain-language summary of 90 to 140 words for the Mayor and Borough Council. Lead with the most important fact, then current impacts, what each department is doing, and decisions or needs for elected officials. Use no information that is not in the report, no headings, no bullet points, and no sign-off. If something important is missing, say so in one sentence at the end.\n\nSITUATION REPORT:\n${buildSitrep()}`; try{ const r=await sample(prompt,{modelTier:'quick',cache:false,onText:({text})=>{ box.textContent=text; }}); UI.sitrepAI=r.text; render(); } catch(e){ box.textContent = e&&e.code==='not_granted' ? 'Claude isn\'t available for this page.' : e&&e.code==='rate_limited' ? 'Claude is busy. Try again in a minute.' : 'The summary couldn\'t be written. Try again.'; btn.disabled=false; if(e&&e.code==='not_granted'){ sample=null; } } } async function aiNotice(p, btn){ btn.disabled=true; const box=document.getElementById('notice-'+p.id); box.textContent='Thinking…'; const prompt=`Write a public notice for residents of the Borough of Stratford, New Jersey, announcing a state of local emergency, based ONLY on the proclamation below. 120 to 180 words, plain language at a 6th-grade reading level, suitable for a Nixle alert, the borough website and social media. Start with a one-line headline. State what is happening, when it takes effect, each order in simple terms, and what residents should do. End with: "For emergencies call 911. Stratford Office of Emergency Management: (856) 783-8616." Do not invent details, times or locations that are not in the proclamation.\n\nPROCLAMATION:\n${soeText(p)}`; try{ const r=await sample(prompt,{modelTier:'quick',cache:false,onText:({text})=>{ box.textContent=text; }}); UI.noticeAI[p.id]=r.text; render(); } catch(e){ box.textContent = e&&e.code==='rate_limited' ? 'Claude is busy. Try again in a minute.' : 'The notice couldn\'t be drafted. Try again.'; btn.disabled=false; } } /* ============================== events ============================== */ document.addEventListener('click', async ev=>{ const c=ev.target.closest('[data-close]'); if(c){ closeSheet(); return; } if(ev.target.id==='modal'){ closeSheet(); return; } const cp=ev.target.closest('[data-copy]'); if(cp){ copyText(cp.dataset.copy, cp); return; } if(ev.target.closest('#hdr-level')){ if(!readOnly&&db) levelSheet(); else location.hash='dashboard'; return; } if(ev.target.closest('#hdr-op')){ if(!readOnly&&db) opSheet(); return; } const el=ev.target.closest('[data-act]'); if(!el) return; if(el.tagName==='SELECT'||(el.tagName==='INPUT'&&el.type!=='button')) return; const a=el.dataset.act, id=el.dataset.id, k=el.dataset.k; const find=(col)=>S[col].find(x=>x.id===id); try{ switch(a){ case 'set-level': levelSheet(); break; case 'set-op': opSheet(); break; case 'agency': agencySheet(k); break; case 'new-incident': editIncident(null); break; case 'open-incident': UI.incSel=id; location.hash='incidents'; break; case 'sel-incident': UI.incSel=id; render(); break; case 'edit-incident': editIncident(find('incidents')); break; case 'make-current': { const i=find('incidents'); await setSingleton('status',{currentIncident:id}); addLog(`Current incident set to ${i.name}`,{auto:1,incidentId:id}); break; } case 'new-task': editTask(null); break; case 'edit-task': ev.preventDefault(); editTask(find('tasks')); break; case 'task-filter': UI.taskAg=k; render(); break; case 'new-resource': editResource(null); break; case 'edit-resource': editResource(find('resources')); break; case 'new-closure': editClosure(null); break; case 'edit-closure': if(ev.target.closest('button')) break; editClosure(find('closures')); break; case 'reopen': { ev.stopPropagation(); const cl=find('closures'); await updDoc('closures',id,{status:'Reopened',reopenedAt:nowISO()}); addLog(`Road reopened: ${cl.road}${cl.limits?' ('+cl.limits+')':''} after ${dur(Date.now()-new Date(cl.closedAt).getTime())}`,{auto:1,agency:cl.agency,incidentId:cl.incidentId,sig:1}); break; } case 'toggle-closed': UI.closedShow=!UI.closedShow; render(); break; case 'del-log': await delDoc('log',id); break; case 'log-filter': UI.logAg=k; render(); break; case 'copy-log': copyText(S.log.slice().reverse().map(l=>`${fmt(l.ts,{full:1})}\t${AG[l.agency]?AG[l.agency].n:''}\t${l.text}`).join('\n'), el); break; case 'wx-edit': wxSheet(); break; case 'wx-product': if(readOnly||!db) break; productSheet(el.dataset.i!=null?Number(el.dataset.i):null); break; case 'wx-brief': briefSheet(); break; case 'ck-reset': confirmSheet('Reset checklist','

Clear every pre-storm checklist item so the departments can work through it again for the next storm?

','Reset checklist', async()=>{ const cl={}; Object.values(PREP).flat().forEach(([id])=>cl[id]=null); await setSingleton('weather',{checklist:cl}); addLog('Pre-storm checklist reset',{auto:1}); }); break; case 'new-soe': editSOE(null); break; case 'sel-soe': UI.soeSel=id; render(); break; case 'edit-soe': editSOE(find('soe')); break; case 'soe-step': { const p=find('soe'); const steps=Object.assign({}, p.steps||{}); const label=SOE_STEPS.find(s=>s[0]===k)[1]; if(steps[k]) steps[k]=null; else { steps[k]={at:nowISO(),by:uid}; addLog(`Declaration ${p.number||'draft'}: ${label}`,{auto:1,incidentId:p.incidentId}); } await updDoc('soe',id,{steps}); break; } case 'issue-soe': { const p=find('soe'); const missing=SOE_STEPS.slice(0,4).filter(([s])=>!(p.steps||{})[s]).map(s=>s[1]); confirmSheet('Mark proclamation issued', `

This marks ${esc(p.number||'the proclamation')} as in effect across the EOC and logs it.

${missing.length?``:''}`, 'Mark issued', async()=>{ await updDoc('soe',id,{status:'Issued',issuedAt:nowISO()}); addLog(`STATE OF LOCAL DISASTER EMERGENCY declared${p.number?' — Proclamation '+p.number:''}`,{auto:1,sig:1,incidentId:p.incidentId}); }); break; } case 'rescind-soe': { const p=find('soe'); confirmSheet('Rescind proclamation', `

End the state of local emergency under ${esc(p.number||'this proclamation')}? All orders end with it. Remember to notify Camden County OEM and post a public notice.

`, 'Rescind', async()=>{ await updDoc('soe',id,{status:'Rescinded',rescindedAt:nowISO()}); addLog(`State of local emergency RESCINDED${p.number?' — Proclamation '+p.number:''}`,{auto:1,sig:1,incidentId:p.incidentId}); }); break; } case 'copy-soe': copyText(soeText(find('soe')), el); break; case 'save-soe': { const p=find('soe'); saveFile(`Stratford_SOE_${(p.number||'draft').replace(/[^\w-]+/g,'_')}.txt`, soeText(p)); break; } case 'ai-notice': aiNotice(find('soe'), el); break; case 'copy-notice': copyText(UI.noticeAI[id]||'', el); break; case 'new-event': editEvent(null); break; case 'sel-event': UI.evSel=id; render(); break; case 'edit-event': editEvent(find('events')); break; case 'copy-event': copyText(eventBriefing(find('events')), el); break; case 'event-incident': { const e=find('events'); const r=await addDoc('incidents',{name:e.name,type:'Planned event',status:'Active',location:e.location||'',command:e.lead?AG[e.lead].n:'',summary:`Planned event. Expected attendance: ${e.attendance||'unknown'}.`,objectives:e.objectives||''}); if(r){ await updDoc('events',id,{incidentId:r.id,status:'Active'}); addLog(`Event opened as incident: ${e.name}`,{auto:1,incidentId:r.id,sig:1}); toast('Incident opened'); } break; } case 'new-form': editForm(k, null); break; case 'edit-form': { ev.preventDefault(); const f=find('forms'); if(f) editForm(f.type, f); break; } case 'new-contact': editContact(null); break; case 'edit-contact': ev.preventDefault(); editContact(find('contacts')); break; case 'copy-sitrep': copyText((UI.sitrepAI?`EXECUTIVE SUMMARY\n${UI.sitrepAI}\n\n`:'')+buildSitrep(), el); break; case 'save-sitrep': { const d=new Date(); saveFile(`Stratford_EOC_Sitrep_${d.getFullYear()}${p2(d.getMonth()+1)}${p2(d.getDate())}_${p2(d.getHours())}${p2(d.getMinutes())}.txt`, (UI.sitrepAI?`EXECUTIVE SUMMARY\n${UI.sitrepAI}\n\n`:'')+buildSitrep()); break; } case 'ai-sitrep': aiSitrep(el); break; case 'new-unit': editUnit(null); break; case 'sel-acc': UI.accSel=id; render(); break; case 'open-acc': UI.accSel=id; break; case 'toggle-inc-closed': UI.incClosed=!UI.incClosed; render(); break; case 'start-par': { const inc=find('incidents'); await updDoc('incidents',id,{parStartedAt:nowISO()}); addLog(`PAR started — ${incNo(inc)} ${inc.name}, ${incUnits(id).length} units`,{auto:1,incidentId:id,sig:1}); break; } case 'cancel-par': await updDoc('incidents',id,{parStartedAt:''}); break; case 'unit-par': { const u=S.units.find(x=>x.id===id); if(!u) break; const inc=S.incidents.find(x=>x.id===u.incidentId); if(!inc) break; const pr=parState(inc); const others=pr.units.filter(x=>x.id!==u.id); const now=nowISO(); await updDoc('units',id,{parAt:now}); if(others.every(x=>x.parAt && x.parAt>=pr.start)){ const ppl=pr.units.reduce((n,x)=>n+unitPersons(x),0); await updDoc('incidents',inc.id,{parCompleteAt:now}); addLog(`PAR complete — ${incNo(inc)}: ${pr.units.length} units, ${ppl} personnel accounted for`,{auto:1,incidentId:inc.id,sig:1}); } break; } case 'assign-unit': { const sel=document.getElementById('inc-unit-'+id); const u=sel&&S.units.find(x=>x.id===sel.value); const inc=find('incidents'); if(!u||(u.status||'Available')!=='Available'){ toast('That unit is no longer available.'); break; } await updDoc('units',u.id,{incidentId:id,status:'Assigned',incStatus:'Dispatched',dispatchedAt:nowISO(),post:'Unassigned',postAt:nowISO(),parAt:''}); addLog(`${u.name} dispatched to ${incNo(inc)} ${inc.name} (${unitPersons(u)} personnel)`,{auto:1,agency:AG[u.agency]?u.agency:undefined,incidentId:id}); break; } case 'release-unit': { const u=S.units.find(x=>x.id===id); if(!u) break; const incId=u.incidentId; await updDoc('units',id,{status:'Available',incidentId:'',incStatus:'',post:'',parAt:''}); addLog(`${u.name} released from ${incName(incId)||'incident'}, available`,{auto:1,agency:AG[u.agency]?u.agency:undefined,incidentId:incId}); break; } case 'edit-unit': if(ev.target.closest('button')) break; editUnit(find('units')); break; case 'unit-214': ev.stopPropagation(); export214(find('units')); break; case 'export-211': export211(); break; case 'approve': { const r=S.requests.find(x=>x.id===id); editMember(id, r?{name:r.name||'',agency:r.agency,title:r.title,phone:r.phone||''}:{}); break; } case 'deny': confirmSheet('Deny request', `

Deny ${esc(who(id))}'s request? They can send a new one later. To fully block someone, also remove them from the page's Share menu.

`, 'Deny', async()=>{ await db.doc('requests/'+id).delete(); }); break; case 'edit-member': editMember(id); break; case 'add-member': editMember(id, {}); break; } }catch(e){} }); document.addEventListener('keydown', ev=>{ if(ev.key==='Escape' && !$('#modal').hidden) closeSheet(); if(ev.key==='Enter' && ev.target.classList && ev.target.classList.contains('card')) ev.target.click(); }); document.addEventListener('change', async ev=>{ const el=ev.target; const a=el.dataset&&el.dataset.act; if(!a) return; if(a==='threat'){ const th=Object.assign({}, (S.weather&&S.weather.threats)||{}); const old=th[el.dataset.k]||0; th[el.dataset.k]=Number(el.value); await setSingleton('weather',{threats:th}); const lab=THREATS.find(t=>t[0]===el.dataset.k)[1]; addLog(`Threat level — ${lab}: ${TLV[old]} → ${TLV[th[el.dataset.k]]}`,{auto:1}); } if(a==='ck'){ const ck=Object.assign({}, (S.weather&&S.weather.checklist)||{}); if(el.checked) ck[el.dataset.k]={at:nowISO(),by:uid}; else ck[el.dataset.k]=null; await setSingleton('weather',{checklist:ck}); } if(a==='task-status'){ const t=S.tasks.find(x=>x.id===el.dataset.id); await updDoc('tasks',t.id,{status:el.value}); addLog(`Task "${t.title}" → ${el.value}`,{auto:1,agency:t.agency,incidentId:t.incidentId}); if(el.value==='Done') await syncUnitsForTask(t.unitIds,t.unitIds,'Done',t.title); } if(a==='unit-post'){ const u=S.units.find(x=>x.id===el.dataset.id); await updDoc('units',u.id,{post:el.value,postAt:nowISO()}); addLog(`${u.name} assigned to ${el.value}`,{auto:1,agency:AG[u.agency]?u.agency:undefined,incidentId:u.incidentId}); } if(a==='unit-incstatus'){ const u=S.units.find(x=>x.id===el.dataset.id); const v=el.value; const patch={incStatus:v}; if(v==='En route') patch.enrouteAt=nowISO(); if(v==='On scene') patch.onSceneAt=nowISO(); if(v==='Rehab'){ patch.post='Rehab'; patch.postAt=nowISO(); } await updDoc('units',u.id,patch); addLog(`${u.name} ${v.toLowerCase()}`,{auto:1,agency:AG[u.agency]?u.agency:undefined,incidentId:u.incidentId}); } if(a==='log-inc'){ UI.logInc=el.value; render(); } if(a==='log-sig'){ UI.logSig=el.checked; render(); } }); document.addEventListener('input', ev=>{ if(ev.target.id==='contact-q'){ UI.contactQ=ev.target.value; render(); } if(ev.target.id==='adm-q') searchPeople(ev.target.value.trim()); }); document.addEventListener('focusin', ev=>{ if(ev.target.id==='adm-q' && !ev.target.value) searchPeople(''); }); document.addEventListener('submit', async ev=>{ const f=ev.target; if(f.dataset.form==='setup'||f.dataset.form==='request'){ ev.preventDefault(); const b=f.querySelector('button[type=submit]'); b.disabled=true; await submitGate(f.dataset.form); b.disabled=false; return; } if(f.dataset.form!=='log') return; ev.preventDefault(); const sfx=f.querySelector('textarea').id.split('-').pop(); const t=$('#lc-text-'+sfx); const text=t.value.trim(); if(!text) { t.focus(); return; } if(!needDb()) return; const btn=f.querySelector('button[type=submit]'); btn.disabled=true; try{ await db.collection('log').add({ts:nowISO(), text, agency:$('#lc-ag-'+sfx).value, incidentId:$('#lc-inc-'+sfx).value, sig:$('#lc-sig-'+sfx).checked, auto:false, by:uid}); t.value=''; $('#lc-sig-'+sfx).checked=false; } catch(e){ try{ handleWriteError(e); }catch(_){} } btn.disabled=false; }); function route(){ const h=(location.hash||'').replace('#',''); view = VIEWS.some(v=>v[0]===h)? h : 'dashboard'; render(); window.scrollTo(0,0); if(room) room.presence({view}).catch(()=>{}); } window.addEventListener('hashchange', route); /* clock */ function liveTimers(){ const now=Date.now(); document.querySelectorAll('[data-since]').forEach(el=>{ const t=Date.parse(el.dataset.since); if(t) el.textContent=hms(now-t); }); document.querySelectorAll('[data-due]').forEach(el=>{ const t=Date.parse(el.dataset.due); const b=el.querySelector('.pardue'); if(!t||!b) return; const left=t-now; b.textContent = left>=0 ? hms(left) : 'OVERDUE '+hms(-left); el.classList.toggle('over', left<0); }); } function tick(){ liveTimers(); const d=new Date(); $('#clock').innerHTML=`${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}${d.toLocaleTimeString('en-US',{timeZoneName:'short'}).split(' ').pop()}`; } tick(); setInterval(tick,1000); setInterval(()=>{ if($('#modal').hidden) scheduleRender(); }, 60000); /* ============================== boot ============================== */ (async function boot(){ const h=(location.hash||'').replace('#',''); if(VIEWS.some(v=>v[0]===h)) view=h; render(); const c = window.claude; if(!c || !c.use){ dbState='none'; baseRO=true; readOnly=true; document.body.classList.add('ro'); render(); return; } const [d,u,s,dl,rm] = await Promise.all(['db','user','sample','downloads','room'].map(n=>c.use(n).catch(()=>null))); db=d; user=u; sample=s; downloads=dl; room=rm; if(user){ try{ uid = await user.id(); }catch(e){} try{ myProfile = await user.me(); isAdmin = !!myProfile.canEdit; isOwnerV = !!myProfile.isOwner; if(uid){ names[uid]=myProfile.name||''; avatars[uid]=myProfile.avatarUrl; } }catch(e){} try{ const w = await user.can('data.write'); if(w===false){ baseRO=true; readOnly=true; document.body.classList.add('ro'); } }catch(e){} } if(!db){ dbState='none'; baseRO=true; readOnly=true; document.body.classList.add('ro'); render(); return; } subscribe(); if(room){ try{ room.presence({view}).catch(()=>{}); room.onPeers(ch=>{ peersList=[...ch.peers]; peersList.forEach(p=>p.by&&who(p.by)); resolveNames().then(renderPeers); renderPeers(); }); }catch(e){} } render(); })();