import React, { useCallback, useState, useEffect } 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 { MedicationRequest } from 'fhir/r4'; import { Check, FileText } from 'lucide-react'; import { useAuthServiceContext, useMedicationRequestServiceContext, usePatientServiceContext } from '../../../../../services'; import { AppHeader, AppSpinner, ProfileLayoutContainer, ScrollableTab, HistoryNavigator, FhirMedicationRequest, FhirMedicationRequestDisplay } from '../../../../../components'; import { PrintableRegion, PrintRecord } from '../../../../../components/ui/print-record'; import { useFhirMedicationRequestTargetedBroadcast } from '../../../../../hooks'; import { useArchive } from '../../../../../hooks/useArchive'; import ArchiveConfirmModal from '../../../../../components/ArchiveConfirmModal/ArchiveConfirmModal'; import { describeWriteFailure } from '../../../../../utils/fetchFailureMessage'; import { mayEditRecord } from '../../../../../utils/recordEditability'; import { useSeatStanding } from '../../../../../utils/seatStanding'; import { patientCacheGuard } from '../../../../../utils/cacheOwner'; const EditMedicationRequestPage: React.FC = () => { const { medicationRequestId } = useParams<{ medicationRequestId: string }>(); const navigate = useNavigate(); const { currentUser, userRole, USER_ROLES, practitionerRoles } = useAuthServiceContext(); const seatStanding = useSeatStanding(); const { patientState, encounterState } = usePatientServiceContext(); const { cachedForPatientId: medicationRequestsOwner, fetchMedicationRequest, transformToFhirMedicationRequest, transformFromFhirMedicationRequest, createMedicationRequest, updateMedicationRequest, archiveMedicationRequest, medicationRequestsList: rawMedicationRequestsList } = useMedicationRequestServiceContext(); // The cache outlives a change of patient: read only the patient on screen. const medicationRequestsGuard = patientCacheGuard(medicationRequestsOwner, patientState?.id); const medicationRequestsList = medicationRequestsGuard.list(rawMedicationRequestsList); const [loading, setLoading] = useState(false); const [submitting, setSubmitting] = useState(false); const [success, setSuccess] = useState(); const [error, setError] = useState(); const [medicationRequest, setMedicationRequest] = useState(); const isPatient = [USER_ROLES.PATIENT, USER_ROLES.RELATED_PERSON].includes(userRole as string); /* * MAY THIS VIEWER EDIT THIS RECORD - the question the page below is drawn from. * * It used to ask `isPatient`, which is one case of it. Writing a MedicationRequest needs a paid clinician seat, * resolved per request by the server's `callerMayWrite`, and an unseated practitioner passed every * check here: the form opened populated, with Save and Archive, and the write came back refused. A * refusal that arrives after the typing has already spent the work. * * THE LIST IS NOT ENOUGH ON ITS OWN. A control removed only from the list is a client gate with a * door beside it - this page is reachable by URL - so the same question is asked again here. */ const seat = mayEditRecord({ seatStanding, resourceType: 'MedicationRequest', viewerIsStaff: !isPatient, practitionerRoles, }); const mayWrite = !isPatient && seat.mayEdit; const isNew = medicationRequestId === 'new'; const spacerMargin = '24px'; const methods = useForm({ defaultValues: { status: '', intent: '', priority: '', doNotPerform: false, reported: false, medicationCodeableConcept: null, reasonCode: [], note: [], dosageInstruction: [], dispenseRequest: null, substitution: null, requester: [{}] } }); const { handleSubmit, reset } = methods; const init = useCallback((medicationRequest: MedicationRequest) => { reset(transformFromFhirMedicationRequest(medicationRequest)); setMedicationRequest(medicationRequest); }, [transformFromFhirMedicationRequest]); useFhirMedicationRequestTargetedBroadcast({ medicationRequest, medicationRequestId, onUpdate: init, onDelete: () => navigate('..', { relative: 'path' }) }); const archive = useArchive((reason, note) => archiveMedicationRequest(medicationRequest!, reason, note)); useEffect(() => { const loadMedicationRequest = async () => { if (isNew || medicationRequest) return; const foundMedicationRequest = medicationRequestsList?.find(mr => mr.id === medicationRequestId); if (foundMedicationRequest) { init(foundMedicationRequest); return; } setLoading(true); try { const fetchedMedicationRequest = await fetchMedicationRequest(medicationRequestId as string); init(fetchedMedicationRequest); } catch (err) { console.error('Error loading medication request:', err); setError('Could not load medication request. Try again.'); } finally { setLoading(false); } }; loadMedicationRequest(); }, [medicationRequest, medicationRequestsList, medicationRequestId, fetchMedicationRequest, 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 createMedicationRequest(transformToFhirMedicationRequest(data, patientState, encounterState, currentUser?.fhir)); navigate('..', { relative: 'path' }); } else { await updateMedicationRequest({ id: medicationRequest?.id, ...transformToFhirMedicationRequest(data) }); } setSuccess(`Medication request ${isNew ? 'created' : 'updated'} successfully.`); setTimeout(() => setSuccess(undefined), 3_000); } catch (err: any) { console.error(`Error ${isNew ? 'creating' : 'updating'} medication request:`, err); setError(describeWriteFailure(err, `Failed to ${isNew ? 'create' : 'update'} medication request`)); } finally { setSubmitting(false); } }; if (loading) { return ( ); } return ( resourceType="MedicationRequest" resourceId={medicationRequestId || ''}> {(showHistory) => (
{!isNew && ( )} {/* SAID, NOT WITHHELD. A Save that simply disappears reads as a broken screen or as a permission the reader has lost, and both send them to an administrator to check permissions that are already correct. A seat is nameable, and a practice can enable one in a minute. */} {!isPatient && !seat.mayEdit && (

{seat.reason}

)} {mayWrite && ( )} {!isNew && mayWrite && ( )} {/* 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. */} {!mayWrite && medicationRequest && }
{success && ( <> setSuccess(undefined)}> {success} )} {error && ( <> setError(undefined)}>
{error}
)} {/* THE READER GETS THE RECORD, NOT THE FORM SWITCHED OFF. `FhirMedicationRequestDisplay` 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. */} {!mayWrite && medicationRequest ? ( undefined}/> ) : ( )} {mayWrite && ( { if (!o) archive.close(); }} resourceLabel="Medication Request" submitting={archive.submitting} error={archive.error} onConfirm={async (reason, note) => { if (await archive.submit(reason, note)) { navigate('..', { relative: 'path' }); } }} /> )}
)} ); }; export default EditMedicationRequestPage;