import { useState, useEffect, useCallback } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { DismissibleAlert } from '../../../../../components/ui/dismissible-alert'; import { Spacer } from '../../../../../components/ui/spacer'; import { useForm, FormProvider } from 'react-hook-form'; import { Immunization } from 'fhir/r4'; import { Check, FileText } from 'lucide-react'; import { useAuthServiceContext, useImmunizationServiceContext, usePatientServiceContext } from '../../../../../services'; import { AppHeader, AppSpinner, ProfileLayoutContainer, ScrollableTab, HistoryNavigator, FhirImmunization, FhirImmunizationDisplay } from '../../../../../components'; import { PrintableRegion, PrintRecord } from '../../../../../components/ui/print-record'; import { useFhirImmunizationTargetedBroadcast } from '../../../../../hooks'; import { useArchive } from '../../../../../hooks/useArchive'; import ArchiveConfirmModal from '../../../../../components/ArchiveConfirmModal/ArchiveConfirmModal'; import { describeWriteFailure } from '../../../../../utils/fetchFailureMessage'; import { patientCacheGuard } from '../../../../../utils/cacheOwner'; const EditImmunizationPage: React.FC = () => { const { immunizationId } = useParams<{ immunizationId: string }>(); const navigate = useNavigate(); const { userRole, USER_ROLES } = useAuthServiceContext(); const { patientState, encounterState } = usePatientServiceContext(); const { cachedForPatientId: immunizationsOwner, fetchImmunization, transformToFhirImmunization, transformFromFhirImmunization, createImmunization, updateImmunization, archiveImmunization, immunizationsList: rawImmunizationsList } = useImmunizationServiceContext(); // The cache outlives a change of patient: read only the patient on screen. const immunizationsGuard = patientCacheGuard(immunizationsOwner, patientState?.id); const immunizationsList = immunizationsGuard.list(rawImmunizationsList); const [loading, setLoading] = useState(false); const [submitting, setSubmitting] = useState(false); const [success, setSuccess] = useState(); const [error, setError] = useState(); const [immunization, setImmunization] = useState(); const isPatient = [USER_ROLES.PATIENT, USER_ROLES.RELATED_PERSON].includes(userRole as string); const isNew = immunizationId === 'new'; const spacerMargin = '24px'; const methods = useForm({ defaultValues: { status: '', statusReason: null, vaccineCode: null, encounter: null, occurrenceDateTime: '', recorded: '', primarySource: true, reportOrigin: null, location: null, manufacturer: null, lotNumber: '', expirationDate: '', site: null, route: null, doseQuantity: null, performer: [], note: [], reasonCode: [], isSubpotent: false, subpotentReason: [], programEligibility: [], fundingSource: null, reaction: [], protocolApplied: [] } }); const { handleSubmit, reset } = methods; const init = useCallback((immunization: Immunization) => { reset(transformFromFhirImmunization(immunization)); setImmunization(immunization); }, [transformFromFhirImmunization]); useFhirImmunizationTargetedBroadcast({ immunization, immunizationId, onUpdate: init, onDelete: () => navigate('..', { relative: 'path' }) }); const archive = useArchive((reason, note) => archiveImmunization(immunization!, reason, note)); useEffect(() => { const loadImmunization = async () => { if (isNew || immunization) return; const foundImmunization = immunizationsList?.find(i => i.id === immunizationId); if (foundImmunization) { init(foundImmunization); return; } setLoading(true); try { const fetchedImmunization = await fetchImmunization(immunizationId as string); init(fetchedImmunization); } catch (err) { console.error('Error loading immunization:', err); setError('Could not load immunization. Try again.'); } finally { setLoading(false); } }; loadImmunization(); }, [immunization, immunizationsList, immunizationId, fetchImmunization, init]); const onSubmit = async (data: any) => { if (isPatient) return; if (!patientState) { setError('Patient information is missing. Please try again.'); return; } setSubmitting(true); setSuccess(undefined); setError(undefined); try { if (isNew) { await createImmunization(transformToFhirImmunization(data, patientState, encounterState)); navigate('..', { relative: 'path' }); } else { await updateImmunization({ id: immunization?.id, ...transformToFhirImmunization(data, patientState, encounterState) }); } setSuccess(`Immunization ${isNew ? 'created' : 'updated'} successfully.`); setTimeout(() => setSuccess(undefined), 3_000); } catch (err: any) { console.error(`Error ${isNew ? 'creating' : 'updating'} immunization:`, err); setError(describeWriteFailure(err, `Failed to ${isNew ? 'create' : 'update'} immunization`)); } finally { setSubmitting(false); } }; if (loading) { return ( ); } return ( resourceType="Immunization" resourceId={immunizationId || ''}> {(showHistory) => (
{!isNew && ( )} {!isPatient && ( )} {!isNew && !isPatient && ( )} {/* The record has to be able to leave the screen. Without this a patient sending it to somebody not on Akashic photographs a scrolling page or prints the browser window, navigation and all. */} {isPatient && immunization && } {success && ( <> setSuccess(undefined)}> {success} )} {error && ( <> setError(undefined)}>
{error}
)} {/* THE READER GETS THE RECORD, NOT THE FORM SWITCHED OFF. `FhirImmunizationDisplay` already renders this resource for the history viewer, the reference preview and the patient snapshot, so a patient was the one audience shown the edit form instead of the view written for reading it. The old shape wrapped the form in `inert`, which is worse than it looks: the fields stay in the accessibility tree, so a screen reader still reads them as inputs, and a text range over the subtree returns an EMPTY STRING - a patient could not select or copy their own record. */} {isPatient && immunization ? ( undefined}/> ) : ( )} {!isPatient && ( { if (!o) archive.close(); }} resourceLabel="Immunization" submitting={archive.submitting} error={archive.error} onConfirm={async (reason, note) => { if (await archive.submit(reason, note)) { navigate('..', { relative: 'path' }); } }} /> )}
)} ); }; export default EditImmunizationPage;