import type { Practitioner, PractitionerRole, Schedule } from 'fhir/r4'; import { formatFhirHumanName } from '../fhirHumanName'; import { schedulePractitionerId } from './schedulePractitioner'; // A Schedule actor display is a snapshot from when the block was saved, so it goes stale when the name // changes later. The saved display is only the fallback for a record the viewer cannot read. export const schedulePractitionerName = ( schedule: Schedule, practitioners: Practitioner[], fallback = 'Practitioner not recorded', // The schedule's role: its practitioner names a schedule that carries no Practitioner actor of its own. role?: PractitionerRole | null, ): string => { const ref = schedule.actor?.find((a) => a.reference?.startsWith('Practitioner/')); const id = schedulePractitionerId(schedule, role); const current = id ? practitioners.find((p) => p.id === id) : undefined; const roleName = id && role?.practitioner?.reference === `Practitioner/${id}` ? role.practitioner.display : undefined; return formatFhirHumanName(current?.name).trim() || ref?.display || roleName || fallback; };