import { directionOf, type ReferralQueueRow } from "../hooks/useReferralQueue"; /** * WHICH OF A PATIENT'S REFERRALS THIS BOOKING IS ABOUT TO CLOSE. * * Booking a patient advances their open inbound referral and retires its front-desk row. That is * correct and it is the point - but the receptionist doing the booking is never told they are doing it, * so a referral leaves a colleague's queue with nobody having decided to close it. * * SHAPE, NOT CLINICAL DETAIL. This answers "how many, and who sent them" and nothing else. It is a line * of context on a booking screen, not a referral record. */ /** Still waiting. `scheduled` and `expired` are already finished, and booking does nothing to them. */ const OPEN_STATES = new Set(["sent", "delivered", "claimed"]); export interface ReferralAboutToClose { id?: string; /** The practice that sent it, when the record names one. */ from?: string; } /** * INBOUND ONLY, and that is the load-bearing filter rather than a tidy-up. * * An outbound referral - one this practice SENT - is closed by the RECEIVING practice booking the * patient, not by us booking them here. Telling a receptionist that their booking closes somebody * else's referral would be false, and it is the kind of false that reads as authoritative. */ export const referralsClosedByBooking = ( rows: ReferralQueueRow[] | undefined, organizationId: string | undefined, ): ReferralAboutToClose[] => (rows ?? []) .filter((row) => directionOf(row, organizationId) === "inbound") // The server closes only a referral whose performer names this practice by reference. .filter((row) => !organizationId || row.performerReference === `Organization/${organizationId}`) .filter((row) => row.state !== undefined && OPEN_STATES.has(row.state)) .map((row) => ({ id: row.orderId, from: row.requesterDisplay }));