import { useEffect } from 'react'; import { DocumentReference } from 'fhir/r4'; import { useDocumentReferenceServiceContext, useFhirServiceContext, usePatientServiceContext, useWebSocketServiceContext } from '../services'; import { isArchived } from '../utils/archivedResource'; export const useFhirDocumentReferenceBroadcast = (options?: { isRoot: boolean; }) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { documentReferencesList, setDocumentReferencesList } = useDocumentReferenceServiceContext(); const { patientState } = usePatientServiceContext(); const { extractReferenceId } = useFhirServiceContext(); useEffect(() => { if (!options?.isRoot && !patientState) { return; } const handleDocumentReferenceEvent = (cloudEvent: any) => { const documentReference: DocumentReference = cloudEvent.data; const eventType = cloudEvent.type; switch (eventType) { case 'com.akashichealthrecords.fhir.documentreference.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. setDocumentReferencesList(prev => prev.some(p => p.id === documentReference.id) ? prev.map(p => p.id === documentReference.id ? documentReference : p) : [...prev, documentReference] ); break; case 'com.akashichealthrecords.fhir.documentreference.updated': setDocumentReferencesList(prev => isArchived(documentReference) ? prev.filter(p => p.id !== documentReference.id) : prev.map(p => p.id === documentReference.id ? documentReference : p) ); break; case 'com.akashichealthrecords.fhir.documentreference.deleted': setDocumentReferencesList(prev => prev.filter(p => p.id !== documentReference.id)); break; } }; subscribe('com.akashichealthrecords.fhir.documentreference.created', handleDocumentReferenceEvent); subscribe('com.akashichealthrecords.fhir.documentreference.updated', handleDocumentReferenceEvent); subscribe('com.akashichealthrecords.fhir.documentreference.deleted', handleDocumentReferenceEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.documentreference.created', handleDocumentReferenceEvent); unsubscribe('com.akashichealthrecords.fhir.documentreference.updated', handleDocumentReferenceEvent); unsubscribe('com.akashichealthrecords.fhir.documentreference.deleted', handleDocumentReferenceEvent); }; }, [patientState, subscribe, unsubscribe, extractReferenceId, documentReferencesList]); };