import { useChartRecordStanding, useFreshAfterReauthorization, type RecordAccessStanding, type RecordFreshness } from './useRecordAccessStanding'; import { isAsOfIncomplete, isServedAtCutoff } from '../utils/searchTruncation'; import { useEffect, useState, useCallback } from 'react'; import { usePatientServiceContext, useImmunizationRecommendationServiceContext } from '../services'; import { describeFetchFailure } from '../utils/fetchFailureMessage'; import { patientCacheGuard } from '../utils/cacheOwner'; interface UseFhirImmunizationRecommendationsOptions { /** The record standing to answer to; the open chart's when not given. */ standing?: RecordAccessStanding; autoLoad?: boolean; errorMessage?: string; forceReload?: boolean; } interface UseFhirImmunizationRecommendationsReturn { /** After a reauthorization, whether this list has been read again under it. */ freshness: RecordFreshness; /** Served as of a cutoff and not in full: what it left out is unknown, never none. */ incomplete: boolean; loading: boolean; error: string | undefined; /** * - was the server actually asked? * * This hook early-returns while `patientState` is unresolved, so `setLoading(true)` never runs and * the effect never fires. The caller is then holding `loading: false` - `error: undefined` - an * empty list - **indistinguishable from a load that succeeded and found nothing** - and * `ResourceListStatus` says *"No X found."* about a question nobody asked. * Only the hook knows which of the two it is in, so it reports it. */ attempted: boolean; /** The service's list is this patient's. Anything else is another patient's, never this one's data. */ listIsThisPatients: boolean; loadImmunizationRecommendations: () => Promise; clearError: () => void; immunizationRecommendationsBundle: ReturnType['immunizationRecommendationsBundle']; immunizationRecommendationsList: ReturnType['immunizationRecommendationsList']; } export const useFhirImmunizationRecommendations = (options: UseFhirImmunizationRecommendationsOptions = {}): UseFhirImmunizationRecommendationsReturn => { const { autoLoad = true, errorMessage = "Failed to load immunization recommendations", forceReload = false } = options; const { patientState } = usePatientServiceContext(); const { cachedForPatientId, fetchImmunizationRecommendationsWithPolling, listRead, immunizationRecommendationsBundle, immunizationRecommendationsList } = useImmunizationRecommendationServiceContext(); // After a reauthorization this list is read again past every cache; until then it is not taken for current. const chartStanding = useChartRecordStanding().standing; const freshness = useFreshAfterReauthorization(options.standing ?? chartStanding, () => ( patientState ? fetchImmunizationRecommendationsWithPolling(patientState, true) : Promise.reject(new Error('No patient to read.'))), { resource: 'ImmunizationRecommendation', patientId: patientState?.id, listRead, servedAtCutoff: isServedAtCutoff(immunizationRecommendationsBundle) }); const [loading, setLoading] = useState(false); const [error, setError] = useState(); const loadImmunizationRecommendations = useCallback(async () => { if (!patientState) { return; } setLoading(true); setError(undefined); try { await fetchImmunizationRecommendationsWithPolling(patientState); } catch (err) { console.error('Failed to load immunization recommendations:', err); setError(describeFetchFailure(err, errorMessage)); } finally { setLoading(false); } }, [patientState, fetchImmunizationRecommendationsWithPolling, errorMessage]); const clearError = useCallback(() => { setError(undefined); }, []); useEffect(() => { if (!autoLoad) return; if (!patientState) return; // A bundle belonging to SOMEBODY ELSE is not a reason not to ask. This used to fire only when // there was no bundle at all, so moving between two charts left the previous patient's list in // place, with no request and nothing on screen to say it was not theirs. // NOT a refetch on every navigation: same patient, bundle loaded, no request. if (!immunizationRecommendationsBundle || cachedForPatientId !== patientState.id || forceReload) { loadImmunizationRecommendations(); } }, [autoLoad, patientState, immunizationRecommendationsBundle, cachedForPatientId, forceReload, loadImmunizationRecommendations]); // The cache outlives a change of patient: hand out only the patient asked about. const guard = patientCacheGuard(cachedForPatientId, patientState?.id); return { freshness, loading: guard.loading(loading, Boolean(error)), error, // Derived from the SAME condition the early returns above test, never tracked separately: a // hand-set flag goes stale the first time somebody adds a third reason to bail, and silently. attempted: Boolean(patientState), listIsThisPatients: cachedForPatientId !== undefined && cachedForPatientId === patientState?.id, loadImmunizationRecommendations, clearError, // Served as of a cutoff and not in full: what it left out is unknown, never none. incomplete: isAsOfIncomplete(guard.bundle(immunizationRecommendationsBundle, null)), immunizationRecommendationsBundle: guard.bundle(immunizationRecommendationsBundle, null), immunizationRecommendationsList: guard.list(immunizationRecommendationsList) }; };