import { useRef, useState } from "react"; import { AlertCircle, Inbox, Loader2, Plus } from "lucide-react"; import { Alert, AlertDescription } from "../../../components/ui/alert.tsx"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "../../../components/ui/dialog.tsx"; import { Button } from "../../../components/ui/button.tsx"; import { Input } from "../../../components/ui/input.tsx"; import { Label } from "../../../components/ui/label.tsx"; import { Textarea } from "../../../components/ui/textarea.tsx"; import { ToggleGroupControl, ToggleGroupControlOption } from "../../../components/ui/toggle-group-control.tsx"; import { EmptyState } from "../../../components/ui/empty-state.tsx"; import { useStaffPermissionServiceContext } from "../../../services"; import { useInboundRequisitions, type InboundRequisition, type RefusedRequisition, } from "../../../hooks/useInboundRequisitions.ts"; import { formatDate, formatDateTime } from "../../../utils/dateUtils"; import { mayHaveBeenWritten, relayServerFailure } from "../../../utils/fetchFailureMessage"; import { newOperationId } from "../../../hooks/useHeldLabResults"; import MatchRequisitionDialog from "./MatchRequisitionDialog.tsx"; import ReviewOrderDialog from "./ReviewOrderDialog.tsx"; import { testTermsOf } from "./requisitionTestTerms.ts"; import RefuseRequisitionDialog, { REASONS } from "./RefuseRequisitionDialog.tsx"; import RequisitionContactDialog, { describeContact, failureWording } from "./RequisitionContactDialog.tsx"; import "./InboundRequisitionsPage.css"; // WHAT ARRIVED ON PAPER FROM SOMEBODY WHO IS NOT ON THIS SYSTEM. // // EVERY OTHER INBOUND PATH STARTS WITH ANOTHER AKASHIC PRACTICE, so the requisitions that most need // tracking - faxed by a clinician who will never have a login - had no way in at all. // // THE PATIENT IS NAMED BY A PERSON AND NEVER BY THIS SCREEN. What is typed here is what the sender // wrote, and it stays that way until somebody opens the row and chooses a record. Nothing on this // page searches for a patient, suggests one, or highlights a likely one. // // TYPING IN AND MATCHING BOTH NEED `manage`; READING THE LIST NEEDS ONLY `view`. That is the split // the API makes, and the screen makes the same one rather than a different one: a tech the practice // has not yet trusted to write to a record can still see that a fax arrived, which is how somebody // knows to fetch the person who can. const BLANK = { from: "", npi: "", test: "", patientName: "", patientBirthDate: "", theirOrderCode: "", note: "", }; const InboundRequisitionsPage = () => { const { canManage } = useStaffPermissionServiceContext(); const { requisitions, requisitionsPartial, refused, refusedUnreadable, refusedPartial, refusedWindowDays, loading, error, reload, log, match, accept, refuse, recordContact, findCandidates, } = useInboundRequisitions(); const mayWrite = canManage("diagnostics"); const [typing, setTyping] = useState(false); const [paper, setPaper] = useState(BLANK); // Which worklist the accepted order joins; the paper says, and most paper is laboratory work. const [kind, setKind] = useState<"laboratory" | "imaging">("laboratory"); const [busy, setBusy] = useState(false); const [logError, setLogError] = useState(); // An entry whose answer was lost keeps its operation, so logging the same paper again cannot store it twice. const unsettled = useRef<{ operationId: string; request: string }>(); const [matching, setMatching] = useState(); const [reviewing, setReviewing] = useState(); const [refusing, setRefusing] = useState(); const [contacting, setContacting] = useState(); const [resending, setResending] = useState(); const [resendError, setResendError] = useState(); // The server keeps the refusal as first recorded; a resend only retries updating the sender's order. const resend = async (row: RefusedRequisition) => { setResending(row.requisitionId); setResendError(undefined); try { await refuse(row.requisitionId as string, { reasonCode: row.refusal?.reasonCode ?? "other", message: row.refusal?.message ?? "Refused." }); } catch (failure) { console.error("Error resending a refusal:", failure); setResendError(failureWording(failure, "refusal")); } finally { setResending(undefined); } }; const field = (key: keyof typeof BLANK) => ( event: { target: { value: string } }, ) => setPaper((held) => ({ ...held, [key]: event.target.value })); // The two facts a row is unreadable without. Everything else on a fax is optional, because a fax // that omits it is a bad requisition and a real one. const submittable = paper.from.trim().length > 0 && paper.patientName.trim().length > 0; const close = () => { setPaper(BLANK); setKind("laboratory"); setTyping(false); setLogError(undefined); }; const submit = async () => { setBusy(true); setLogError(undefined); const requisition = { from: paper.from.trim(), patientName: paper.patientName.trim(), ...(paper.npi.trim() ? { npi: paper.npi.trim() } : {}), ...(paper.test.trim() ? { test: paper.test.trim() } : {}), ...(kind === "imaging" ? { kind: "imaging" as const } : {}), ...(paper.patientBirthDate.trim() ? { patientBirthDate: paper.patientBirthDate.trim() } : {}), ...(paper.theirOrderCode.trim() ? { theirOrderCode: paper.theirOrderCode.trim() } : {}), ...(paper.note.trim() ? { note: paper.note.trim() } : {}), }; const request = JSON.stringify(requisition); const attempt = unsettled.current?.request === request ? unsettled.current : { operationId: newOperationId(), request }; unsettled.current = attempt; try { await log(requisition, attempt.operationId); unsettled.current = undefined; close(); await reload(); } catch (failure) { console.error("Error logging an inbound requisition:", failure); // Only a server's definite refusal settles the entry; any other failure may have stored it. const refused = typeof (failure as { status?: unknown } | null)?.status === "number" && !mayHaveBeenWritten(failure); if (!refused) { setLogError("This may have been saved; the answer was lost. Log it again unchanged to finish; it will not be stored twice."); } else { unsettled.current = undefined; setLogError(relayServerFailure(failure, "That could not be saved. Nothing was recorded.")); } } finally { setBusy(false); } }; return (

Requisitions received

Outside orders waiting for patient matching.

{mayWrite && ( )}
{error && !loading && ( {error} )} { if (!open && !busy) close(); }}> Add requisition Enter what arrived from the outside practice.
{logError && ( {logError} )}
{/* AS THE PAGE HAS IT, and the label says so. Somebody correcting a spelling here is editing the evidence the match will later be judged against. */}
setKind(value === "imaging" ? "imaging" : "laboratory")}>