import { useEffect } from 'react'; import { DetectedIssue } from 'fhir/r4'; import { useDetectedIssueServiceContext, useFhirServiceContext, usePatientServiceContext, useWebSocketServiceContext } from '../services'; import { isArchived } from '../utils/archivedResource'; export const useFhirDetectedIssueBroadcast = () => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { detectedIssuesList, setDetectedIssuesList } = useDetectedIssueServiceContext(); const { patientState } = usePatientServiceContext(); const { extractReferenceId } = useFhirServiceContext(); useEffect(() => { if (!patientState) { return; } const handleDetectedIssueEvent = (cloudEvent: any) => { const detectedIssue: DetectedIssue = cloudEvent.data; const eventType = cloudEvent.type; const patientId = extractReferenceId(detectedIssue.patient); if (patientState.id === patientId) { switch (eventType) { case 'com.akashichealthrecords.fhir.detectedissue.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. setDetectedIssuesList(prev => prev.some(p => p.id === detectedIssue.id) ? prev.map(p => p.id === detectedIssue.id ? detectedIssue : p) : [...prev, detectedIssue] ); break; case 'com.akashichealthrecords.fhir.detectedissue.updated': setDetectedIssuesList(prev => isArchived(detectedIssue) ? prev.filter(p => p.id !== detectedIssue.id) : prev.map(p => p.id === detectedIssue.id ? detectedIssue : p) ); break; case 'com.akashichealthrecords.fhir.detectedissue.deleted': setDetectedIssuesList(prev => prev.filter(p => p.id !== detectedIssue.id)); break; } } }; subscribe('com.akashichealthrecords.fhir.detectedissue.created', handleDetectedIssueEvent); subscribe('com.akashichealthrecords.fhir.detectedissue.updated', handleDetectedIssueEvent); subscribe('com.akashichealthrecords.fhir.detectedissue.deleted', handleDetectedIssueEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.detectedissue.created', handleDetectedIssueEvent); unsubscribe('com.akashichealthrecords.fhir.detectedissue.updated', handleDetectedIssueEvent); unsubscribe('com.akashichealthrecords.fhir.detectedissue.deleted', handleDetectedIssueEvent); }; }, [patientState, subscribe, unsubscribe, extractReferenceId, detectedIssuesList]); };