import { useEffect, useRef, useState, useSyncExternalStore } from "react"; import { formatDateTime } from "../../../utils/dateUtils"; import type { Attachment } from "fhir/r4"; import { AlertCircle, Loader2 } from "lucide-react"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "../../../components/ui/dialog.tsx"; import { Alert, AlertDescription } from "../../../components/ui/alert.tsx"; import { Button } from "../../../components/ui/button.tsx"; import { LabReports } from "../../../components/LabReports/LabReports"; import { ReportAddenda } from "../../../components/LabReports/ReportAddenda"; import type { DiagnosticOrderQueueRow } from "../../../hooks/useDiagnosticOrderQueue.ts"; import { useLabReportsOnOrder } from "../../../hooks/useLabReportsOnOrder.ts"; import { REFUSAL_NEXT_STEPS } from "../../../hooks/useRecordOrderRefusal.ts"; import { useDiagnosticResult, type EnteredResult } from "../../../hooks/useDiagnosticResult.ts"; import { useReturnDiagnosticResult } from "../../../hooks/useReturnDiagnosticResult.ts"; import { openPdfInTab } from "../../../hooks/useSendOutDiagnosticOrder.ts"; import { useOrderResultRead } from "../../../hooks/useOrderResultRead.ts"; import { onViewerChange, viewerEpoch } from "../../../utils/writeThroughHold"; import { relayServerFailure } from "../../../utils/fetchFailureMessage"; import { DIAGNOSTIC_ORDER_STATE_LABELS, nextStatesFor, type DiagnosticOrderState, } from "../../../utils/diagnosticOrderQueue.ts"; import { awaitsSpecimen, deliveryLine, isAwaitingResult, returnLine, stateLabel } from "./queueLines.ts"; import { useStaffPermissionServiceContext } from "../../../services"; import { controlRunLine, qualityControlAtRelease } from "../../../utils/qualityControlNotice"; import { labStatusWords } from "../HeldLabResultsPage/heldLabResultWords.ts"; import "../BenchPage/BenchPage.css"; import "./ReleaseResultDialog.css"; import "./RecordRefusalDialog.css"; const CRITICAL_CHANNEL: Record = { telephone: "by telephone", "in-person": "in person", "secure-message": "by secure message" }; const refusalNextStep = (id?: string) => REFUSAL_NEXT_STEPS.find((step) => step.id === id)?.label; // The queue lists each order once with one next step; everything else that can be done to an // order lives here, with the order it belongs to. const identity = (row: DiagnosticOrderQueueRow) => `${row.patientDisplay ?? "Patient not named"} · ${row.test ?? "Test not named"}`; export const Identity = ({ row, detail }: { row: DiagnosticOrderQueueRow; detail?: string }) => (
{identity(row)} {detail ? {detail} : null}
); export const Fact = ({ term, children, hint }: { term: string; children: React.ReactNode; hint?: string }) => (
{term}
{children}
{hint ?
{hint}
: null}
); const fromLine = (row: DiagnosticOrderQueueRow) => row.fromAkashic ? [`From ${row.fromOutside ?? "the sending practice"}`, row.fromAkashic.orderedBy, `Sender’s order ${row.fromAkashic.theirOrderId}`] .filter(Boolean) .join(" · ") : row.fromOutside && row.theirOrderNumber ? `From ${row.fromOutside} · Sender’s order ${row.theirOrderNumber}` : undefined; /** The laboratory's attached files are fetched when somebody asks for them, not with the order. */ const useReportOnDemand = (orderId?: string) => { const readLabReports = useLabReportsOnOrder(); // Each opening is its own: a new order, or this one closed and opened again. A read answers only the opening // that asked, so files read for one are never shown in the next. const opening = useRef(0); const openFor = useRef(); if (openFor.current !== orderId) { openFor.current = orderId; opening.current += 1; } const [shown, setShown] = useState<{ opening: number; reports: Attachment[]; withheld?: string }>(); const [failed, setFailed] = useState<{ opening: number; message: string }>(); const [readingFor, setReadingFor] = useState(); const mine = shown?.opening === opening.current ? shown : undefined; const reports = mine && !mine.withheld ? mine.reports : undefined; const withheld = mine?.withheld; const error = failed?.opening === opening.current ? failed.message : undefined; const reading = readingFor === opening.current; const toggle = async () => { if (!orderId) return; if (mine) { setShown(undefined); return; } const asked = opening.current; setReadingFor(asked); setFailed(undefined); try { const found = await readLabReports(orderId); if (opening.current !== asked) return; setShown({ opening: asked, reports: found.reports ?? [], ...(found.withheld ? { withheld: found.message || "These files are not available to you yet." } : {}) }); } catch (failure) { if (opening.current !== asked) return; console.error("Error reading the attached laboratory files on an order:", failure); setFailed({ opening: asked, message: relayServerFailure(failure, "Could not open the attached files just now.") }); } finally { setReadingFor((current) => (current === asked ? undefined : current)); } }; return { reports, withheld, error, reading, toggle, open: Boolean(mine) }; }; type ReportOnDemand = ReturnType; const ReportButton = ({ report }: { report: ReportOnDemand }) => ( ); const ReportShown = ({ report }: { report: ReportOnDemand }) => ( <> {report.error && ( {report.error} )} {/* Withheld, none attached and could not ask are three different answers, and none says the result is missing. */} {report.withheld ? (

The attached laboratory files can’t be shown here: {report.withheld}

) : null} {report.reports && (report.reports.length ? ( ) : (

No laboratory files are attached to this result.

))} ); const ASKED = "Asked. What the laboratory sends back is filed on this order, or held for a person to match. Nothing reaches the patient until it is released."; /** * Asking the laboratory that confirmed this order for its results now, offered only with its receipt and diagnostics * manage; a refusal is shown in the server's words. An ask belongs to the opening it was made in (this order, this * viewer): once that ends nothing more is sent or shown for it, and an older ask's answer never clears a newer one. */ const useAskForResults = (row?: DiagnosticOrderQueueRow) => { const { canManage } = useStaffPermissionServiceContext(); const { askForResults } = useOrderResultRead(); const viewer = useSyncExternalStore(onViewerChange, viewerEpoch); const opening = useRef(0); const openFor = useRef<{ orderId?: string; viewer?: number }>({}); if (openFor.current.orderId !== row?.orderId || openFor.current.viewer !== viewer) { openFor.current = { orderId: row?.orderId, viewer }; opening.current += 1; } useEffect(() => () => { opening.current += 1; }, []); const latest = useRef(0); const [asked, setAsked] = useState<{ id: number; opening: number; busy?: boolean; said?: string; failed?: boolean }>(); const ask = async () => { const orderId = row?.orderId; if (!orderId) return; const mine = { id: ++latest.current, opening: opening.current }; // The viewer is read live, not through the last render, so a change just before sending retires the ask. const viewerAt = viewerEpoch(); const owns = () => opening.current === mine.opening && viewerEpoch() === viewerAt; const settle = (next: { said?: string; failed?: boolean }) => setAsked((now) => (now?.id === mine.id ? { ...mine, ...next } : now)); setAsked({ ...mine, busy: true }); try { settle(await askForResults(orderId, owns) ? { said: ASKED } : { said: "The laboratory was not asked for results.", failed: true }); } catch (failure) { settle({ said: relayServerFailure(failure, "Could not ask the laboratory for results. Try again."), failed: true }); } }; const current = asked?.opening === opening.current ? asked : undefined; return { offered: Boolean(row?.labConfirmed && row.orderId && canManage("diagnostics")), ask, ...current }; }; export const QueueOrderDialog = ({ row, panelOf = 1, busy, onClose, onAdvance, onSendOut, onSendToRead, onRefused, onWithdraw, onRefusalDealtWith, onRelease, onEnter, onRetryTransmission, }: { row?: DiagnosticOrderQueueRow; panelOf?: number; busy: boolean; onClose: () => void; onAdvance: (row: DiagnosticOrderQueueRow, state: DiagnosticOrderState) => void; onSendOut: (row: DiagnosticOrderQueueRow) => void; /** A performed, unreported study, to a reader on Akashic or not; absent when it cannot go. */ onSendToRead?: (row: DiagnosticOrderQueueRow) => void; onRefused: (row: DiagnosticOrderQueueRow) => void; /** The ordering clinician takes the order back; offered only where the server says it would admit it. */ onWithdraw?: (row: DiagnosticOrderQueueRow) => void; onRefusalDealtWith: (row: DiagnosticOrderQueueRow) => void; onRelease: (row: DiagnosticOrderQueueRow) => void; onEnter: (row: DiagnosticOrderQueueRow) => void; /** An electronic send saved but not confirmed queued, handed on again under the same send-out. */ onRetryTransmission?: (row: DiagnosticOrderQueueRow) => void; }) => { const report = useReportOnDemand(row?.orderId); const asking = useAskForResults(row); const { canManage, permissionsSettled } = useStaffPermissionServiceContext(); const mayWork = row?.kind !== "laboratory" || (permissionsSettled && canManage("diagnostics")); if (!row) return null; // Offered moves come from the state, so a button whose only outcome is a refusal is never shown. const moves = nextStatesFor(row.kind, row.state); const laboratory = row.sentOut?.laboratory ?? row.akashicRoute?.laboratory; const delivery = deliveryLine(row); const from = fromLine(row); return ( { if (!open) onClose(); }}> Order details Where this order stands and what can be done with it.
{stateLabel(row.state)} {laboratory ? {laboratory} : null} {delivery ? {delivery} : null} {from ? {from} : null} {panelOf > 1 ? ( {`Ordered with ${panelOf - 1} other ${panelOf === 2 ? "test" : "tests"} — one draw`} ) : null}
{/* Still sent, because it genuinely was sent; the refusal is what says the work stopped. */} {row.refusal && (
{row.refusal.reason ?? "The laboratory refused this order"} {row.refusal.theirMessage && ( {row.refusal.theirMessage} )} {row.refusal.theirCode && Their reference: {row.refusal.theirCode}} {refusalNextStep(row.refusal.nextStep) && Next: {refusalNextStep(row.refusal.nextStep)}} {mayWork && row.orderId && ( )}
)} {/* Dealing with a refusal ends it as work; the order still shows it happened. */} {row.pastRefusal && !row.refusal && (

Order history

{["Laboratory refused the order", row.pastRefusal.recorded ? formatDateTime(row.pastRefusal.recorded) : undefined] .filter(Boolean).join(" · ")} {row.pastRefusal.reason && {row.pastRefusal.reason}} {row.pastRefusal.theirMessage && ( {row.pastRefusal.theirMessage} )} {row.pastRefusal.theirCode && Their reference: {row.pastRefusal.theirCode}} {row.pastRefusal.resolved ? `Dealt with ${formatDateTime(row.pastRefusal.resolved)}` : "Dealt with"}
)}
{mayWork && moves.map((state) => // Sending asks where rather than just stamping; marking it without a laboratory left orders sent to nobody. state === "sent" ? ( ) : ( ), )} {onRetryTransmission && row.transmissionOwed && row.orderId && ( )} {onRetryTransmission && row.deliveryOwed && row.orderId && ( )} {mayWork && onSendToRead && row.orderId && ( )} {/* A result reaches nobody until somebody releases it. */} {mayWork && row.awaitingRelease && row.orderId && ( )} {/* A refused order waits on the refusal being dealt with, not on a result. A test performed here waits for its specimen to be received; one sent out is entered from the other laboratory's report. */} {mayWork && isAwaitingResult(row.state) && row.orderId && !row.refusal && !awaitsSpecimen(row) && ( )} {row.resultOnFile && row.orderId && } {asking.offered && (!asking.said || asking.failed) && ( )} {onWithdraw && row.withdrawable && row.orderId && ( )} {/* The laboratory would not take it, which is not the sample being refused. */} {mayWork && row.orderId && !row.refusal && !row.awaitingRelease && ( )}
{asking.said ?

{asking.said}

: null}
); }; /** * Who released the result and when, as the report records it. Never the viewer, the ordering practitioner or an * addendum's author, and never inferred: a result not released says so, and a missing signer says it was not recorded. */ /** * Where a report filed from a laboratory came from, and the laboratory's own status and time. Said apart from the * release line, because the laboratory finishing a report is not anyone here releasing it. */ const LaboratorySource = ({ from }: { from: NonNullable }) => (

{[`From ${from.laboratory ?? "the laboratory"}: their report ${from.theirReport}, version ${from.version}`, labStatusWords(from.laboratoryStatus), from.issued ? `issued ${formatDateTime(from.issued)}` : undefined] .filter(Boolean).join(" · ")}

); const ReleaseAttribution = ({ result }: { result: EnteredResult }) => { const at = result.status === "final" ? result.released?.at : undefined; return (

{!at ? "Not released yet." : result.released?.by ? `Signed by ${result.released.by} · ${formatDateTime(at)}` : `Signed ${formatDateTime(at)} · signer not recorded`}

); }; /** * Where quality control stood when the result went out, from the position stamped on it, never today's. Said only * when the server sent the stamped position, so a missing answer is not mistaken for one released before stamping. */ const QualityControlAtRelease = ({ result, test }: { result: EnteredResult; test?: string }) => { if (result.status !== "final" || result.qualityControlAtRelease === undefined) return null; const run = controlRunLine(result.qualityControlAtRelease ?? undefined); return (

{qualityControlAtRelease(result.qualityControlAtRelease, test)} {run ? <>
{run} : null}

); }; export const QueueResultDialog = ({ row, panelOf = 1, busy, onClose, onAddendum, onReturn, onFaxBack, }: { row?: DiagnosticOrderQueueRow; panelOf?: number; busy: boolean; onClose: () => void; onAddendum: (row: DiagnosticOrderQueueRow) => void; onReturn: (row: DiagnosticOrderQueueRow) => void; onFaxBack: (row: DiagnosticOrderQueueRow) => void; }) => { const { result, error: readError, loading } = useDiagnosticResult(row?.orderId); const report = useReportOnDemand(row?.orderId); const { resultPage } = useReturnDiagnosticResult(); // The server takes an addendum only from diagnostics manage; nobody else is offered one. The Admin // workspace reads as manage here, so a result the server just refused to show also offers none. const { canManage } = useStaffPermissionServiceContext(); const mayAddend = canManage("diagnostics") && !readError; const [printError, setPrintError] = useState(); if (!row) return null; const printResult = async () => { if (!row.orderId) return; // Opened before the await, while the click still counts as the user acting. const tab = window.open("", "_blank"); if (tab) tab.opener = null; setPrintError(undefined); try { openPdfInTab(tab, await resultPage(row.orderId)); } catch (failure) { tab?.close(); setPrintError(relayServerFailure(failure, "The result page could not be made.")); } }; const returned = returnLine(row); const signed = Boolean(row.resultOnFile && !row.awaitingRelease && row.orderId); const from = fromLine(row); return ( { if (!open) onClose(); }}> Result details The result on file for this order. {/* The sender files what comes back against their own number, so the result names it. */} {from ?
{from}
: null} {loading ? (

Reading the result…

) : null} {readError ? ( {readError} ) : null} {/* An imaging read is findings and impression; its measurements are optional and not missed. */} {result && (result.measurements.length || row.kind !== "imaging") ? (result.measurements.length ? ( {result.measurements.map((measurement, index) => ( ))}
MeasurementValueUnit
{measurement.name ?? "Not named"} {[measurement.value ?? "Not recorded", measurement.flag].filter(Boolean).join(" ")} {measurement.unit ?? ""}
) : (

No measurement was entered on this result.

)) : null} {result?.findings ?

{result.findings}

: null} {result?.impression ?

Impression {result.impression}

: null} {/* The order the report answers carries what was added since signing, beside the signed words. */} {result?.criticalFinding?.told ? (

{[`Critical result told to ${result.criticalFinding.told}`, result.criticalFinding.how ? CRITICAL_CHANNEL[result.criticalFinding.how] ?? result.criticalFinding.how : undefined, result.criticalFinding.at ? formatDateTime(result.criticalFinding.at) : undefined].filter(Boolean).join(" ")}

) : null} {result?.fromLaboratory ? : null} {result ? : null} {result && row.kind !== "imaging" ? : null} {result?.addenda?.length ? : null} {panelOf > 1 ?

Other tests in this panel keep their own status.

: null} {/* Released is not reviewed; the queue never implies the clinician has seen it. */}

{row.state === "reviewed" ? "The ordering clinician has reviewed this result." : "Ordering clinician has not reviewed this result."}

{returned ?

{returned}

: null}
{/* A laboratory's paperwork; an imaging read is its own report and has none. */} {row.resultOnFile && row.orderId && row.kind !== "imaging" && } {/* Only once the result is out; before release the words belong in the report itself. */} {signed && mayAddend && ( )} {/* The signed page the server renders for any order here, on the permission it asks for; an in-house imaging read has no laboratory paperwork to print instead. */} {signed && mayAddend && (row.fromOutside || row.kind === "imaging") && ( )} {/* Back the way it came, for a practice that ordered on paper and has no login here. */} {signed && row.fromOutside && ( <> {/* Fax is for a practice that ordered on paper; an Akashic return lands on their own order. */} {!row.fromAkashic && !row.readFor && ( )} )}
{printError && ( {printError} )}
); };