import type { CodeableConcept } from 'fhir/r4'; import { SNOMED_CT_SYSTEM, getOrgRoleByCode, type StaffRoleOption } from './staffRoleCatalog.ts'; /** * Derive the auto-populated `PractitionerRole.specialty` codings from the org roles a staff member holds. * * Extracted from PractitionerRoleService's save path so the REGRESSION TEST can exercise the * real writer rather than a hand-authored fixture. That distinction is the whole point here: the bug this * fixes shipped because every test built its own specialty object, so nothing ever asserted on what the * writer actually emitted. A fixture would have repeated the mistake. * * Contract, unchanged from the inline version except for `text`: * - only roles that carry a `snomedSpecialty` AND are not `specialtyRequired` auto-derive. A * `specialtyRequired` role is generic ("Physician") and the user picks the specialty on the form instead. * - deduped on the SNOMED CODE, so a practitioner holding two roles that share a code gets ONE concept. * Deliberate and unchanged - the `specialtyKey` helpers in the service key on `system|code` too. * * `text` carries the ROLE's display, which is both FHIR-correct and the better value - see the long note * at the call site in PractitionerRoleService.tsx for why. * * `coding[0].display` IS DELIBERATELY ABSENT AND IS LOAD-BEARING. 19 of the 40 SNOMED codes in the * catalog are wrong - a dentist's resolves to "Transport distance too great" - and the missing display is * the only reason none of that reaches a screen. The reason lives in full on `snomedSpecialty` in * `staffRoleCatalog.ts`; the tripwire is `__tests__/autoSpecialtyDisplayMask.test.ts`. * (This docstring used to send the reader to the call site "for why coding[0].display is left absent". * That note is about the blank `text` and says nothing about the display - a pointer to an explanation * nobody ever wrote, which reads as an unfinished field rather than a deliberate one.) */ export function deriveAutoSpecialtyCodings( organizationRoles: Array | undefined | null>, ): CodeableConcept[] { const seenCodes = new Set(); const codings: CodeableConcept[] = []; for (const roleOption of organizationRoles ?? []) { const catalogEntry = roleOption?.code ? getOrgRoleByCode(roleOption.code) : undefined; if (!catalogEntry?.snomedSpecialty || catalogEntry.specialtyRequired) continue; const snomedCode = catalogEntry.snomedSpecialty; if (seenCodes.has(snomedCode)) continue; seenCodes.add(snomedCode); codings.push({ coding: [{ system: SNOMED_CT_SYSTEM, code: snomedCode }], text: catalogEntry.display, }); } return codings; }