◊
FallClinicPaper
v1 · prime 937
.
');w.document.close();w.print()} function renderDocuments(v){const docs=state.documents.sort((a,b)=>b.createdAt-a.createdAt);v.innerHTML=`

Documents

${docs.length} total
${docs.length?`${docs.map(d=>``).join('')}
DateTemplateCodeStatusHash
${dateStr(d.createdAt)}${esc(d.templateName)}${esc(d.code)}${d.status}${esc(d.hash)}
`:'
No documents. Generate one from Templates.
'}`} function renderPractice(v){const f=state.firm||{};v.innerHTML=`

Practice Setup

`} async function savePracticeForm(){const f=state.firm||{id:uid('fi'),ts:now()};f.name=$('#fName').value.trim();f.email=$('#fEmail').value.trim();f.address=$('#fAddr').value.trim();f.phone=$('#fPhone').value.trim();f.cqcRegistration=$('#fCqc').value.trim();f.updatedAt=now();state.firm=f;await idbPut('firms',f);await auditLog('practice.saved');toast('Saved');render()} function renderPatients(v){v.innerHTML=`

Patients

${state.patients.length}
${state.patients.length?`${state.patients.map(p=>{const d=p.demographics||{};const n=((d.title||'')+' '+(d.firstName||'')+' '+(d.lastName||'')).trim()||p.id.slice(0,8);return ``}).join('')}
NameNHSDOB
${esc(n)}${esc(d.nhsNumber||'—')}${esc(d.dob||'—')}
`:'
Patients sync from fallcliniconboard.
'}`} const T0_QA=[ {q:/referral|2ww|two.?week|urgent/i,a:'Referral letter should include: patient demographics, presenting complaint, HPC, PMH, current medications, allergies, examination findings, investigations, reason for referral, specific questions. Urgent (2WW) cancer referrals: NICE NG12 — suspected cancer pathway, must be seen within 14 days. Routine referrals: 18 weeks RTT (Referral to Treatment) target. E-referral via NHS e-RS preferred.'}, {q:/prescription|fp10|controlled|drug/i,a:'FP10 prescriptions: must include patient name/address/DOB, prescriber details, medication (approved name preferred), dose, frequency, quantity, date. Controlled drugs (Misuse of Drugs Regulations 2001): quantity in words and figures, prescriber signature in ink, form/strength specified. Repeatable prescriptions: state number of repeats. Electronic prescribing (EPS) for most items.'}, {q:/fit.?note|med3|sick|fitness/i,a:'Fit note (Med3/Statement of Fitness for Work): can state "not fit" or "may be fit" with adjustments. Valid for up to 3 months at a time. First 7 days: self-certification. From day 8: Med3 required. Adjustments: phased return, altered hours, amended duties, workplace adaptations. Backdating: up to 1 month if clinical records support. No obligation to see patient for return to work.'}, {q:/consent|informed|capacity|gillick/i,a:'Informed consent requires: disclosure of procedure, risks (common and serious), benefits, alternatives, right to withdraw. Montgomery v Lanarkshire [2015] UKSC 11 — duty to disclose material risks. Adults: presumed to have capacity (MCA 2005). Under 16: Gillick competence. 16-17: presumed competent (Family Law Reform Act 1969 s.8). Consent forms should be procedure-specific.'}, {q:/dnar|dnacpr|respect|resuscitation/i,a:'DNACPR: clinical decision about whether CPR would be successful or in the patient\'s best interest. ReSPECT: broader emergency care plan including CPR decision. Must be discussed with patient (if capacity) or LPA/family. Not the same as withdrawing treatment. MCA 2005 applies. Valid ADRT takes precedence. Review regularly. Tracey v Cambridge [2014] — duty to consult patient/family.'}, {q:/discharge|summary|handover/i,a:'Discharge summary (NICE QS174): must include diagnosis, procedures, medications (including changes), follow-up plan, GP actions, safety netting. Send within 24 hours of discharge. Medication reconciliation at discharge (NICE NG5). Include allergies. Copies to GP and patient.'}, {q:/death.?cert|mccd|coroner/i,a:'MCCD (Medical Certificate of Cause of Death): issued by doctor who attended the deceased during last illness. Must refer to coroner if: unknown cause, violent/unnatural, during operation, in custody, sudden/unexplained, not seen by doctor within 28 days. Births and Deaths Registration Act 1953. Death must be registered within 5 days. Medical examiner scrutiny introduced 2024.'}, {q:/medical.?report|amra|access/i,a:'Access to Medical Reports Act 1988: patient must consent before employer/insurer can request medical report. Patient has right to see report before supply, request amendments, withhold consent. Separate from Subject Access Request (SAR) under GDPR. Report should be factual and relevant to the request. Fee chargeable (BMA guidance on fees).'}]; function askT0(q){for(const r of T0_QA){if(r.q.test(q))return {answer:r.a,source:'T0 · UK clinical document rules'}}return null} async function askT3(q){if(!state.settings.anthropicKey)return null;try{const res=await fetch('https://api.anthropic.com/v1/messages',{method:'POST',headers:{'x-api-key':state.settings.anthropicKey,'anthropic-version':'2023-06-01','content-type':'application/json'},body:JSON.stringify({model:'claude-sonnet-4-20250514',max_tokens:600,messages:[{role:'user',content:'You are a UK clinical documentation expert. GMC, NHS, prescribing, consent, referrals. Concise.\n\n'+q}]})});if(!res.ok)return null;const j=await res.json();return {answer:j.content?.[0]?.text,source:'T3 · Anthropic'}}catch(e){return null}} function renderQA(v){v.innerHTML=`

Q & A

T0 + T3 BYOK
${(state.ui.chat||[]).map(m=>`
${esc(m.text)}${m.source?`
${esc(m.source)}
`:''}
`).join('')}
`;const box=$('#chatBox');if(box)box.scrollTop=box.scrollHeight} async function askQuestion(){const inp=$('#chatIn');if(!inp)return;const q=inp.value.trim();if(!q)return;inp.value='';if(!state.ui.chat)state.ui.chat=[];state.ui.chat.push({role:'user',text:q});render();let r=askT0(q);if(!r)r=await askT3(q);state.ui.chat.push(r?{role:'bot',text:r.answer,source:r.source}:{role:'bot',text:'No T0 match. Add BYOK key for T3.',source:'system'});persistUI();render()} function openModal(type){const modal=$('#modal');$('#modalTitle').textContent='Settings';modal.classList.add('open');$('#modalBody').innerHTML=`
`} function closeModal(){$('#modal').classList.remove('open')} function saveSettings(){state.settings.anthropicKey=$('#sKey').value.trim();state.settings.auditChain=$('#sAudit').checked;$('#tierBadge').textContent=state.settings.anthropicKey?'T3':'T0';persistUI();closeModal();toast('Saved');render()} function exportAll(){const d={tool:TOOLNAME,v:VERSION,ts:now(),firm:state.firm,patients:state.patients,documents:state.documents};const b=new Blob([JSON.stringify(d,null,2)],{type:'application/json'});const u=URL.createObjectURL(b);const a=document.createElement('a');a.href=u;a.download='fallclinicpaper-export.json';a.click();URL.revokeObjectURL(u);toast('Exported')} function importAll(){const inp=document.createElement('input');inp.type='file';inp.accept='.json';inp.onchange=async()=>{const f=inp.files[0];if(!f)return;try{const d=JSON.parse(await f.text());if(d.firm){state.firm=d.firm;await idbPut('firms',d.firm)}for(const k of['patients','documents']){if(Array.isArray(d[k]))for(const r of d[k]){state[k].push(r);await idbPut(k,r)}}persistUI();toast('Imported');render()}catch(e){toast('Failed')}};inp.click()} async function wipeAll(){if(!confirm('Wipe ALL data?'))return;for(const s of['patients','firms','documents','audit','state']){const tx=db.transaction(s,'readwrite');tx.objectStore(s).clear();await new Promise(r=>{tx.oncomplete=r})}location.reload()} async function seedDemo(){if(state.patients.length||state.firm)return; const firm={id:uid('fi'),name:'Demo Medical Centre',address:'1 Harley Street, London W1G 9QD',email:'reception@democlinic.nhs.uk',phone:'020 7123 4567',cqcRegistration:'CQC-1-234567890',updatedAt:now(),isDemo:true}; state.firm=firm;await idbPut('firms',firm); const p1={id:uid('pt'),ts:now(),updatedAt:now(),isDemo:true,status:'complete',demographics:{title:'Mrs',firstName:'Margaret',lastName:'Thompson',dob:'1952-03-14',sex:'Female',nhsNumber:'9434765919',address:'42 Oak Lane, London N1 3RT',postcode:'N1 3RT',phone:'07700 900123',email:'m.thompson@email.co.uk'},medical:{conditions:['Type 2 diabetes','Hypertension'],allergies:[{allergen:'Penicillin',reaction:'Rash',severity:'moderate'}],medications:['Metformin 500mg BD','Amlodipine 5mg OD']},consent:{gdprConsent:true},safeguarding:{flagged:false}}; const p2={id:uid('pt'),ts:now(),updatedAt:now(),isDemo:true,status:'new',demographics:{title:'Mr',firstName:'Amir',lastName:'Hassan',dob:'1988-07-22',sex:'Male',nhsNumber:'',address:'15 Elm Road, London E2 7QP'},medical:{conditions:[],allergies:[],medications:[]},consent:{},safeguarding:{}}; state.patients.push(p1,p2);await idbPut('patients',p1);await idbPut('patients',p2); await auditLog('demo.seeded',{reasoning:'first boot'});await persistUI()} (async function boot(){try{await openDB();await loadAll();await seedDemo();initMesh();$('#tierBadge').textContent=state.settings.anthropicKey?'T3':'T0';render()}catch(e){console.error('[fallclinicpaper] boot error:',e);document.getElementById('view').innerHTML='
Boot error: '+esc(e.message)+'
'}})();