import { useEffect, useRef } from "react"; import type { ServiceRequest } from "fhir/r4"; import { TriangleAlert } from "lucide-react"; import { RowPriority, RowStatus } from "../../../../components/ui/row-meta"; import { Button } from "../../../../components/ui/button"; import { CardContent } from "../../../../components/ui/card"; import { LabReports } from "../../../../components/LabReports/LabReports"; import { ReportAddenda } from "../../../../components/LabReports/ReportAddenda"; import { SignedReportText } from "../../../../components/LabReports/SignedReportText"; import type { OrderResultDetail } from "../../../../hooks/useOrderLabReports.ts"; import { qualityControlAtRelease, qualityControlNotice } from "../../../../utils/qualityControlNotice"; import { formatDateTime } from "../../../../utils/dateUtils"; import { openOrderRefusal, specimenRefusal } from "../../../../utils/orderRefusal"; import { ARCHIVE_REASON_LABELS, isArchived, readArchiveDetail } from "../../../../utils/archivedResource"; import { canWithdrawDiagnosticOrder, DIAGNOSTIC_ORDER_STATE_LABELS, type DiagnosticOrderState, } from "../../../../utils/diagnosticOrderQueue"; import { describeReviewPending, describeReviewSignature, mayMarkReviewed, orderingPractitionerReference, readDiagnosticOrderReview, } from "../../../../utils/diagnosticOrderReview"; /** * One ordered test, as the clinician who ordered it sees it. * * ITS OWN FILE BECAUSE IT IS DRAWN IN TWO PLACES. A test ordered on its own is a card; a test ordered * with others is a line inside the panel's card. The controls and the wording have to be identical in * both -- `Mark reviewed` cannot be undone, and a row that behaves differently depending on how it was * ordered is the kind of difference somebody acts on without noticing. * * THE CARD IS THE CALLER'S. A panel draws one card around several of these; a single order draws one * around one. Nesting cards would put a border inside a border for nothing. */ const LABORATORY_CODE = "108252007"; const IMAGING_CODE = "363679005"; const patientIdOf = (order: ServiceRequest): string | undefined => order.subject?.reference?.startsWith("Patient/") ? order.subject.reference.split("/")[1] : undefined; /** The category is the discriminator, the same one the server branches on. */ const kindOf = (order: ServiceRequest): "laboratory" | "imaging" | undefined => { for (const category of order.category ?? []) { for (const coding of category.coding ?? []) { if (coding.system !== "http://snomed.info/sct") continue; if (coding.code === LABORATORY_CODE) return "laboratory"; if (coding.code === IMAGING_CODE) return "imaging"; } } return undefined; }; export interface DiagnosticOrderRowProps { order: ServiceRequest; state?: DiagnosticOrderState; result?: OrderResultDetail; callerPractitionerId?: string; /** Which order is one press from being acknowledged, and which is mid-flight. */ confirming?: string; reviewing?: string; onConfirm: (orderId: string) => void; onReview: (orderId: string) => void; onWithdraw: (order: ServiceRequest) => void; /** This is the order a "Result to review" link opened. */ opened?: boolean; } export const DiagnosticOrderRow = ({ order, state, result, callerPractitionerId, confirming, reviewing, onConfirm, onReview, onWithdraw, opened = false, }: DiagnosticOrderRowProps) => { // The order a "Result to review" link named: brought into view and marked, nothing more. Reviewing stays a press. const openedRef = useRef(null); useEffect(() => { if (opened) openedRef.current?.scrollIntoView?.({ block: "center" }); }, [opened]); const withdrawn = isArchived(order); // Why it went, when the order carries it. The reason is the clinician's own answer. const withdrawal = withdrawn ? readArchiveDetail(order) : undefined; // A refused order is still "sent" on the machine; the clinician who ordered it has to see it stopped. const refusal = withdrawn ? undefined : openOrderRefusal(order); // Until a result is in, a refused tube is why nothing has come back. const tubeRefused = withdrawn || state === "resulted" || state === "reviewed" ? undefined : specimenRefusal(order); const signature = readDiagnosticOrderReview(order); const mine = mayMarkReviewed(order, callerPractitionerId); // Said only when the released report carries a stamped position that is not a current pass, and said as at release. const qualityNotice = result?.qualityControl && qualityControlNotice(result.qualityControl, order.code?.text) ? qualityControlAtRelease(result.qualityControl, order.code?.text) : undefined; const placedHere = Boolean(callerPractitionerId) && orderingPractitionerReference(order) === `Practitioner/${callerPractitionerId}`; return (

{order.code?.text ?? "Test not named"}

{/* WHEN IT WAS ORDERED, WITH THE TIME, and the time is the point rather than decoration. WALKED 2026-09-14: this patient carried two rows reading "CBC panel - Blood by Automated count · Lab test · Result received · Mark reviewed", byte-identical, one placed weeks ago and one an hour earlier. `Mark reviewed` cannot be undone and the state machine only moves forward, so acknowledging the wrong one drops a real result off the clinician's worklist while the record says somebody read it. The walker could not tell which row was which and pressed neither. A DATE ALONE WOULD NOT HAVE SEPARATED THEM. Two of the same test on one day is what a serial measurement IS - before and after treatment, a recheck - and it is when getting it wrong matters most. The time is what makes the row unique. NOTHING NEW IS FETCHED. `authoredOn` is already on every order this row is handed; twelve of the fourteen on that patient carry it. The two that do not say so rather than rendering a gap, because a row that goes quiet about when it was ordered is the same problem in a smaller font. */}

{kindOf(order) === "imaging" ? "Imaging" : "Lab test"} {order.encounter ? " — ordered at a visit" : ""} {" · "} {order.authoredOn ? `Ordered ${formatDateTime(order.authoredOn)}` : "Ordered date not recorded"} {refusal?.reason && {" · "}{refusal.reason}} {tubeRefused && ( {" · "} {`Sample refused: ${tubeRefused.reason ?? "reason not recorded"}`} {tubeRefused.redraw ? ". A new sample was asked for." : ". The order was cancelled."} )} {withdrawal && ( {" · "} {`Withdrawn: ${ARCHIVE_REASON_LABELS[withdrawal.reason]}`} {withdrawal.note?.trim() ? ` — ${withdrawal.note.trim()}` : ""} )}

{/* A state nobody stamped is its own thing, not a blank: an order this system does not recognise is one somebody has to look at. */} {/* OUTLINE, NOT SECONDARY. In this product's light theme `--secondary` is a mid-dark fill (L 0.44) while `--secondary-foreground` is still shadcn's near-black (L 0.205), which was meant for a light fill -- so a secondary badge renders dark on dark and the state cannot be read. The referral screen's state pill uses outline for the same reason. */} {/* WITHDRAWN IS NOT A STATE ON THE MACHINE, and deliberately so: the machine only moves forward, and adding a terminal state to it would mean every reader of every queue had to learn one. The status on the resource carries it, which is what FHIR has the word for, and it is read here through the same helper every other archived resource is read through. */} {refusal ? ( ) : tubeRefused && state === "collected" ? ( Sample refused ) : {withdrawn ? "Withdrawn" : state ? DIAGNOSTIC_ORDER_STATE_LABELS[state] : "Not tracked"} } {/* ONLY ON A RESULT THAT IS IN, and only here. `reviewed` answers "has anybody looked at this?", which is a question about a result rather than about an order -- so it is offered when there is something to have looked at, and never from the staff queue, where the server refuses it to anybody without the practitioner role. */} {/* ONLY WHILE IT CAN STILL BE TAKEN BACK. Past `ordered` a specimen exists or a study happened, and the server refuses - so offering it there would be a button whose only outcome is a 409. The refusal still renders if the state is stale, which is why the error below relays the server's own sentence. Only the clinician who placed it is offered it, which is all the server allows. */} {canWithdrawDiagnosticOrder(state, withdrawn, placedHere) && order.id && ( )} {state === "resulted" && order.id && mine && ( )} {state === "resulted" && !mine && (

{describeReviewPending(order)}

)}
{/* WHAT WAS MEASURED, where the result is reviewed: each value under the name it was recorded with, its range and flag as recorded. Nothing here marks it reviewed. */} {result?.denied && (

You do not have access to this result.

)} {result?.checking && (

Checking the result…

)} {result?.unproven && (

The report filed on this order does not match this patient's order, so it is not shown.

)} {result?.unavailable && (

This result could not be loaded just now. Reload the page to try again.

)} {result?.withheld && (

{result.withheld}

)} {Boolean(result?.values?.length || result?.valuesUnread || result?.valuesDenied || result?.valuesUnproven) && ( {result?.values && result.values.length > 0 && (
    {result.values.map((line) => (
  • {line.label}{" "} {line.value} {line.range && · {line.range}} {line.interpretation && · {line.interpretation}} {line.changedHere && · {line.changedHere}}
  • ))}
)} {result?.valuesDenied ? (

{result.valuesDenied === 1 ? "1 value is not available to you" : `${result.valuesDenied} values are not available to you`}.

) : null} {result?.valuesUnproven ? (

{result.valuesUnproven === 1 ? "1 value does not match this result and is not shown" : result.valuesUnproven + " values do not match this result and are not shown"}.

) : null} {result?.valuesUnread ? (

{result.valuesUnread === 1 ? "1 value could not be loaded" : `${result.valuesUnread} values could not be loaded`}. Reload the page to try again.

) : null}
)} {qualityNotice && (

{qualityNotice}

)} {/* THE SIGNED WORDS BEFORE ANYTHING ADDED TO THEM: an addendum is read against the report it sits beside, so a row that listed only the addendum left it answering nothing. */} {result?.signed && ( )} {result?.studies && result.studies.length > 0 && patientIdOf(order) && (

Images:{" "} {result.studies.map((studyId) => ( View images ))}

)} {result && result.reports.length > 0 && ( )} {/* AFTER THE SIGNED WORDS, because that is where they were written. A reader who saw the report before an addendum existed saw something still true; this is what changed since. */} {result && result.addenda.length > 0 && ( )} {state === "reviewed" && signature && (

{describeReviewSignature(signature)}

)}
); }; export default DiagnosticOrderRow;