import { useEffect } from 'react'; import { CarePlan } from 'fhir/r4'; import { useCarePlanServiceContext, useFhirServiceContext, usePatientServiceContext, useWebSocketServiceContext } from '../services'; import { isArchived } from '../utils/archivedResource'; export const useFhirCarePlanBroadcast = () => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { carePlansList, setCarePlansList } = useCarePlanServiceContext(); const { patientState } = usePatientServiceContext(); const { extractReferenceId } = useFhirServiceContext(); useEffect(() => { if (!patientState) { return; } const handleCarePlanEvent = (cloudEvent: any) => { const carePlan: CarePlan = cloudEvent.data; const eventType = cloudEvent.type; const patientId = extractReferenceId(carePlan.subject); if (patientState.id === patientId) { switch (eventType) { case 'com.akashichealthrecords.fhir.careplan.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. setCarePlansList(prev => prev.some(p => p.id === carePlan.id) ? prev.map(p => p.id === carePlan.id ? carePlan : p) : [...prev, carePlan] ); break; case 'com.akashichealthrecords.fhir.careplan.updated': setCarePlansList(prev => isArchived(carePlan) ? prev.filter(p => p.id !== carePlan.id) : prev.map(p => p.id === carePlan.id ? carePlan : p) ); break; case 'com.akashichealthrecords.fhir.careplan.deleted': setCarePlansList(prev => prev.filter(p => p.id !== carePlan.id)); break; } } }; subscribe('com.akashichealthrecords.fhir.careplan.created', handleCarePlanEvent); subscribe('com.akashichealthrecords.fhir.careplan.updated', handleCarePlanEvent); subscribe('com.akashichealthrecords.fhir.careplan.deleted', handleCarePlanEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.careplan.created', handleCarePlanEvent); unsubscribe('com.akashichealthrecords.fhir.careplan.updated', handleCarePlanEvent); unsubscribe('com.akashichealthrecords.fhir.careplan.deleted', handleCarePlanEvent); }; }, [patientState, subscribe, unsubscribe, extractReferenceId, carePlansList]); };