import { useEffect, useRef, useState } from "react"; import { AlertCircle, Loader2 } from "lucide-react"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "../../../components/ui/dialog.tsx"; import { Alert, AlertDescription } from "../../../components/ui/alert.tsx"; import { Button } from "../../../components/ui/button.tsx"; import { EmptyState } from "../../../components/ui/empty-state.tsx"; import { Input } from "../../../components/ui/input.tsx"; import { Label } from "../../../components/ui/label.tsx"; import { RadioControl } from "../../../components/ui/radio-control.tsx"; import { formatDate, formatDateTime } from "../../../utils/dateUtils"; import { relayServerFailure } from "../../../utils/fetchFailureMessage"; import { newOperationId, type HeldLabResult, type HeldResultCandidates, type ResolvedHeldResult, } from "../../../hooks/useHeldLabResults.ts"; import { heldReasonWords, labStatusWords } from "./heldLabResultWords.ts"; // Saying which order a lab result answers. Only the orders the server offers are shown, exactly the ones it will // accept: this practice's, sent to that laboratory at that address, for the patient the laboratory names. Nothing is // searched for or suggested. Filed is not released: the outcome says it reaches no patient until someone releases it. interface Props { item?: HeldLabResult; onClose: () => void; onDone: () => void; candidates: (id: string) => Promise; resolve: (id: string, orderId: string, operationId: string) => Promise; } /** * An order named by its page address (`…/diagnostic-orders//…`) or its bare id, for an order the server could not * offer: one sent before laboratories confirmed patients. The server checks it exactly as it checks an offered one. */ export const orderIdFrom = (text: string): string | undefined => { const written = text.trim(); return (/\/diagnostic-orders\/([A-Za-z0-9.-]{1,64})(?:[/?#]|$)/.exec(written) ?? /^([A-Za-z0-9.-]{1,64})$/.exec(written))?.[1]; }; const outcomeWords = (result: ResolvedHeldResult | undefined): { done: boolean; words: string } => { if (result?.outcome === "filed") return { done: true, words: "Filed onto the order. It reaches the patient only when someone releases it." }; if (result?.outcome === "superseded") return { done: true, words: "A newer edition of this result was already filed on the order, so this one is kept as received." }; if (result?.outcome === "held") return { done: false, words: `Matched, but it could not be filed: ${heldReasonWords(result.reason)}` }; return { done: false, words: "Someone else acted on this result meanwhile. Look at the list again." }; }; const MatchHeldResultDialog = ({ item, onClose, onDone, candidates, resolve }: Props) => { const [found, setFound] = useState(); const [loadError, setLoadError] = useState(); const [chosen, setChosen] = useState(""); // An order named by hand stands in for the offered ones while anything is typed. const [typed, setTyped] = useState(""); const target = typed.trim() ? orderIdFrom(typed) : chosen; const [busy, setBusy] = useState(false); const [error, setError] = useState(); const [result, setResult] = useState<{ done: boolean; words: string }>(); // One attempt, one id: a resend after an unclear answer is recognised by the server, never applied twice. const operation = useRef(newOperationId()); useEffect(() => { setFound(undefined); setLoadError(undefined); setChosen(""); setTyped(""); setError(undefined); setResult(undefined); operation.current = newOperationId(); if (!item) return; let current = true; candidates(item.id) .then((answer) => { if (current) setFound(answer); }) .catch((failure) => { if (current) setLoadError(relayServerFailure(failure, "Could not find the orders this result may answer.")); }); return () => { current = false; }; }, [item, candidates]); const match = async () => { if (!item || !target) return; setBusy(true); setError(undefined); try { const said = outcomeWords(await resolve(item.id, target, operation.current)); setResult(said); } catch (failure) { setError(relayServerFailure(failure, "The match was not confirmed. Try again; a repeat is recognised.")); } finally { setBusy(false); } }; const report = item?.report; return ( { if (!open) (result ? onDone : onClose)(); }}> Match this laboratory result to an order {heldReasonWords(item?.heldReason)}
Test
{report?.code ?? "Not named"}
{labStatusWords(report?.status) ? <>
Status
{labStatusWords(report?.status)}
: null} {report?.issued ? <>
Issued
{formatDateTime(report.issued)}
: null}
Patient at the laboratory
{report?.subject?.display ?? "Not named"}{report?.subject?.reference ? ` (${report.subject.reference})` : ""}
{result ? ( {result.words} ) : loadError ? ( {loadError} ) : !found ? (

Finding the orders it may answer…

) : found.orders.length === 0 && !found.complete ? (

{found.reason ? `${found.reason} ` : ""}Not every order could be looked at just now, so one may be missing. Try again shortly.

) : found.orders.length === 0 ? ( ) : ( <> ({ value: each.orderId, label: [each.test ?? "Order", each.patient?.name, each.requested ? `requested ${formatDate(each.requested)}` : undefined] .filter(Boolean).join(" · "), }))} onChange={(value: string) => setChosen(value)} /> {!found.complete ?

Not every order could be looked at just now, so one may be missing. Try again shortly.

: null} )} {!result && found ? (
setTyped(event.target.value)} />

An order sent before laboratories confirmed their patients is not listed. Paste the address of its page; it is checked exactly as a listed one is.

{typed.trim() && !orderIdFrom(typed) ?

That is not an order's page address.

: null}
) : null} {error ? {error} : null} {result ? ( ) : ( <> )}
); }; export default MatchHeldResultDialog;