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 { DetectedIssue } from 'fhir/r4'; import { useDetectedIssueServiceContext, useAuthServiceContext, usePatientServiceContext } from '../services'; import { useFhirDetectedIssueTargetedBroadcast } from '../hooks'; import { FhirDetectedIssue, FhirDetectedIssueDisplay } from '../components'; import { PrintableRegion, PrintRecord } from '../components/ui/print-record'; import { invalidSubmitMessage } from '../utils/forms/invalidSubmitMessage'; interface DetectedIssueModalProps { isOpen: boolean; onClose: () => void; detectedIssue?: DetectedIssue; onSuccess?: (detectedIssue: DetectedIssue) => void; onError?: (error: string) => void; title?: string; } export const DetectedIssueModal: React.FC = ({ isOpen, onClose, detectedIssue, onSuccess, onError, title }) => { const { userRole, USER_ROLES, selectedPractitionerRole } = useAuthServiceContext(); const { patientState } = usePatientServiceContext(); const { transformToFhirDetectedIssue, transformFromFhirDetectedIssue, createDetectedIssue, updateDetectedIssue } = useDetectedIssueServiceContext(); const [submitting, setSubmitting] = useState(false); const [success, setSuccess] = useState(); const [error, setError] = useState(); const isNew = !detectedIssue; // 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 FhirDetectedIssue 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'} Detected Issue`; const methods = useForm({ defaultValues: { identifier: [], status: '', code: null, severity: '', identifiedDateTime: '', author: null, implicated: [], evidence: [], detail: '', reference: '', mitigation: [] } }); 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((detectedIssue: DetectedIssue) => { reset(transformFromFhirDetectedIssue(detectedIssue)); }, [transformFromFhirDetectedIssue, reset]); useFhirDetectedIssueTargetedBroadcast({ detectedIssue, isOpen, onUpdate: init, onDelete: onClose }); useEffect(() => { if (detectedIssue) { init(detectedIssue); } }, [detectedIssue, 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: DetectedIssue; if (isNew) { result = await createDetectedIssue(transformToFhirDetectedIssue(data, patientState, selectedPractitionerRole)); } else { result = await updateDetectedIssue({ id: detectedIssue?.id, ...transformToFhirDetectedIssue(data, patientState) }); } const successMsg = `Detected issue ${isNew ? 'created' : 'updated'} successfully.`; setSuccess(successMsg); onSuccess?.(result); setTimeout(() => { setSuccess(undefined); onClose(); }, 1500); } catch (err: any) { console.error(`Error ${isNew ? 'creating' : 'updating'} detected issue:`, err); const errorMsg = `Failed to ${isNew ? 'create' : 'update'} detected issue. Please try again.`; 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. `FhirDetectedIssueDisplay` 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 && detectedIssue ? ( undefined}/> ) : ( )}
); };