import type { ReferralQueueRow } from "../../hooks/useReferralQueue"; import type { ReferralState } from "../referralQueue"; /** * HAS THIS ARRIVING REFERRAL ALREADY BEEN MATCHED TO A PATIENT? * * A referral typed in at the front desk has no patient, so no ServiceRequest and no Task exist for it and * it cannot appear in the coordinator's queue. Matching it to a patient is what creates that record - at * the SAME id, which the log handler states as its contract. So a referral id appearing in the queue is * exactly the fact "somebody has already matched this". * * WHY THE QUEUE AND NOT THE THREAD. The pool thread is composed once, when the referral arrives, and * nothing updates it afterwards - so the thread cannot answer this. The queue can, and it is a projection * carrying state and the SENDING practice only. It names no patient, which is what makes this readable * from the front desk at all. * * NOTHING HERE NAMES THE PATIENT, and that is the disclosure rule this surface is built on rather than a * gap. Telling a receptionist that a referral is already being worked needs no identity; telling them WHO * it was matched to would, and the server does not send it. */ export type ReferralMatchState = /** Nobody has matched it. The match action is the work, and it is offered. */ | { kind: "unmatched" } /** Somebody has matched it. `state` is where the referral got to, when the queue says. */ | { kind: "matched"; state?: ReferralState } /** * We could not find out. * * Its own answer rather than folded into either, because both of the others are unsafe here: reporting * UNMATCHED invites a second receptionist to match a referral that already has a patient, which is the * defect this exists to stop; reporting MATCHED takes the work away from somebody who may be the first * person to reach it. The screen keeps the action and says the check did not run. */ | { kind: "unknown" }; export interface ReferralQueueReadState { rows: ReferralQueueRow[]; loading: boolean; error?: unknown; } /** * The queue keys a matched referral at the SAME id the arriving item carries - stated by * `logInboundReferral`: it writes no ServiceRequest, and "when the patient is finally linked the * ServiceRequest is created AT THAT SAME ID". */ export const referralMatchStateFor = ( referralId: string | undefined, queue: ReferralQueueReadState, ): ReferralMatchState => { if (!referralId) return { kind: "unknown" }; if (queue.loading) return { kind: "unknown" }; // An error and an empty list are different facts, and only one of them means "not matched". if (queue.error) return { kind: "unknown" }; const row = queue.rows.find((candidate) => candidate.orderId === referralId); if (!row) return { kind: "unmatched" }; return { kind: "matched", state: row.state }; };