/** * Reads and writes the review marker a diagnostic order carries as an extension, so a result can * name who reviewed it and when without a second resource to keep in step. */ import type { ServiceRequest } from "fhir/r4"; import { formatDateTime } from "./dateUtils"; export const DIAGNOSTIC_ORDER_REVIEW_EXTENSION_URL = "https://akashichealthrecords.com/fhir/StructureDefinition/diagnostic-order-review"; export interface DiagnosticOrderReview { reference: string; display?: string; at: string; } export const readDiagnosticOrderReview = ( order: ServiceRequest | undefined, ): DiagnosticOrderReview | undefined => { for (const extension of order?.extension ?? []) { if (extension.url !== DIAGNOSTIC_ORDER_REVIEW_EXTENSION_URL) continue; const children = extension.extension ?? []; const by = children.find((child) => child.url === "by")?.valueReference; const at = children.find((child) => child.url === "at")?.valueDateTime; if (!by?.reference || !at) continue; return { reference: by.reference, display: by.display, at }; } return undefined; }; export const orderingPractitionerReference = (order: ServiceRequest): string | undefined => { const reference = order.requester?.reference; return reference?.startsWith("Practitioner/") ? reference : undefined; }; export const mayMarkReviewed = ( order: ServiceRequest, practitionerId: string | undefined, ): boolean => { if (!practitionerId) return false; const ours = orderingPractitionerReference(order); // Inbound paper names the outside practice, not a clinician here; any of ours may close it. return ours ? ours === `Practitioner/${practitionerId}` : true; }; export const describeReviewSignature = (review: DiagnosticOrderReview): string => review.display ? `Reviewed by ${review.display} on ${formatDateTime(review.at)}` : `Reviewed on ${formatDateTime(review.at)}`; export const describeReviewPending = (order: ServiceRequest): string => { if (!orderingPractitionerReference(order)) { return "Waiting on a clinician here to review this"; } const who = order.requester?.display?.trim(); return who ? `Waiting on ${who} to review this` : "Waiting on the clinician who ordered it to review this"; }; export const withReview = ( order: ServiceRequest, review: DiagnosticOrderReview, ): ServiceRequest => ({ ...order, extension: [ ...(order.extension ?? []).filter( (extension) => extension.url !== DIAGNOSTIC_ORDER_REVIEW_EXTENSION_URL, ), { url: DIAGNOSTIC_ORDER_REVIEW_EXTENSION_URL, extension: [ { url: "by", valueReference: review.display ? { reference: review.reference, display: review.display } : { reference: review.reference }, }, { url: "at", valueDateTime: review.at }, ], }, ], });