import type { Payload, PayloadRequest } from "payload"; import type { ReservationRow, SettlementConsumed } from "./allocationTypes"; import { settleOperationReservation } from "./allocation"; /** * Operation-wide batch settlement: mission failure and expiry sweeps. Each * row still settles through `settleOperationReservation`, so the exactly-once * guard applies per row and re-running a sweep is a no-op. */ /** * Mission-failure settlement: every still-reserved reservation for the * operation settles with reason `mission-failed`, consuming only what the * caller evidences and returning the rest. Rows already settled (including * extraction-driven settlements) are terminal and therefore untouched, and * no operation-effects rows are written or reversed here: a recorded * extraction deposit stays final even when the mission fails. */ export async function failOperationReservations( payload: Payload, operationId: string, opts?: { effectId?: number; actorId?: number; consumedByKey?: Record; }, req?: PayloadRequest, ): Promise { const active = await payload.find({ collection: "operation-reservations", where: { and: [{ operationId: { equals: operationId } }, { status: { equals: "reserved" } }], }, limit: 1000, depth: 0, overrideAccess: true, req, }); let settled = 0; for (const doc of active.docs) { const row = doc as unknown as ReservationRow; await settleOperationReservation( payload, { reservationId: row.id }, { outcome: "settled", reason: "mission-failed", consumed: opts?.consumedByKey?.[row.reservationKey], effectId: opts?.effectId, actorId: opts?.actorId, }, req, ); settled += 1; } return settled; } /** * Expiry sweeper: reservations past `expiresAt` while still reserved settle * as `expired` with everything returned. Idempotent via the settle guard. */ export async function expireOperationReservations( payload: Payload, now: Date = new Date(), req?: PayloadRequest, ): Promise { const due = await payload.find({ collection: "operation-reservations", where: { and: [{ status: { equals: "reserved" } }, { expiresAt: { less_than: now.toISOString() } }], }, limit: 1000, depth: 0, overrideAccess: true, req, }); let settled = 0; for (const doc of due.docs) { const row = doc as unknown as ReservationRow; await settleOperationReservation( payload, { reservationId: row.id }, { outcome: "expired" }, req, ); settled += 1; } return settled; }