import type { Observation } from 'fhir/r4'; import { ORGANIZATION_TAG_SYSTEM } from './carePlanAuthorship'; import { createdAtOrganization } from './createdAtOrganization'; export interface ObservationPractice { /** Recorded at a practice other than the reader's, so it is shown and not editable here. */ fromAnotherPractice: boolean; /** That practice's name, when the record carries one. */ practiceName?: string; /** Why it cannot be changed here, ready to render. */ readOnlyReason?: string; } /** * Mirrors the server's `evaluateObservationPracticeAuthorship`, so a surface never hides an edit the server allows. When * either practice cannot be told, nothing is claimed. */ export const observationPractice = ( observation: Observation | undefined, currentOrganizationId: string | undefined, ): ObservationPractice => { const origin = createdAtOrganization(observation); const tags = (observation?.meta?.tag ?? []).filter((tag) => tag.system === ORGANIZATION_TAG_SYSTEM && tag.code); const owner = origin.id ?? (tags.length === 1 ? tags[0].code : undefined); // The server writes `Organization/` as the display when it could not read the name. const practiceName = origin.name && !origin.name.startsWith('Organization/') ? origin.name : undefined; const patientRecordedIt = (observation?.performer ?? []).some((performer) => performer.reference?.startsWith('Patient/') || performer.reference?.startsWith('RelatedPerson/')); const fromAnotherPractice = !patientRecordedIt && Boolean(owner && currentOrganizationId && owner !== currentOrganizationId); return { fromAnotherPractice, ...(practiceName ? { practiceName } : {}), ...(fromAnotherPractice ? { readOnlyReason: practiceName ? `This reading was recorded at ${practiceName}. Only that practice can change it - you can still read it.` : 'This reading was recorded at another practice. Only the practice that recorded it can change it - you can still read it.', } : {}), }; };