import type { Communication } from 'fhir/r4'; import { looksLikeAnIdentifier, senderLabel } from './senderLabel'; // A message a related person writes for a patient anchors to the patient (sender = Patient/{id}) and the // SERVER stamps who really wrote it, from the writer's own act-as identity; a copy on the request is dropped. // So this reads only that stamp, never the sender's display, which the writing client supplies. export const SENT_ON_BEHALF_BY_URL = 'https://akashichealthrecords.com/fhir/StructureDefinition/sent-on-behalf-by'; // helperReference is the stamped writer, compared by identity; two helpers may share a name. export type OnBehalfOf = { helperReference: string; helperName: string; patientName?: string }; export const onBehalfOf = ( communication: Communication, rosterNames?: Record, ): OnBehalfOf | undefined => { const stamp = communication.extension?.find((extension) => extension?.url === SENT_ON_BEHALF_BY_URL); if (!stamp?.valueReference?.reference?.startsWith('RelatedPerson/')) return undefined; const named = (stamp.valueReference.display ?? '').trim(); // The patient by reference, from the roster: the sender's display is the writing client's word. Left // unnamed when the roster cannot say, so the caller can use the thread's own counterparty. const patient = senderLabel({ display: undefined, reference: communication.sender?.reference, rosterNames }); return { helperReference: stamp.valueReference.reference, helperName: named && !looksLikeAnIdentifier(named) ? named : 'Their helper', ...(patient !== 'Participant' ? { patientName: patient } : {}), }; };