import { isAsOfIncomplete } from '../utils/searchTruncation'; import { useEffect, useState, useCallback } from 'react'; import { usePatientServiceContext, useNutritionOrderServiceContext } from '../services'; import { describeFetchFailure } from '../utils/fetchFailureMessage'; import { patientCacheGuard } from '../utils/cacheOwner'; interface UseFhirNutritionOrdersOptions { autoLoad?: boolean; errorMessage?: string; forceReload?: boolean; } interface UseFhirNutritionOrdersReturn { /** Served as of a cutoff and not in full: what it left out is unknown, never none. */ incomplete: boolean; loading: boolean; error: string | undefined; loadNutritionOrders: () => Promise; clearError: () => void; nutritionOrdersBundle: ReturnType['nutritionOrdersBundle']; nutritionOrdersList: ReturnType['nutritionOrdersList']; } export const useFhirNutritionOrders = (options: UseFhirNutritionOrdersOptions = {}): UseFhirNutritionOrdersReturn => { const { autoLoad = true, errorMessage = "Failed to load nutrition orders", forceReload = false } = options; const { patientState } = usePatientServiceContext(); const { cachedForPatientId, fetchNutritionOrdersWithPolling, nutritionOrdersBundle, nutritionOrdersList } = useNutritionOrderServiceContext(); const [loading, setLoading] = useState(false); const [error, setError] = useState(); const loadNutritionOrders = useCallback(async () => { if (!patientState) { return; } setLoading(true); setError(undefined); try { await fetchNutritionOrdersWithPolling(patientState); } catch (err) { console.error('Failed to load nutrition orders:', err); setError(describeFetchFailure(err, errorMessage)); } finally { setLoading(false); } }, [patientState, fetchNutritionOrdersWithPolling, 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 (!nutritionOrdersBundle || cachedForPatientId !== patientState.id || forceReload) { loadNutritionOrders(); } }, [autoLoad, patientState, nutritionOrdersBundle, cachedForPatientId, forceReload, loadNutritionOrders]); // The cache outlives a change of patient: hand out only the patient asked about. const guard = patientCacheGuard(cachedForPatientId, patientState?.id); return { loading: guard.loading(loading, Boolean(error)), error, loadNutritionOrders, clearError, // Served as of a cutoff and not in full: what it left out is unknown, never none. incomplete: isAsOfIncomplete(guard.bundle(nutritionOrdersBundle, null)), nutritionOrdersBundle: guard.bundle(nutritionOrdersBundle, null), nutritionOrdersList: guard.list(nutritionOrdersList) }; };