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 { DeviceRequest } from 'fhir/r4'; import { Check, FileText } from 'lucide-react'; import { AppHeader, AppSpinner, ProfileLayoutContainer, ScrollableTab, HistoryNavigator, FhirDeviceRequest, FhirDeviceRequestDisplay } from '../../../../../components'; import { PrintableRegion, PrintRecord } from '../../../../../components/ui/print-record'; import { useAuthServiceContext, useDeviceRequestServiceContext, usePatientServiceContext } from '../../../../../services'; import { useFhirDeviceRequestTargetedBroadcast } 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 EditDeviceRequestPage: React.FC = () => { const { deviceRequestId } = useParams<{ deviceRequestId: string }>(); const navigate = useNavigate(); const { currentUser, userRole, USER_ROLES, practitionerRoles } = useAuthServiceContext(); const seatStanding = useSeatStanding(); const { patientState, encounterState } = usePatientServiceContext(); const { cachedForPatientId: deviceRequestsOwner, fetchDeviceRequest, transformToFhirDeviceRequest, transformFromFhirDeviceRequest, createDeviceRequest, updateDeviceRequest, archiveDeviceRequest, deviceRequestsList: rawDeviceRequestsList } = useDeviceRequestServiceContext(); // The cache outlives a change of patient: read only the patient on screen. const deviceRequestsGuard = patientCacheGuard(deviceRequestsOwner, patientState?.id); const deviceRequestsList = deviceRequestsGuard.list(rawDeviceRequestsList); const [loading, setLoading] = useState(false); const [submitting, setSubmitting] = useState(false); const [success, setSuccess] = useState(); const [error, setError] = useState(); const [deviceRequest, setDeviceRequest] = useState(); const archive = useArchive((reason, note) => archiveDeviceRequest(deviceRequest!, reason, note)); 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 DeviceRequest 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: 'DeviceRequest', viewerIsStaff: !isPatient, practitionerRoles, }); const mayWrite = !isPatient && seat.mayEdit; const isNew = deviceRequestId === 'new'; const spacerMargin = '24px'; const methods = useForm({ defaultValues: { status: '', intent: '', priority: '', codeCodeableConcept: null, occurrenceType: '', occurrenceDateTime: '', occurrenceTiming: null, reasonCode: [], reasonReference: [], supportingInfo: [], performerType: null, performer: null, note: [] } }); const { handleSubmit, reset } = methods; const init = useCallback((deviceRequest: DeviceRequest) => { reset(transformFromFhirDeviceRequest(deviceRequest)); setDeviceRequest(deviceRequest); }, [transformFromFhirDeviceRequest]); useFhirDeviceRequestTargetedBroadcast({ deviceRequest, deviceRequestId, onUpdate: init, onDelete: () => navigate('..', { relative: 'path' }) }); useEffect(() => { const loadDeviceRequest = async () => { if (isNew || deviceRequest) return; const foundDeviceRequest = deviceRequestsList?.find(dr => dr.id === deviceRequestId); if (foundDeviceRequest) { init(foundDeviceRequest); return; } setLoading(true); try { const fetchedDeviceRequest = await fetchDeviceRequest(deviceRequestId as string); init(fetchedDeviceRequest); } catch (err) { console.error('Error loading device request:', err); setError('Could not load device request. Try again.'); } finally { setLoading(false); } }; loadDeviceRequest(); }, [deviceRequest, deviceRequestsList, deviceRequestId, fetchDeviceRequest, 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 createDeviceRequest(transformToFhirDeviceRequest(data, patientState, encounterState, currentUser?.fhir)); navigate('..', { relative: 'path' }); } else { await updateDeviceRequest({ id: deviceRequest?.id, ...transformToFhirDeviceRequest(data) }); } setSuccess(`Allergy/intolerance ${isNew ? 'created' : 'updated'} successfully.`); setTimeout(() => setSuccess(undefined), 3_000); } catch (err: any) { console.error(`Error ${isNew ? 'creating' : 'updating'} device request:`, err); setError(describeWriteFailure(err, `Failed to ${isNew ? 'create' : 'update'} device request`)); } finally { setSubmitting(false); } }; if (loading) { return ; } return ( resourceType="DeviceRequest" resourceId={deviceRequestId || ''}> {(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 && deviceRequest && }
{success && ( <> setSuccess(undefined)}> {success} )} {error && ( <> setError(undefined)}>
{error}
)} {/* THE READER GETS THE RECORD, NOT THE FORM SWITCHED OFF. `FhirDeviceRequestDisplay` 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 && deviceRequest ? ( undefined}/> ) : ( )} {mayWrite && ( { if (!o) archive.close(); }} resourceLabel="Device Request" submitting={archive.submitting} error={archive.error} onConfirm={async (reason, note) => { if (await archive.submit(reason, note)) { navigate('..', { relative: 'path' }); } }} /> )}
)} ); }; export default EditDeviceRequestPage;