Dev.to WebDev 🛠 Dev 👁 0 📖 1 min read

Checking a payment run day by day: a reserve invariant, early-payment discounts and integer cents

A payment run is a list of (date, amount) outflows mixed with expected receipts. The only question that matters is whether the running balance stays above a reserve on every day. That makes it a simple invariant you can

A payment run is a list of (date, amount) outflows mixed with expected receipts. The only question that matters is whether the running balance stays above a reserve on every day. That makes it a simple invariant you can test.

The data

const reserve = 1_000_000n;           // $10,000.00
const opening = 3_000_000n;
const events = [
  { day: 1, amt: -800_000n,  what: 'bill A' },
  { day: 3, amt: -1_200_000n, what: 'bill B' },
  { day: 4, amt:  1_500_000n, what: 'receipt' },
  { day: 5, amt: -900_000n,  what: 'bill C' },
];

The check

Sort by day, apply all receipts and payments of a day together, and record the first breach:

function firstBreach(opening, events, reserve) {
  const byDay = new Map();
  for (const e of events) byDay.set(e.day, (byDay.get(e.day) ?? 0n) + e.amt);
  let bal = opening;
  for (const day of [...byDay.keys()].sort((a, b) => a - b)) {
    bal += byDay.get(day);
    if (bal < reserve) return { day, short: reserve - bal };
  }
  return null;
}

Same-day netting is a modelling choice: if your bank posts payments before receipts, apply negatives first. Write it down and test it.

Discounts are a scenario, not a rule

A 2% discount on bill B for paying on day 1 changes two events:

const disc = 1_200_000n * 9_800n / 10_000n; // 1_176_000n

Take it only if firstBreach on the modified plan is still null. Here the balance on day 1 drops to $10,240, which passes, and saves $240.

Stress the receipts

Move the receipt a week later and run the check again. In this example day 5 then breaks the reserve: by $9,000 in the plain plan and by $8,760 with the discount taken. That is the number to know before you approve a run.

We use the same invariant in the Supplier Bills & Payment Run Planner (paid, with a free demo).

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.