import { useCallback } from 'react'; import type { Bundle, Patient, Resource } from 'fhir/r4'; import { useOptionalAllergyIntoleranceServiceContext } from '../../../services/AllergyIntoleranceService'; import { useOptionalConditionServiceContext } from '../../../services/ConditionService'; import { useOptionalImmunizationServiceContext } from '../../../services/ImmunizationService'; import { useOptionalMedicationRequestServiceContext } from '../../../services/MedicationRequestService'; import { useOptionalObservationServiceContext } from '../../../services/ObservationService'; import { useOptionalProcedureServiceContext } from '../../../services/ProcedureService'; import { useOptionalRiskAssessmentServiceContext } from '../../../services/RiskAssessmentService'; import { filedKeysFor } from '../../../utils/filedToEncounter'; import type { ProposalKind } from '../../../utils/recordProposals'; /** * What the record shows as already filed to this visit, as proposal keys, so a re-check after a reload * does not offer it again. Reads only the kinds the note proposed; a kind that cannot be read, or has no * provider here, is left out. */ export const useFiledToEncounter = () => { const allergy = useOptionalAllergyIntoleranceServiceContext(); const condition = useOptionalConditionServiceContext(); const immunization = useOptionalImmunizationServiceContext(); const medication = useOptionalMedicationRequestServiceContext(); const observation = useOptionalObservationServiceContext(); const procedure = useOptionalProcedureServiceContext(); const risk = useOptionalRiskAssessmentServiceContext(); return useCallback(async (kinds: ProposalKind[], patient: Patient, encounterId: string): Promise> => { const readers: Partial Promise> | undefined>> = { allergy: () => allergy?.fetchAllergyIntolerances(patient) as Promise> | undefined, condition: () => condition?.fetchConditions(patient) as Promise> | undefined, immunization: () => immunization?.fetchImmunizations(patient) as Promise> | undefined, medication: () => medication?.fetchMedicationRequests(patient) as Promise> | undefined, observation: () => observation?.fetchObservations(patient) as Promise> | undefined, procedure: () => procedure?.fetchProcedures(patient) as Promise> | undefined, risk: () => risk?.fetchRiskAssessments(patient) as Promise> | undefined, }; const keys = new Set(); await Promise.all([...new Set(kinds)].map(async (kind) => { const read = readers[kind]; if (!read) return; try { const bundle = await read(); if (!bundle) return; const resources = (bundle.entry ?? []).map((entry) => entry.resource).filter(Boolean) as Resource[]; filedKeysFor(kind, resources, encounterId).forEach((key) => keys.add(key)); } catch { // Unknown is not "nothing filed", but it must not block the offer; the clinician still decides. } })); return keys; }, [allergy, condition, immunization, medication, observation, procedure, risk]); };