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 { EpisodeOfCare, Organization } from 'fhir/r4'; import { Check, FileText } from 'lucide-react'; import { useAuthServiceContext, useEpisodeOfCareServiceContext, usePatientServiceContext } from '../../../../../services'; import { AppHeader, AppSpinner, HistoryNavigator, ProfileLayoutContainer, ScrollableTab, FhirEpisodeOfCare, FhirEpisodeOfCareDisplay } from '../../../../../components'; import { PrintableRegion, PrintRecord } from '../../../../../components/ui/print-record'; import { useFhirEpisodeOfCareTargetedBroadcast } from '../../../../../hooks'; import { useArchive } from '../../../../../hooks/useArchive'; import ArchiveConfirmModal from '../../../../../components/ArchiveConfirmModal/ArchiveConfirmModal'; import { describeWriteFailure } from '../../../../../utils/fetchFailureMessage'; import { patientCacheGuard } from '../../../../../utils/cacheOwner'; const EditEpisodeOfCarePage: React.FC = () => { const { episodeOfCareId } = useParams<{ episodeOfCareId: string }>(); const navigate = useNavigate(); const { userRole, USER_ROLES, wpOrganization } = useAuthServiceContext(); const { patientState } = usePatientServiceContext(); const { cachedForPatientId: episodesOfCareOwner, fetchEpisodeOfCare, transformToFhirEpisodeOfCare, transformFromFhirEpisodeOfCare, createEpisodeOfCare, updateEpisodeOfCare, archiveEpisodeOfCare, episodesOfCareList: rawEpisodesOfCareList } = useEpisodeOfCareServiceContext(); // The cache outlives a change of patient: read only the patient on screen. const episodesOfCareGuard = patientCacheGuard(episodesOfCareOwner, patientState?.id); const episodesOfCareList = episodesOfCareGuard.list(rawEpisodesOfCareList); const [loading, setLoading] = useState(false); const [submitting, setSubmitting] = useState(false); const [success, setSuccess] = useState(); const [error, setError] = useState(); const [episodeOfCare, setEpisodeOfCare] = useState(); const archive = useArchive((reason, note) => archiveEpisodeOfCare(episodeOfCare!, reason, note)); const isPatient = [USER_ROLES.PATIENT, USER_ROLES.RELATED_PERSON].includes(userRole as string); const isNew = episodeOfCareId === 'new'; const spacerMargin = '24px'; const methods = useForm({ defaultValues: { identifier: [], status: '', statusHistory: [], type: [], diagnosis: [], managingOrganization: null, referralRequest: [], careManager: null, team: [], account: [] } }); const { handleSubmit, reset } = methods; const init = useCallback((episodeOfCare: EpisodeOfCare) => { reset(transformFromFhirEpisodeOfCare(episodeOfCare)); setEpisodeOfCare(episodeOfCare); }, [transformFromFhirEpisodeOfCare]); useFhirEpisodeOfCareTargetedBroadcast({ episodeOfCare, episodeOfCareId, onUpdate: init, onDelete: () => navigate('..', { relative: 'path' }) }); useEffect(() => { const loadEpisodeOfCare = async () => { if (isNew || episodeOfCare) return; const foundEpisodeOfCare = episodesOfCareList?.find(eoc => eoc.id === episodeOfCareId); if (foundEpisodeOfCare) { init(foundEpisodeOfCare); return; } setLoading(true); try { const fetchedEpisodeOfCare = await fetchEpisodeOfCare(episodeOfCareId as string); init(fetchedEpisodeOfCare); } catch (err) { console.error('Error loading episode of care:', err); setError('Could not load episode of care. Try again.'); } finally { setLoading(false); } }; loadEpisodeOfCare(); }, [episodeOfCare, episodesOfCareList, episodeOfCareId, fetchEpisodeOfCare, 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 createEpisodeOfCare(transformToFhirEpisodeOfCare(data, patientState, wpOrganization.current as Organization)); navigate('..', { relative: 'path' }); } else { await updateEpisodeOfCare({ id: episodeOfCare?.id, ...transformToFhirEpisodeOfCare(data) }); } setSuccess(`Episode of care ${isNew ? 'created' : 'updated'} successfully.`); setTimeout(() => setSuccess(undefined), 3_000); } catch (err: any) { console.error(`Error ${isNew ? 'creating' : 'updating'} episode of care:`, err); setError(describeWriteFailure(err, `Failed to ${isNew ? 'create' : 'update'} episode of care`)); } finally { setSubmitting(false); } }; if (loading) { return ( ); } return ( resourceType="EpisodeOfCare" resourceId={episodeOfCareId || ''}> {(showHistory) => (
{!isNew && ( )} {!isPatient && ( )} {!isNew && !isPatient && ( )} {/* 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. */} {isPatient && episodeOfCare && } {success && ( <> setSuccess(undefined)}> {success} )} {error && ( <> setError(undefined)}>
{error}
)} {/* THE READER GETS THE RECORD, NOT THE FORM SWITCHED OFF. `FhirEpisodeOfCareDisplay` 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 && episodeOfCare ? ( undefined}/> ) : ( )} { if (!o) archive.close(); }} resourceLabel="Episode of Care" submitting={archive.submitting} error={archive.error} onConfirm={async (reason, note) => { if (await archive.submit(reason, note)) { navigate('..', { relative: 'path' }); } }} />
)} ); }; export default EditEpisodeOfCarePage;