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 { Task, Organization, Practitioner } from 'fhir/r4'; import { useTaskServiceContext, useAuthServiceContext, usePatientServiceContext } from '../services'; import { FhirTask, FhirTaskDisplay } from '../components'; import { PrintableRegion, PrintRecord } from '../components/ui/print-record'; import { useFhirTaskTargetedBroadcast, useActiveEncounterReference } from '../hooks'; import { describeWriteFailure } from '../utils/fetchFailureMessage'; import { invalidSubmitMessage } from '../utils/forms/invalidSubmitMessage'; interface TaskModalProps { isOpen: boolean; onClose: () => void; task?: Task; onSuccess?: (task: Task) => void; onError?: (error: string) => void; title?: string; } export const TaskModal: React.FC = ({ isOpen, onClose, task, onSuccess, onError, title }) => { const { currentUser, userRole, USER_ROLES, wpOrganization } = useAuthServiceContext(); const { patientState, encounterState } = usePatientServiceContext(); const activeEncounter = useActiveEncounterReference(); const { transformToFhirTask, transformFromFhirTask, createTask, updateTask } = useTaskServiceContext(); const [submitting, setSubmitting] = useState(false); const [success, setSuccess] = useState(); const [error, setError] = useState(); const isNew = !task; // 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 FhirTask 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'} Task`; const methods = useForm({ defaultValues: { encounter: activeEncounter, identifier: [], instantiatesCanonical: [], instantiatesUri: [], basedOn: [], groupIdentifier: null, partOf: [], status: '', statusReason: null, businessStatus: null, intent: '', priority: '', code: null, description: '', focus: [{}], for: null, authoredOn: '', lastModified: '', requester: null, performerType: [], owner: null, location: null, reasonCode: [], reasonReference: [], insurance: [], note: [], relevantHistory: [] } }); 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((task: Task) => { reset(transformFromFhirTask(task)); }, [transformFromFhirTask, reset]); useFhirTaskTargetedBroadcast({ task, isOpen, onUpdate: init, onDelete: onClose }); useEffect(() => { if (task) { init(task); } }, [task, 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 { const practitioner: Practitioner = currentUser?.fhir as Practitioner; let result: Task; if (isNew) { result = await createTask(transformToFhirTask(data, patientState, practitioner, encounterState, wpOrganization.current as Organization)); } else { result = await updateTask({ id: task?.id, ...transformToFhirTask(data) }); } const successMsg = `Task ${isNew ? 'created' : 'updated'} successfully.`; setSuccess(successMsg); onSuccess?.(result); setTimeout(() => { setSuccess(undefined); onClose(); }, 1500); } catch (err: any) { console.error(`Error ${isNew ? 'creating' : 'updating'} task:`, err); const errorMsg = describeWriteFailure(err, `Failed to ${isNew ? 'create' : 'update'} task`); setError(errorMsg); onError?.(errorMsg); } finally { setSubmitting(false); } }; if (!isOpen) return null; return ( {/* No Cancel: this Modal's X already calls onClose. */} {/* A READER GETS PRINT WHERE A WRITER GETS SAVE. A patient reading a record has no use for a Create/Update button - live it lies, disabled it tells them what they may not do, and neither answers the question they 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. `FhirTaskDisplay` 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 && task ? ( undefined}/> ) : ( )}
); };