import React, { 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 { MedicationDispense } from 'fhir/r4'; import { Check, FileText } from 'lucide-react'; import { useAuthServiceContext, useMedicationDispenseServiceContext, usePatientServiceContext } from '../../../../../services'; import { AppHeader, AppSpinner, ProfileLayoutContainer, ScrollableTab, HistoryNavigator, FhirMedicationDispense, FhirMedicationDispenseDisplay } from '../../../../../components'; import { PrintableRegion, PrintRecord } from '../../../../../components/ui/print-record'; import { useFhirMedicationDispenseTargetedBroadcast } from '../../../../../hooks'; import { useArchive } from '../../../../../hooks/useArchive'; import ArchiveConfirmModal from '../../../../../components/ArchiveConfirmModal/ArchiveConfirmModal'; import { describeWriteFailure } from '../../../../../utils/fetchFailureMessage'; import { patientCacheGuard } from '../../../../../utils/cacheOwner'; const EditMedicationDispensePage: React.FC = () => { const { medicationDispenseId } = useParams<{ medicationDispenseId: string }>(); const navigate = useNavigate(); const { userRole, USER_ROLES } = useAuthServiceContext(); const { patientState, encounterState } = usePatientServiceContext(); const { cachedForPatientId: medicationDispensesOwner, fetchMedicationDispense, transformToFhirMedicationDispense, transformFromFhirMedicationDispense, createMedicationDispense, updateMedicationDispense, archiveMedicationDispense, medicationDispensesList: rawMedicationDispensesList, } = useMedicationDispenseServiceContext(); // The cache outlives a change of patient: read only the patient on screen. const medicationDispensesGuard = patientCacheGuard(medicationDispensesOwner, patientState?.id); const medicationDispensesList = medicationDispensesGuard.list(rawMedicationDispensesList); const [loading, setLoading] = useState(false); const [submitting, setSubmitting] = useState(false); const [success, setSuccess] = useState(); const [error, setError] = useState(); const [medicationDispense, setMedicationDispense] = useState(); const isPatient = [USER_ROLES.PATIENT, USER_ROLES.RELATED_PERSON].includes(userRole as string); const isNew = medicationDispenseId === 'new'; const spacerMargin = '24px'; const methods = useForm({ defaultValues: { identifier: [], partOf: [], status: '', statusReasonCodeableConcept: null, category: null, medicationType: '', medicationCodeableConcept: null, medicationReference: null, subject: null, context: null, supportingInformation: [], performer: [], location: null, authorizingPrescription: [], type: null, quantity: null, daysSupply: null, whenPrepared: '', whenHandedOver: '', destination: null, receiver: [], note: [], dosageInstruction: [], substitution: null, detectedIssue: [], eventHistory: [] } }); const { handleSubmit, reset } = methods; const init = useCallback((medicationDispense: MedicationDispense) => { reset(transformFromFhirMedicationDispense(medicationDispense)); setMedicationDispense(medicationDispense); }, [transformFromFhirMedicationDispense]); useFhirMedicationDispenseTargetedBroadcast({ medicationDispense, medicationDispenseId, onUpdate: init, onDelete: () => navigate('..', { relative: 'path' }) }); const archive = useArchive((reason, note) => archiveMedicationDispense(medicationDispense!, reason, note)); useEffect(() => { const loadMedicationDispense = async () => { if (isNew || medicationDispense) return; const foundMedicationDispense = medicationDispensesList?.find(md => md.id === medicationDispenseId); if (foundMedicationDispense) { init(foundMedicationDispense); return; } setLoading(true); try { const fetchedMedicationDispense = await fetchMedicationDispense(medicationDispenseId as string); init(fetchedMedicationDispense); } catch (err) { console.error('Error loading medication dispense:', err); setError('Could not load medication dispense. Try again.'); } finally { setLoading(false); } }; loadMedicationDispense(); }, [medicationDispense, medicationDispensesList, medicationDispenseId, fetchMedicationDispense, 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 createMedicationDispense(transformToFhirMedicationDispense(data, patientState, encounterState)); navigate('..', { relative: 'path' }); } else { await updateMedicationDispense({ id: medicationDispense?.id, ...transformToFhirMedicationDispense(data, patientState) }); } setSuccess(`Medication dispense ${isNew ? 'created' : 'updated'} successfully.`); setTimeout(() => setSuccess(undefined), 3_000); } catch (err: any) { console.error(`Error ${isNew ? 'creating' : 'updating'} medication dispense:`, err); setError(describeWriteFailure(err, `Failed to ${isNew ? 'create' : 'update'} medication dispense`)); } finally { setSubmitting(false); } }; if (loading) { return ( ); } return ( resourceType="MedicationDispense" resourceId={medicationDispenseId || ''}> {(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 && medicationDispense && } {success && ( <> setSuccess(undefined)}> {success} )} {error && ( <> setError(undefined)}>
{error}
)} {/* THE READER GETS THE RECORD, NOT THE FORM SWITCHED OFF. `FhirMedicationDispenseDisplay` 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 && medicationDispense ? ( undefined}/> ) : ( )} { if (!o) archive.close(); }} resourceLabel="Medication Dispense" submitting={archive.submitting} error={archive.error} onConfirm={async (reason, note) => { if (await archive.submit(reason, note)) { navigate('..', { relative: 'path' }); } }} />
)} ); }; export default EditMedicationDispensePage;