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 { QuestionnaireResponse } from 'fhir/r4'; import { useQuestionnaireResponseServiceContext, useAuthServiceContext, usePatientServiceContext } from '../services'; import { FhirQuestionnaireResponse, FhirQuestionnaireResponseDisplay } from '../components'; import { PrintableRegion, PrintRecord } from '../components/ui/print-record'; import { useFhirQuestionnaireResponseTargetedBroadcast } from '../hooks'; import { describeWriteFailure } from '../utils/fetchFailureMessage'; import { invalidSubmitMessage } from '../utils/forms/invalidSubmitMessage'; interface QuestionnaireResponseModalProps { isOpen: boolean; onClose: () => void; questionnaireResponse?: QuestionnaireResponse; onSuccess?: (questionnaireResponse: QuestionnaireResponse) => void; onError?: (error: string) => void; title?: string; } export const QuestionnaireResponseModal: React.FC = ({ isOpen, onClose, questionnaireResponse, onSuccess, onError, title }) => { const { userRole, USER_ROLES } = useAuthServiceContext(); const { patientState } = usePatientServiceContext(); const { transformToFhirQuestionnaireResponse, transformFromFhirQuestionnaireResponse, createQuestionnaireResponse, updateQuestionnaireResponse } = useQuestionnaireResponseServiceContext(); const [submitting, setSubmitting] = useState(false); const [success, setSuccess] = useState(); const [error, setError] = useState(); const isNew = !questionnaireResponse; // 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 FhirQuestionnaireResponse 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'} Questionnaire Response`; const methods = useForm({ defaultValues: {} }); 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((questionnaireResponse: QuestionnaireResponse) => { reset(transformFromFhirQuestionnaireResponse(questionnaireResponse)); }, [transformFromFhirQuestionnaireResponse, reset]); useFhirQuestionnaireResponseTargetedBroadcast({ questionnaireResponse, isOpen, onUpdate: init, onDelete: onClose }); useEffect(() => { if (questionnaireResponse) { init(questionnaireResponse); } }, [questionnaireResponse, init]); const onSubmit = async (data: any) => { 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: QuestionnaireResponse; if (isNew) { result = await createQuestionnaireResponse(transformToFhirQuestionnaireResponse(data)); } else { result = await updateQuestionnaireResponse({ ...transformToFhirQuestionnaireResponse(data), id: questionnaireResponse?.id, item: questionnaireResponse?.item, authored: questionnaireResponse?.authored }); } const successMsg = `Questionnaire response ${isNew ? 'created' : 'updated'} successfully.`; setSuccess(successMsg); onSuccess?.(result); setTimeout(() => { setSuccess(undefined); onClose(); }, 1500); } catch (err: any) { console.error(`Error ${isNew ? 'creating' : 'updating'} questionnaire response:`, err); const errorMsg = describeWriteFailure(err, `Failed to ${isNew ? 'create' : 'update'} questionnaire response`); setError(errorMsg); onError?.(errorMsg); } finally { setSubmitting(false); } }; if (!isOpen) return null; return ( {/* 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. `FhirQuestionnaireResponseDisplay` 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 && questionnaireResponse ? ( undefined}/> ) : ( )}
); };