import type { DiagnosticReport, ServiceRequest } from "fhir/r4"; import { withheldText } from "./returnedPublication"; // One test ordered at one practice and performed by another Akashic laboratory is held twice: the sender's order and // the laboratory's order made from it, then the laboratory's report and the copy returned onto the sender's order. // A person who can read both sees two of everything. These keep one per logical test, by the lineage the server // writes, never by matching names or dates, so two real tests are never folded into one. const ORIGIN_URL = "https://akashichealthrecords.com/fhir/StructureDefinition/lab-order-origin"; /** The sender's order a laboratory's order was made from, when the laboratory's order names one. */ export const originOrderIdOf = (order: ServiceRequest): string | undefined => { const origin = order.extension?.find((extension) => extension.url === ORIGIN_URL); const reference = origin?.extension?.find((part) => part.url === "order")?.valueReference?.reference; return reference?.startsWith("ServiceRequest/") ? reference.slice("ServiceRequest/".length) || undefined : undefined; }; const ORG_TAG = "https://akashichealthrecords.com/fhir/tags/organization"; const practiceOf = (order: ServiceRequest): string | undefined => order.meta?.tag?.find((tag) => tag.system === ORG_TAG)?.code; /** * The orders, one per test where a laboratory order was made from an order also listed: the viewing practice's own * order of the pair is kept, and the sender's when neither or both are theirs. */ export const withoutMirroredOrders = (orders: readonly T[], ownPractice?: string): T[] => { const byId = new Map(orders.map((order) => [order.id, order])); const mirrorKept = (mirror: T, original: T): boolean => Boolean(ownPractice) && practiceOf(mirror) === ownPractice && practiceOf(original) !== ownPractice; return orders.filter((order) => { const from = originOrderIdOf(order); const original = from ? byId.get(from) : undefined; if (original) return mirrorKept(order, original); return !orders.some((other) => originOrderIdOf(other) === order.id && mirrorKept(other, order)); }); }; const RETURNED_PREFIX = "ret-"; /** * The reports, one per result: where the laboratory's report and the copy returned from it are both listed, the copy * filed on the ordering practice's order is kept, unless the server holds it back, when the laboratory's report is. */ export const oneReportPerResult = (reports: readonly T[]): T[] => { const byId = new Map(reports.map((report) => [report.id, report])); return reports.filter((report) => { const id = report.id ?? ""; if (id.startsWith(RETURNED_PREFIX)) { return !(withheldText(report) && byId.has(id.slice(RETURNED_PREFIX.length))); } const copy = byId.get(RETURNED_PREFIX + id); return !copy || Boolean(withheldText(copy)); }); };