import type { Goal } from 'fhir/r4'; import { ORGANIZATION_TAG_SYSTEM } from './carePlanAuthorship'; import { createdAtOrganization } from './createdAtOrganization'; export interface GoalPractice { /** Written 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; } /** * Where a goal was written, against the practice the reader is acting in. * * A goal is changed by whoever created it. The practice that created it is the goal's * `createdAtOrganization`, falling back to its organization tag when that tag is unambiguous. A goal * the patient set is theirs wherever it was stamped, so it is never "from another practice". When the * owner or the reader's practice cannot be told, it is not claimed either, as with care plans. */ export const goalPractice = ( goal: Goal | undefined, context: { patientId?: string; currentOrganizationId?: string }, ): GoalPractice => { const origin = createdAtOrganization(goal); const tags = (goal?.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 patientSetIt = Boolean(context.patientId) && goal?.expressedBy?.reference === `Patient/${context.patientId}`; return { fromAnotherPractice: !patientSetIt && Boolean(owner && context.currentOrganizationId && owner !== context.currentOrganizationId), ...(practiceName ? { practiceName } : {}), }; };