import React, { useState, useEffect, useCallback } from 'react'; import { Flex, FlexItem } from '../components/ui/flex'; import { DismissibleAlert } from '../components/ui/dismissible-alert'; import { Modal } from '../components/ui/wp-modal-shim'; import { useForm, FormProvider } from 'react-hook-form'; import { CareTeam, Organization } from 'fhir/r4'; import { useCareTeamServiceContext, useAuthServiceContext, usePatientServiceContext } from '../services'; import { FhirCareTeam, FhirCareTeamDisplay } from '../components'; import { PrintableRegion, PrintRecord } from '../components/ui/print-record'; import { useFhirCareTeamTargetedBroadcast } from '../hooks'; import { describeWriteFailure } from '../utils/fetchFailureMessage'; import { invalidSubmitMessage } from '../utils/forms/invalidSubmitMessage'; interface CareTeamModalProps { isOpen: boolean; onClose: () => void; careTeam?: CareTeam; onSuccess?: (careTeam: CareTeam) => void; onError?: (error: string) => void; title?: string; } export const CareTeamModal: React.FC = ({ isOpen, onClose, careTeam, onSuccess, onError, title }) => { const { userRole, USER_ROLES, wpOrganization } = useAuthServiceContext(); const { patientState, encounterState } = usePatientServiceContext(); const { transformToFhirCareTeam, transformFromFhirCareTeam, createCareTeam, updateCareTeam } = useCareTeamServiceContext(); const [submitting, setSubmitting] = useState(false); const [success, setSuccess] = useState(); const [error, setError] = useState(); const isNew = !careTeam; // A RELATED PERSON IS A PATIENT VIEWER. This read // `userRole === USER_ROLES.PATIENT`, so a parent acting for a child was treated as // staff here while the matching page and FhirCareTeam itself both counted them. // It now decides which of the two renders below the reader gets, so a narrow // predicate would put a proxy into the edit form rather than the record. const isPatient = [USER_ROLES.PATIENT, USER_ROLES.RELATED_PERSON].includes(userRole as string); const modalTitle = title || `${isNew ? 'Create' : 'Edit'} Care Team`; const methods = useForm({ defaultValues: { identifier: [], status: '', category: [], name: '', subject: null, encounter: null, participant: [{ member: [{}] }], reasonCode: [], reasonReference: [], managingOrganization: [], telecom: [], note: [] } }); const { handleSubmit, reset } = methods; // A REFUSED CLICK SAYS SO WHERE IT HAPPENED. The button is in the modal header, above a form that // can be several screens tall, and react-hook-form reports each problem inline beside its field - // so somebody scrolled past the first card saw nothing change at all. This fills the error slot // this modal already has, at the top of the form, next to the button they pressed. const onInvalid = (errors: unknown) => setError(invalidSubmitMessage(errors)); const init = useCallback((careTeam: CareTeam) => { reset(transformFromFhirCareTeam(careTeam)); }, [transformFromFhirCareTeam, reset]); useFhirCareTeamTargetedBroadcast({ careTeam, isOpen, onUpdate: init, onDelete: onClose }); useEffect(() => { if (careTeam) { init(careTeam); } }, [careTeam, init]); const onSubmit = async (data: any) => { if (isPatient) return; if (!patientState) { const errorMsg = 'Patient information is missing. Please try again.'; setError(errorMsg); onError?.(errorMsg); return; } setSubmitting(true); setSuccess(undefined); setError(undefined); try { let result: CareTeam; if (isNew) { result = await createCareTeam(transformToFhirCareTeam(data, patientState, wpOrganization.current as Organization, encounterState)); } else { result = await updateCareTeam({ id: careTeam?.id, ...transformToFhirCareTeam(data, patientState) }, careTeam?.meta?.versionId); } const successMsg = `Care team ${isNew ? 'created' : 'updated'} successfully.`; setSuccess(successMsg); onSuccess?.(result); setTimeout(() => { setSuccess(undefined); onClose(); }, 1500); } catch (err: any) { console.error(`Error ${isNew ? 'creating' : 'updating'} care team:`, err); const errorMsg = describeWriteFailure(err, `Failed to ${isNew ? 'create' : 'update'} care team`); setError(errorMsg); onError?.(errorMsg); } finally { setSubmitting(false); } }; if (!isOpen) return null; return ( {/* A READER GETS PRINT WHERE A WRITER GETS SAVE. This was a disabled Create/Update button, which tells a patient what they may not do - a denial rendered as a dead control, the same failure the record itself had. Print answers the question they actually have: how do I get this to somebody who is not on Akashic. */} {isPatient ? ( ) : ( )} ]} >
{success && ( setSuccess(undefined)} className="mb-4"> {success} )} {error && ( setError(undefined)} className="mb-4"> {error} )}
{/* THE READER GETS THE RECORD, NOT THE FORM SWITCHED OFF. `FhirCareTeamDisplay` 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 && careTeam ? ( undefined}/> ) : ( )}
); };