import { useEffect } from 'react'; import { Task } from 'fhir/r4'; import { useTaskServiceContext, useFhirServiceContext, usePatientServiceContext, useWebSocketServiceContext } from '../services'; import { isArchived } from '../utils/archivedResource'; export const useFhirTaskBroadcast = () => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { setTasksList } = useTaskServiceContext(); const { patientState } = usePatientServiceContext(); const { extractReferenceId } = useFhirServiceContext(); useEffect(() => { if (!patientState) { return; } const handleTaskEvent = (cloudEvent: any) => { const task: Task = cloudEvent.data; const eventType = cloudEvent.type; if (!task?.id) { return; } const patientId = extractReferenceId(task.for); if (patientState.id === patientId) { switch (eventType) { case 'com.akashichealthrecords.fhir.task.created': setTasksList(prev => [ task, ...prev.filter(existingTask => existingTask.id !== task.id) ]); break; case 'com.akashichealthrecords.fhir.task.updated': setTasksList(prev => { if (isArchived(task)) { return prev.filter(existingTask => existingTask.id !== task.id); } const taskExists = prev.some(existingTask => existingTask.id === task.id); if (!taskExists) { return [task, ...prev]; } return prev.map(existingTask => existingTask.id === task.id ? task : existingTask ); }); break; case 'com.akashichealthrecords.fhir.task.deleted': setTasksList(prev => prev.filter(p => p.id !== task.id)); break; } } }; subscribe('com.akashichealthrecords.fhir.task.created', handleTaskEvent); subscribe('com.akashichealthrecords.fhir.task.updated', handleTaskEvent); subscribe('com.akashichealthrecords.fhir.task.deleted', handleTaskEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.task.created', handleTaskEvent); unsubscribe('com.akashichealthrecords.fhir.task.updated', handleTaskEvent); unsubscribe('com.akashichealthrecords.fhir.task.deleted', handleTaskEvent); }; }, [patientState, subscribe, unsubscribe, extractReferenceId, setTasksList]); };