import { useEffect } from 'react'; import { Practitioner } from 'fhir/r4'; import { usePractitionerServiceContext, useFhirServiceContext, useWebSocketServiceContext } from '../services'; export const useFhirPractitionerBroadcast = () => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { setPractitionersList } = usePractitionerServiceContext(); const { extractReferenceId } = useFhirServiceContext(); useEffect(() => { const handlePractitionerEvent = (cloudEvent: any) => { const eventType = cloudEvent.type; switch (eventType) { case 'com.akashichealthrecords.fhir.practitioner.created': const { practitioner: createdPractitioner, practitionerRole } = cloudEvent.data; if (createdPractitioner?.id) { console.log('Processing Practitioner create event for practitioner:', createdPractitioner.id); // Same race as every other created append, one level deeper: the id // lives at `.practitioner.id`, which is exactly where the `updated` arm below // already looks. Without this a practitioner the staff-list refetch had already // brought in appeared twice in the directory. // // SKIPS rather than replaces, which is the opposite choice to the other hooks // and is deliberate: this event carries at most ONE role, so the entry built here // is `roles: [thatOne]`. Replacing an existing entry would throw away every other // role the refetch already knew about - trading a duplicate row for a silently // truncated one, which is harder to notice and worse. setPractitionersList(prev => prev.some(entry => entry.practitioner.id === createdPractitioner.id) ? prev : [ ...prev, { practitioner: createdPractitioner, roles: practitionerRole ? [practitionerRole] : [] } ] ); } break; case 'com.akashichealthrecords.fhir.practitioner.updated': const updatedPractitioner: Practitioner = cloudEvent.data; if (updatedPractitioner?.id) { console.log('Processing Practitioner update event for practitioner:', updatedPractitioner.id); setPractitionersList(prev => prev.map(practitionerWithRoles => practitionerWithRoles.practitioner.id === updatedPractitioner.id ? { ...practitionerWithRoles, practitioner: updatedPractitioner } : practitionerWithRoles ) ); } break; } }; subscribe('com.akashichealthrecords.fhir.practitioner.created', handlePractitionerEvent); subscribe('com.akashichealthrecords.fhir.practitioner.updated', handlePractitionerEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.practitioner.created', handlePractitionerEvent); unsubscribe('com.akashichealthrecords.fhir.practitioner.updated', handlePractitionerEvent); }; }, [subscribe, unsubscribe, extractReferenceId, setPractitionersList]); };