pediatric-ai-scribe-v3/client/src/pages/HospitalCourse.tsx
Daniel cd1f762f34 feat(notes): restore audio recording + save/load across all 7 note pages
Recovered from git history (commit be14578) — the vanilla recording UI
was deleted during the "minimum-viable" note ports without being
re-implemented. Every note page now gets the full vanilla behavior
back:

Recording (Encounter, Dictation, SOAP, Sick Visit, Hospital Course):
  • AudioRecorder — MediaRecorder mono/16kHz/EC+NS/opus 32kbps
  • Pause / Resume (native where supported, restart-on-same-stream
    fallback for Safari)
  • Live preview via Web Speech API (opt-in in Settings)
  • On stop → upload to /api/transcribe; fall back to live preview
    if server unavailable or blob > 24 MB
  • Failed uploads → /api/audio-backups (IndexedDB fallback)

Save / Load / New-patient toolbar (all 7 note pages):
  • sessionStorage keys _savedEncId_<type> + _idempKey_<type>
    survive page refresh + sign-out within the same tab
  • Optimistic locking via expected_version (409 → "Someone else
    edited this encounter")
  • Load popover lists saved encounters of matching type only
  • Draft #N chip shows current session-bound row

Well Visit and Chart Review: toolbar only — vanilla had no recorder
on those tabs (paste-based workflows).

New components:
  client/src/components/Recorder.tsx
  client/src/components/EncounterToolbar.tsx

New libraries:
  client/src/lib/recorder.ts            — AudioRecorder class
  client/src/lib/transcribe.ts          — /api/transcribe + audio backup
  client/src/lib/web-speech.ts          — webkit speech preview + dedupe
  client/src/lib/encounter-persistence.ts — save/load/version tracking
2026-04-24 05:24:09 +02:00

197 lines
9.4 KiB
TypeScript

// ============================================================
// HOSPITAL COURSE — /api/generate-hospital-course
// ============================================================
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { api, ApiError } from '@/lib/api';
import type { HospitalCourseOk } from '@/shared/types';
import Recorder from '@/components/Recorder';
import EncounterToolbar from '@/components/EncounterToolbar';
type SettingKind = 'floor' | 'picu' | 'nicu' | 'psych';
type FormatKind = 'auto' | 'prose' | 'dayByDay' | 'organSystem';
const TYPE = 'hospital' as const;
interface NoteEntry { date: string; type: string; content: string }
export default function HospitalCourse() {
const [label, setLabel] = useState('');
const [recError, setRecError] = useState<string | null>(null);
const [patientAge, setPatientAge] = useState('');
const [patientGender, setPatientGender] = useState('');
const [pmh, setPmh] = useState('');
const [setting, setSetting] = useState<SettingKind>('floor');
const [los, setLos] = useState('');
const [format, setFormat] = useState<FormatKind>('auto');
const [hAndPContent, setHAndPContent] = useState('');
const [notesText, setNotesText] = useState('');
const [additionalInstructions, setAdditionalInstructions] = useState('');
const [result, setResult] = useState<{ hospitalCourse: string; format: string } | null>(null);
const generate = useMutation<HospitalCourseOk, Error, any>({
mutationFn: (body) => api.post<HospitalCourseOk>('/api/generate-hospital-course', body),
onSuccess: (data) => setResult({ hospitalCourse: data.hospitalCourse, format: data.format || 'auto' }),
});
function submit(e: React.FormEvent) {
e.preventDefault();
setResult(null);
// Notes textarea: one blank-line-separated note per block. First
// line of each block is used as the date if it looks like one,
// rest becomes content.
const notes: NoteEntry[] = notesText
.split(/\n\s*\n/)
.map((block) => block.trim())
.filter(Boolean)
.map((block, i) => ({ date: `Day ${i + 1}`, type: 'Progress Note', content: block }));
generate.mutate({
notes,
hAndP: hAndPContent ? { date: 'Admission', content: hAndPContent } : undefined,
patientAge, patientGender, pmh, setting,
los: los ? parseInt(los) : undefined,
formatPreference: format,
additionalInstructions: additionalInstructions || undefined,
});
}
const input = 'w-full rounded-md border border-input bg-background px-3 py-2 text-sm';
return (
<div className="max-w-4xl mx-auto p-6 space-y-4">
<header>
<h1 className="text-2xl font-semibold">Hospital Course</h1>
<p className="text-sm text-muted-foreground">
Progress notes + H&amp;P hospital course summary (prose, day-by-day, or organ-system format).
</p>
</header>
<EncounterToolbar
type={TYPE}
label={label} setLabel={setLabel}
transcript={notesText} generatedNote={result?.hospitalCourse || ''}
partialData={{ age: patientAge, gender: patientGender, pmh, setting, los, format, hAndPContent, additionalInstructions }}
onLoad={(enc) => {
setNotesText(enc.transcript || '');
setResult(enc.generated_note ? { hospitalCourse: enc.generated_note, format: 'auto' } : null);
try {
const pd = enc.partial_data ? JSON.parse(enc.partial_data) : null;
if (pd?.age) setPatientAge(pd.age);
if (pd?.gender) setPatientGender(pd.gender);
if (pd?.pmh) setPmh(pd.pmh);
if (pd?.setting) setSetting(pd.setting);
if (pd?.los) setLos(pd.los);
if (pd?.format) setFormat(pd.format);
if (pd?.hAndPContent) setHAndPContent(pd.hAndPContent);
if (pd?.additionalInstructions) setAdditionalInstructions(pd.additionalInstructions);
} catch { /* ignore */ }
setLabel(enc.label || '');
}}
onClear={() => {
setNotesText(''); setResult(null);
setPatientAge(''); setPatientGender(''); setPmh('');
setSetting('floor'); setLos(''); setFormat('auto');
setHAndPContent(''); setAdditionalInstructions('');
}}
/>
<form onSubmit={submit} className="space-y-4">
<div className="grid grid-cols-3 gap-3">
<label className="flex flex-col gap-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Age</span>
<input className={input} value={patientAge} onChange={(e) => setPatientAge(e.target.value)} />
</label>
<label className="flex flex-col gap-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Gender</span>
<select className={input} value={patientGender} onChange={(e) => setPatientGender(e.target.value)}>
<option value="">Select</option><option>Male</option><option>Female</option>
</select>
</label>
<label className="flex flex-col gap-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Setting</span>
<select className={input} value={setting} onChange={(e) => setSetting(e.target.value as SettingKind)}>
<option value="floor">Floor</option>
<option value="picu">PICU</option>
<option value="nicu">NICU</option>
<option value="psych">Psych</option>
</select>
</label>
</div>
<div className="grid grid-cols-3 gap-3">
<label className="flex flex-col gap-1 col-span-2">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">PMH</span>
<input className={input} placeholder="e.g. Asthma, hypothyroidism" value={pmh} onChange={(e) => setPmh(e.target.value)} />
</label>
<label className="flex flex-col gap-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">LOS (days)</span>
<input className={input} type="number" value={los} onChange={(e) => setLos(e.target.value)} />
</label>
</div>
<label className="flex flex-col gap-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Format</span>
<select className={input} value={format} onChange={(e) => setFormat(e.target.value as FormatKind)}>
<option value="auto">Auto (infer from setting + LOS)</option>
<option value="prose">Prose summary</option>
<option value="dayByDay">Day-by-day</option>
<option value="organSystem">Organ-system (ICU)</option>
</select>
</label>
<label className="flex flex-col gap-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">H&amp;P</span>
<textarea className={input + ' min-h-[120px] font-mono text-sm'} value={hAndPContent} onChange={(e) => setHAndPContent(e.target.value)} />
</label>
<Recorder
module="hospital"
onTranscript={(text, meta) => {
if (meta.appended) {
setNotesText((prev) => prev ? prev + '\n\n' + text : text);
} else {
setNotesText((prev) => prev ? prev + '\n\n' + text : text);
}
setRecError(null);
}}
onError={(msg) => setRecError(msg)}
/>
{recError && <div className="text-sm text-destructive">{recError}</div>}
<label className="flex flex-col gap-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
Progress notes <span className="normal-case font-normal text-muted-foreground">(separate each note with a blank line)</span>
</span>
<textarea className={input + ' min-h-[200px] font-mono text-sm'} value={notesText} onChange={(e) => setNotesText(e.target.value)} />
</label>
<label className="flex flex-col gap-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Additional instructions</span>
<textarea className={input + ' min-h-[60px] text-sm'} value={additionalInstructions} onChange={(e) => setAdditionalInstructions(e.target.value)} />
</label>
{generate.error && <div className="text-sm text-destructive">{(generate.error as ApiError).message}</div>}
<button
type="submit"
disabled={generate.isPending || !notesText.trim()}
className="rounded-md bg-primary text-primary-foreground px-4 py-2 text-sm font-medium disabled:opacity-50"
>
{generate.isPending ? 'Generating…' : 'Generate Hospital Course'}
</button>
</form>
{result && (
<section className="rounded-lg border border-border bg-card">
<header className="px-4 py-2 border-b border-border flex items-center justify-between bg-muted/40">
<h2 className="text-sm font-semibold">
Hospital Course <span className="text-xs font-normal text-muted-foreground">({result.format})</span>
</h2>
<button onClick={() => navigator.clipboard.writeText(result.hospitalCourse)} className="text-xs text-muted-foreground underline">Copy</button>
</header>
<div className="p-4 whitespace-pre-wrap text-sm">{result.hospitalCourse}</div>
</section>
)}
</div>
);
}