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 { RiskAssessment } from 'fhir/r4'; import { Check, FileText } from 'lucide-react'; import { useAuthServiceContext, usePatientServiceContext, useRiskAssessmentServiceContext } from '../../../../../services'; import { AppHeader, AppSpinner, ProfileLayoutContainer, ScrollableTab, HistoryNavigator, FhirRiskAssessment, FhirRiskAssessmentDisplay } from '../../../../../components'; import { PrintableRegion, PrintRecord } from '../../../../../components/ui/print-record'; import { useFhirRiskAssessmentTargetedBroadcast } 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 EditRiskAssessmentPage: React.FC = () => { const { riskAssessmentId } = useParams<{ riskAssessmentId: string }>(); const navigate = useNavigate(); const { currentUser, userRole, USER_ROLES, practitionerRoles } = useAuthServiceContext(); const seatStanding = useSeatStanding(); const { patientState, encounterState } = usePatientServiceContext(); const { cachedForPatientId: riskAssessmentsOwner, fetchRiskAssessment, transformToFhirRiskAssessment, transformFromFhirRiskAssessment, createRiskAssessment, updateRiskAssessment, archiveRiskAssessment, riskAssessmentsList: rawRiskAssessmentsList } = useRiskAssessmentServiceContext(); // The cache outlives a change of patient: read only the patient on screen. const riskAssessmentsGuard = patientCacheGuard(riskAssessmentsOwner, patientState?.id); const riskAssessmentsList = riskAssessmentsGuard.list(rawRiskAssessmentsList); const [loading, setLoading] = useState(false); const [submitting, setSubmitting] = useState(false); const [success, setSuccess] = useState(); const [error, setError] = useState(); const [riskAssessment, setRiskAssessment] = useState(); const archive = useArchive((reason, note) => archiveRiskAssessment(riskAssessment!, 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 RiskAssessment 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: 'RiskAssessment', viewerIsStaff: !isPatient, practitionerRoles, }); const mayWrite = !isPatient && seat.mayEdit; const isNew = riskAssessmentId === 'new'; const spacerMargin = '24px'; const methods = useForm({ defaultValues: { identifier: [], basedOn: [], parent: null, status: '', method: null, code: null, subject: null, encounter: null, occurrenceDateTime: '', condition: null, performer: [{}], reasonCode: [], reasonReference: [], basis: [], prediction: [], mitigation: '', note: [] } }); const { handleSubmit, reset } = methods; const init = useCallback((riskAssessment: RiskAssessment) => { reset(transformFromFhirRiskAssessment(riskAssessment)); setRiskAssessment(riskAssessment); }, [transformFromFhirRiskAssessment]); useFhirRiskAssessmentTargetedBroadcast({ riskAssessment, riskAssessmentId, onUpdate: init, onDelete: () => navigate('..', { relative: 'path' }) }); useEffect(() => { const loadRiskAssessment = async () => { if (isNew || riskAssessment) return; const foundRiskAssessment = riskAssessmentsList?.find(ra => ra.id === riskAssessmentId); if (foundRiskAssessment) { init(foundRiskAssessment); return; } setLoading(true); try { const fetchedRiskAssessment = await fetchRiskAssessment(riskAssessmentId as string); init(fetchedRiskAssessment); } catch (err) { console.error('Error loading risk assessment:', err); setError('Could not load risk assessment. Try again.'); } finally { setLoading(false); } }; loadRiskAssessment(); }, [riskAssessment, riskAssessmentsList, riskAssessmentId, fetchRiskAssessment, 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 createRiskAssessment(transformToFhirRiskAssessment(data, patientState, encounterState, currentUser?.fhir)); navigate('..', { relative: 'path' }); } else { await updateRiskAssessment({ id: riskAssessment?.id, ...transformToFhirRiskAssessment(data) }); } setSuccess(`Risk assessment ${isNew ? 'created' : 'updated'} successfully.`); setTimeout(() => setSuccess(undefined), 3_000); } catch (err: any) { console.error(`Error ${isNew ? 'creating' : 'updating'} risk assessment:`, err); setError(describeWriteFailure(err, `Failed to ${isNew ? 'create' : 'update'} risk assessment`)); } finally { setSubmitting(false); } }; if (loading) { return ( ); } return ( resourceType="RiskAssessment" resourceId={riskAssessmentId || ''}> {(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 && riskAssessment && }
{success && ( <> setSuccess(undefined)}> {success} )} {error && ( <> setError(undefined)}>
{error}
)} {/* THE READER GETS THE RECORD, NOT THE FORM SWITCHED OFF. `FhirRiskAssessmentDisplay` 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 && riskAssessment ? ( undefined}/> ) : ( )} {mayWrite && ( { if (!o) archive.close(); }} resourceLabel="Risk Assessment" submitting={archive.submitting} error={archive.error} onConfirm={async (reason, note) => { if (await archive.submit(reason, note)) { navigate('..', { relative: 'path' }); } }} /> )}
)} ); }; export default EditRiskAssessmentPage;