import { useEffect } from 'react'; import { Encounter } from 'fhir/r4'; import { useEncounterServiceContext, useFhirServiceContext, usePatientServiceContext, useWebSocketServiceContext } from '../services'; import { isArchived } from '../utils/archivedResource'; export const useFhirEncounterBroadcast = () => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { encountersList, setEncountersList } = useEncounterServiceContext(); const { patientState } = usePatientServiceContext(); const { extractReferenceId } = useFhirServiceContext(); useEffect(() => { if (!patientState) { return; } const handleEncounterEvent = (cloudEvent: any) => { const encounter: Encounter = cloudEvent.data; const eventType = cloudEvent.type; const patientId = extractReferenceId(encounter.subject); if (patientState.id === patientId) { switch (eventType) { case 'com.akashichealthrecords.fhir.encounter.created': // The list has two writers: this broadcast, and the service's own refetch after a write // (several of which POLL until the new id appears). Refetch first and the list already holds // the record, so an unconditional append put a SECOND copy of it on screen - observed on a // patient's questionnaire answers, where one submission rendered as two completed forms. // Keeping the broadcast's copy rather than skipping: its body is at least as fresh. setEncountersList(prev => prev.some(p => p.id === encounter.id) ? prev.map(p => p.id === encounter.id ? encounter : p) : [...prev, encounter] ); break; case 'com.akashichealthrecords.fhir.encounter.updated': setEncountersList(prev => isArchived(encounter) ? prev.filter(p => p.id !== encounter.id) : prev.map(p => p.id === encounter.id ? encounter : p) ); break; case 'com.akashichealthrecords.fhir.encounter.deleted': setEncountersList(prev => prev.filter(p => p.id !== encounter.id)); break; } } }; subscribe('com.akashichealthrecords.fhir.encounter.created', handleEncounterEvent); subscribe('com.akashichealthrecords.fhir.encounter.updated', handleEncounterEvent); subscribe('com.akashichealthrecords.fhir.encounter.deleted', handleEncounterEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.encounter.created', handleEncounterEvent); unsubscribe('com.akashichealthrecords.fhir.encounter.updated', handleEncounterEvent); unsubscribe('com.akashichealthrecords.fhir.encounter.deleted', handleEncounterEvent); }; }, [patientState, subscribe, unsubscribe, extractReferenceId, encountersList]); };