import { useCallback, useRef } from "react"; import { useHttpService } from "../services/HttpService.tsx"; import { useStaffPermissionServiceContext } from "../services"; import { environment } from "../environments/environment.ts"; import { SaveRetiredError } from "../utils/saveOperation"; /** * Asking the laboratory that confirmed an order for its results now, rather than at the next scheduled read. This only * asks: the reads happen elsewhere, and what comes back is filed on the order or held for a person to match. Nothing * reaches a patient until someone releases it. */ export const NO_LONGER_ALLOWED = "You can no longer ask laboratories for results here."; export const useOrderResultRead = () => { const { post } = useHttpService(); const { canManage } = useStaffPermissionServiceContext(); // Read again just before the request leaves, after the sign-in and proof waits; an answer to a sent ask is kept. const mayAsk = useRef(false); mayAsk.current = canManage("diagnostics"); /** * True only when the server says the read was queued. `owns` is the caller's claim on the ask: once it is false, * nothing more is sent for it. An answer to an ask already sent is kept either way. */ const askForResults = useCallback(async (orderId: string, owns?: () => boolean): Promise => { const admit = (phase?: "answer") => { if (phase === "answer") return; if (!mayAsk.current) throw new Error(NO_LONGER_ALLOWED); if (owns && !owns()) throw new SaveRetiredError(); }; const answer = await post<{ queued?: boolean }>( `${environment.fhirClinicalApi}/diagnostic-order/${encodeURIComponent(orderId)}/result-read`, {}, { admit }, ); return answer?.queued === true; }, [post]); return { askForResults }; };