feat: add drain tail to the payments

This commit is contained in:
Nathnael
2026-08-04 08:59:33 +00:00
parent a20498fd77
commit acd2cfbe8c
9 changed files with 379 additions and 22 deletions

View File

@@ -7,11 +7,51 @@
* (BookingWindowService) drives all timing off that config.
*/
export const BATCH_TIMEZONE = 'Africa/Addis_Ababa';
export const BATCH_TIMEZONE = "Africa/Addis_Ababa";
/** How long before the pay deadline the one reminder notification goes out. */
export const PAYMENT_REMINDER_LEAD_MS = 10 * 60_000;
/** Drain tail applied to every pay window when FREIGHT_PAYMENT_DRAIN_MINUTES is unset. */
export const DEFAULT_PAYMENT_DRAIN_MINUTES = 7;
/**
* Drain tail on every pay window, in ms. Read per call so the env var can be
* changed without a rebuild (and so tests can set it).
*/
export function paymentDrainMs(): number {
// An empty/blank value is UNSET, not zero — a bare `FREIGHT_PAYMENT_DRAIN_MINUTES=`
// left in a .env must not silently disable the drain (Number('') is 0).
const raw = process.env.FREIGHT_PAYMENT_DRAIN_MINUTES?.trim();
const minutes = raw ? Number(raw) : NaN;
return (
(Number.isFinite(minutes) && minutes >= 0
? minutes
: DEFAULT_PAYMENT_DRAIN_MINUTES) * 60_000
);
}
/**
* A pay window AND its drain tail have closed.
*
* Settlement is asynchronous (provider confirm → payment-api → outbox relay), so
* a payment made in the last seconds of the window lands after `paymentDeadline`.
* The drain defers the WHOLE expiry pipeline — wagons stay held, the waiting list
* is not promoted, the window cycle does not conclude — so that settlement still
* has a live booking to land on. A payment that arrives even later is not lost
* either: it settles the expired invoice and revives the booking (see
* BillingService.settleByPaymentId + BookingInvoiceService.advanceBookingOnPayment).
*
* No deadline ⇒ never lapsed; callers decide what an unknown deadline means.
*/
export function payWindowLapsed(
deadline: Date | null | undefined,
now: number,
drainMs: number = paymentDrainMs(),
): boolean {
return deadline != null && deadline.getTime() + drainMs <= now;
}
/** Fallback wagons-per-booking when a booking has no computed `wagonsRequired`. */
export const DEFAULT_WAGONS_PER_BOOKING = 1;