import type { Invoice, PaymentReconciliation } from 'fhir/r4'; // The server stamps the practice that owns a bill (and each payment against it) as this tag on every write, and // scopes every practice read by it. It is the one answer to "whose bill is this": never the URL, the issuer's // display name or the practice the screen happens to have selected. export const OWNING_PRACTICE_TAG_SYSTEM = 'https://akashichealthrecords.com/fhir/tags/organization'; /** The practice that owns a record, or undefined when it carries none or more than one. */ export const owningPracticeOf = (record: Invoice | PaymentReconciliation | undefined): string | undefined => { const owners = [...new Set((record?.meta?.tag ?? []) .filter((tag) => tag.system === OWNING_PRACTICE_TAG_SYSTEM && tag.code) .map((tag) => tag.code as string))]; return owners.length === 1 ? owners[0] : undefined; }; /** A bill read through practice `practiceId` for patient `patientId` is theirs only when it says so itself. */ export const isBillOf = (invoice: Invoice | undefined, practiceId: string, patientId: string): boolean => owningPracticeOf(invoice) === practiceId && invoice?.subject?.reference === `Patient/${patientId}`;