BT San Technology

19 August 2026

Following Up Receivables in ERP: Due Dates, Aging and Follow-up Notes

27 min read · ERP and CRM

Illustration: an outstanding-balance report on screen with a calculator on an accounting desk
AI-generated illustration

At month end, the manager asks for the receivables aging report. Accounting runs it and gets one number. Three days later, sales runs it again and gets another, because payments arrived in between and someone edited an invoice date. One customer has paid but still gets collection calls. Another is disputing damaged goods but receives the third automatic reminder email. A transfer with no invoice reference sits in a suspense account and nobody applies it.

This article walks through writing the core of receivables follow-up so that it is correct and testable. It uses TypeScript that Node 24 runs directly and the SQLite that ships with Node, so there is nothing to install. A manager can read the explanations and tables and see the picture. An engineer can run the code and follow along.

The real problem: the numbers change with the run date, and the wrong people get chased

The mess in receivables is not in the addition. It is in untidy data and unstable dates. Consider three hypothetical scenarios. They are not projects from any BT San customer.

  • A wholesaler that gives two kinds of credit, 30 days and 60 days: the old report calculated aging from the invoice date, so a customer on 60-day credit looked overdue for a long time even though the invoice was not yet due. Sales called a customer who had not defaulted.
  • A contractor who pays in installments and has a credit note: an invoice for 800, 200 paid, and another credit note. If the report shows the full amount or deducts twice, the month-end figure will not match the trial balance.
  • A transfer with no reference: a customer transfers 300 without saying which invoice it pays. The customer's total balance stays too high for weeks, until someone chases something that was already paid.

The root causes are three things that design can fix: clear, repeatable rules for due dates and aging as of a given date; explicitly written rules for applying payments; and a follow-up log that cannot be edited after the fact. The rule for who must be contacted and when is business policy. The code's job is to make that policy apply the same way every time.

How typical ERP systems do it: what is known and what must not be assumed

TopicWhat the documentation saysEffect on our code
Report reference dateThe ERPNext documentation says the Accounts Receivable report lets you choose a Report Date. Outstanding amounts are shown as of that date, and payments dated after the report date are not counted unless you choose to show future payments.Every function takes an asOf parameter and filters every document type by that date.
Basis for agingThe ERPNext documentation lets you age from the Due Date or the Posting Date, as reviewed, and has a view by Payment Terms that splits the amount by installment. The documentation does not state the starting day ranges, so you must check the settings.The example ages from the due date and sets its own day ranges. These must be agreed with accounting.
Follow-up levels and daysThe Odoo 18 documentation lets you set the number of days for each follow-up level, counted from the due date. A negative value sends a reminder before the due date. Each level can send an email, a letter or an SMS, and can create an activity for the person responsible.Our queue rules follow the same approach: remind before, remind after, call, escalate.
Next follow-up dateThe Odoo 18 documentation says the Next reminder date is set automatically when processing and can be edited by hand. It recommends reconciling bank statement lines before starting follow-up.Store the promised payment date and the next step in the follow-up log instead of guessing from dates.
Excluding an invoiceThe Odoo 18 documentation page that could be opened does not explain how to exclude a disputed invoice from automatic follow-up.The skip-disputed-invoices rule in this article is our own design. It does not claim that any system works this way.
Aging table and expected credit lossAn article explaining IFRS 9 says most short-term trade receivables use the simplified approach, which measures lifetime expected credit losses from initial recognition, and that a provision matrix grouped by aging is a common method.Our aging table is a starting point for accounting. It is not a calculation of the allowance for doubtful accounts.
Summary of the ERPNext documentation (docs.frappe.io), the Odoo 18 documentation, and an article explaining IFRS 9 by Lux Actuaries, as accessed on 2026-11-21. Read the documentation for the product version and the standard you actually use.

The Wikipedia definition of DSO (Days Sales Outstanding) is the receivables balance at a point in time divided by average daily sales, giving a number of days rather than money. This definition leaves several choices open (ending or average receivables, how many days of sales). This article picks one and writes it in the code. See step 5.

Overview of the example

All the code is in the examples/accounts-receivable-aging-follow-up/ folder. It uses only Node 24 built-ins, including the node:sqlite module. There is no npm install. TypeScript runs directly with the command node file.ts. (Node only strips the types and does not type-check, so the example does not use enum or namespace, and import statements must include the .ts extension, as the Node documentation says.) Money is stored in satang (integers) to avoid decimal fractions.

FileRole
aging.tsPure functions: due date, aging buckets, payment allocation, credit notes, DSO
followup.tsFollow-up queue rules and skipping disputed invoices
schema.sqlSQLite tables and the triggers that make the follow-up log append-only
data.tsSample data with edge cases, and the database read and write functions
demo.ts / aging.test.tsA script that builds the report and queue, and a node:test suite with 9 cases

The sample data has 4 customers and 8 invoices, with 30-day and 60-day credit terms, partial payments, 1 credit note, a payment with no reference, a payment that references an invoice number that does not exist, a payment dated after month end, and 1 disputed invoice.

Step 1: due dates, and aging buckets with clear boundaries

The due date is the invoice date plus the number of days in the credit term. Days overdue is the report date minus the due date. The due date itself is day 0 and does not yet count as overdue. The agreed buckets are not yet due (0 and below), 1 to 30, 31 to 60, 61 to 90, and over 90.

aging.ts · lines 14–23
export const dueDate = (issued: string, termDays: number): string => addDays(issued, termDays);
// Due day itself is NOT overdue: it is day 0.
export const daysPastDue = (due: string, asOf: string): number => num(asOf) - num(due);
export function bucketOf(d: number): string {
  if (d <= 0) return "not due";
  if (d <= 30) return "1-30";
  if (d <= 60) return "31-60";
  if (d <= 90) return "61-90";
  return "over 90";
}
aging.ts: the boundary is d <= 30, so day 30 is still in the 1-30 bucket and day 31 moves to the next one
  • All dates are bound as YYYY-MM-DD text and converted to a UTC day number before subtracting. Local time is not used, so time zones and daylight saving time cannot throw off the day difference.
  • The credit term is copied onto the invoice when the document is issued. If the report read it from the customer record at run time, editing a customer's terms later would change last month's report.
  • The boundaries must be agreed in writing. Sales sometimes counts day 30 as part of the first bucket and sometimes stops at day 29. The code and the test suite lock the boundary in place. Whoever changes it must change the tests too.

Step 2: the report as of a given date, repeatable every time

The month-end report must give the same numbers no matter which day it is run. The only way is to filter everything by the report date (asOf). Invoices issued after that date, payments dated after that date, and credit notes dated after that date are not counted. This is not reading the current state of each row and subtracting. Pulling the outstanding amount from a balance column that is updated all the time cannot be reproduced for a past date.

aging.ts · lines 25–70
export function computeAging(asOf: string, invoices: Invoice[], payments: Payment[], notes: CreditNote[], mode: Mode) {
  const warnings: string[] = [];
  const rows = new Map<string, Row>();
  for (const inv of invoices.filter((i) => i.issued <= asOf)) {
    const due = dueDate(inv.issued, inv.termDays);
    const d = daysPastDue(due, asOf);
    rows.set(inv.id, { invoice: inv, due, daysPastDue: d, bucket: bucketOf(d), credited: 0, paid: 0, open: inv.amount });
  }
  for (const n of notes.filter((n) => n.date <= asOf)) {
    const r = rows.get(n.invoiceId);
    if (!r) { warnings.push(`credit note ${n.id}: invoice ${n.invoiceId} not found as of ${asOf}`); continue; }
    const used = Math.min(n.amount, r.open);
    if (used < n.amount) warnings.push(`credit note ${n.id}: exceeds open balance of ${r.invoice.id}, capped`);
    r.credited += used; r.open -= used;
  }
  const pool: Unapplied[] = [];
  const pays = payments.filter((p) => p.received <= asOf).sort((a, b) => a.received.localeCompare(b.received) || a.id.localeCompare(b.id));
  const paidDate = new Map(pays.map((p) => [p.id, p.received]));
  for (const p of pays) {
    const r = p.invoiceId ? rows.get(p.invoiceId) : undefined;
    if (p.invoiceId && (!r || r.invoice.customerId !== p.customerId)) {
      warnings.push(`payment ${p.id}: invoice ${p.invoiceId} unknown or belongs to another customer, treated as cash without a reference`);
      pool.push({ paymentId: p.id, customerId: p.customerId, amount: p.amount });
    } else if (r) {
      const used = Math.min(p.amount, r.open);
      r.paid += used; r.open -= used;
      if (used < p.amount) { warnings.push(`payment ${p.id}: overpaid ${r.invoice.id}, excess kept as unapplied`); pool.push({ paymentId: p.id, customerId: p.customerId, amount: p.amount - used }); }
    } else pool.push({ paymentId: p.id, customerId: p.customerId, amount: p.amount });
  }
  // simplified: oldest-first runs after named payments, not interleaved by date; production should replay payments in order and store allocations as rows.
  const unapplied: Unapplied[] = [];
  for (const u of pool) {
    if (mode === "oldest_first") {
      const when = paidDate.get(u.paymentId)!;
      const targets = [...rows.values()].filter((r) => r.invoice.customerId === u.customerId && r.open > 0 && r.invoice.issued <= when)
        .sort((a, b) => a.due.localeCompare(b.due) || a.invoice.id.localeCompare(b.invoice.id));
      for (const r of targets) {
        const used = Math.min(u.amount, r.open);
        r.paid += used; r.open -= used; u.amount -= used;
        if (u.amount === 0) break;
      }
    }
    if (u.amount > 0) unapplied.push(u);
  }
  return { asOf, mode, rows: [...rows.values()], unapplied, warnings };
}
aging.ts: computeAging filters by asOf, applies credit notes, applies payments that name an invoice, and then handles payments with no reference

Three places in this function are easy to get wrong.

  • A credit note larger than the remaining balance is capped and produces a warning. It does not silently push the balance negative.
  • A payment that references an invoice number that does not exist, or one that belongs to another customer, is treated as a payment with no reference, with a warning. It is not applied to an invoice that is not theirs.
  • If a customer pays more than the named invoice, the excess does not vanish. It becomes unapplied money for someone to review.

Step 3: applying payments: by named invoice, then oldest first

A payment that names an invoice number is applied to that invoice. A payment with no reference has two options. The first (named_only) leaves it as unapplied money until someone specifies the invoice. The report temporarily shows a higher outstanding amount than the truth, but it does not guess on the customer's behalf. The second (oldest_first) applies it to that customer's oldest due invoice first, and only to invoices issued on or before the payment date. The two options give clearly different results in the example. See the run output below.

Oldest-first application is a default many businesses use, but it is not a universal rule. A customer may have meant to pay a newer invoice first, or may have a special agreement. If the oldest invoice is disputed, applying money to it may not match the payer's intent. Accounting should choose one option as policy, and in a real system every application should be recorded as its own row. This example recalculates each time so that it is easy to reproduce.

Step 4: the follow-up queue: rules that can be written as code

The example policy is: remind within 7 days before the due date (including the due date itself), send an email when 1 to 14 days overdue, call at 15 days or more overdue, and escalate and propose a credit hold at 45 days or more overdue. The numbers 7, 15 and 45 are assumed values that must be agreed with the business.

followup.ts · lines 10–31
// simplified: thresholds are global; production keeps them per customer segment and per credit term.
export function buildQueue(rows: Row[], log: LogEntry[], asOf: string, policy: Policy = DEFAULT_POLICY) {
  const actions: Action[] = [];
  const disputed: Row[] = [];
  const holds = new Set<string>();
  for (const r of rows) {
    if (r.open <= 0) continue;
    if (r.invoice.disputed) { disputed.push(r); continue; }
    const last = log.filter((l) => l.invoiceId === r.invoice.id && l.at <= asOf).at(-1);
    const waiting = last?.promiseDate != null && last.promiseDate >= asOf;
    const d = r.daysPastDue;
    let action = "none";
    if (d <= 0) { if (-d <= policy.remindBeforeDays) action = "reminder_before_due"; }
    else if (d >= policy.escalateAtDays) action = "escalate_credit_hold";
    else if (d >= policy.callAtDays) action = "call";
    else action = "email_reminder";
    if (action !== "none" && waiting) action = "wait_promise_to_pay";
    if (action === "escalate_credit_hold") holds.add(r.invoice.customerId);
    if (action !== "none") actions.push({ invoiceId: r.invoice.id, customerId: r.invoice.customerId, action, daysPastDue: d, open: r.open });
  }
  return { actions, disputed, creditHold: [...holds].sort() };
}
followup.ts: buildQueue skips disputed invoices, waits for the promised payment date, and collects customers who should have a credit hold
  • An invoice with a dispute never enters the automatic queue, but it does not disappear from the report. It is split out as its own list so that someone is responsible for clearing the dispute. Sending repeated reminders to a customer who is disputing damages the relationship and does not help collect the money.
  • If the latest log entry has a promised payment date (promise-to-pay) and that date has not passed, the queue shows wait_promise_to_pay instead of chasing again. The promised date itself still counts as waiting. Once the date has passed, chasing resumes.
  • A credit hold is a proposal at the end of the queue, not an automatic action. It should go through approval (see the article on multi-level approval and delegation) because it affects the customer's purchasing immediately.

Step 5: an append-only follow-up log, and DSO

The follow-up log must be able to answer who made contact, when, through which channel, what the customer said, which date they promised to pay, and what the next step is. A common problem is that people edit old entries to make them look better, or delete them. This example uses SQLite triggers to reject UPDATE and DELETE. If an entry is wrong, you add a new row that corrects the understanding.

schema.sql · lines 32–47
-- Append-only: a wrong entry is corrected by adding a new row, never by editing.
CREATE TABLE followups (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  invoice_id TEXT NOT NULL REFERENCES invoices(id),
  at TEXT NOT NULL,
  by_user TEXT NOT NULL,
  channel TEXT NOT NULL,
  outcome TEXT NOT NULL,
  promise_date TEXT,
  next_action TEXT
) STRICT;

CREATE TRIGGER followups_no_update BEFORE UPDATE ON followups
BEGIN SELECT RAISE(ABORT, 'followups is append-only'); END;
CREATE TRIGGER followups_no_delete BEFORE DELETE ON followups
BEGIN SELECT RAISE(ABORT, 'followups is append-only'); END;
schema.sql: the followups table and the triggers that reject edits and deletes
data.ts · lines 54–61
export function appendFollowup(db: DatabaseSync, e: LogEntry): void {
  db.prepare("INSERT INTO followups (invoice_id, at, by_user, channel, outcome, promise_date, next_action) VALUES (?, ?, ?, ?, ?, ?, ?)")
    .run(e.invoiceId, e.at, e.byUser, e.channel, e.outcome, e.promiseDate, e.nextAction);
}
export function readLog(db: DatabaseSync, asOf: string): LogEntry[] {
  return db.prepare("SELECT invoice_id AS invoiceId, at, by_user AS byUser, channel, outcome, promise_date AS promiseDate, next_action AS nextAction FROM followups WHERE at <= ? ORDER BY at, id")
    .all(asOf) as unknown as LogEntry[];
}
data.ts: adding an entry, and reading only entries dated no later than asOf

Reading the log is also filtered by asOf. The follow-up queue for October 31 therefore does not see entries added in November.

DSO in the example has a single, clear definition: the outstanding balance of all invoices as of the report date (after credit notes and applied payments, including invoices not yet due and disputed invoices, without deducting unapplied money), divided by the invoices issued in the last 90 days including the report date, multiplied by 90. Other companies may use average receivables or a different sales window. Agree on one definition and use it every month, because numbers cannot be compared across definitions.

aging.ts · lines 78–85
// DSO = ending open invoice balance at asOf / invoiced in the last `window` days x window.
// Unapplied cash is NOT netted; disputed and not-yet-due invoices ARE included.
export function dso(rows: Row[], invoices: Invoice[], asOf: string, window = 90): number {
  const from = addDays(asOf, -(window - 1));
  const sales = invoices.filter((i) => i.issued >= from && i.issued <= asOf).reduce((s, i) => s + i.amount, 0);
  const ar = rows.reduce((s, r) => s + r.open, 0);
  return sales === 0 ? 0 : (ar / sales) * window;
}
aging.ts: dso, with the definition written in the comment above the function

A real run: the month-end report, the queue and the log

demo.ts builds an in-memory database from the sample data. It then produces the report as of 2026-10-31 in both modes, the follow-up queue, an attempt to edit and delete log entries, and the report as of 2026-11-30.

demo.ts · lines 8–19
const show = (asOf: string, mode: Mode) => {
  const a = computeAging(asOf, INVOICES, PAYMENTS, CREDIT_NOTES, mode);
  const t = bucketTotals(a.rows);
  console.log(`as of ${asOf}, mode ${mode}`);
  for (const r of a.rows) if (r.open > 0 || r.paid > 0)
    console.log(`  ${r.invoice.id} due ${r.due} days ${String(r.daysPastDue).padStart(4)} ${r.bucket.padEnd(8)} open ${m(r.open)}${r.invoice.disputed ? "  DISPUTED" : ""}`);
  console.log("  buckets: " + BUCKETS.map((b) => `${b}=${(t[b] / 100).toFixed(2)}`).join("  "));
  console.log(`  unapplied cash: ${a.unapplied.map((u) => `${u.paymentId}=${(u.amount / 100).toFixed(2)}`).join(", ") || "none"}`);
  for (const w of a.warnings) console.log(`  warning: ${w}`);
  console.log(`  DSO(90 days) = ${dso(a.rows, INVOICES, asOf).toFixed(1)} days`);
  return a;
};
demo.ts: the show function prints the report, aging buckets, unapplied money, warnings and DSO
output.txt
1) month-end report, payment without invoice reference left unapplied
as of 2026-10-31, mode named_only
  INV-001 due 2026-08-31 days   61 61-90    open    600.00
  INV-002 due 2026-10-01 days   30 1-30     open    500.00
  INV-003 due 2026-10-30 days    1 1-30     open    300.00
  INV-004 due 2026-09-30 days   31 31-60    open    800.00
  INV-005 due 2026-12-14 days  -44 not due  open    600.00
  INV-006 due 2026-07-15 days  108 over 90  open    600.00
  INV-007 due 2026-09-19 days   42 31-60    open    300.00  DISPUTED
  INV-008 due 2026-10-31 days    0 not due  open    450.00
  buckets: not due=1050.00  1-30=800.00  31-60=1100.00  61-90=600.00  over 90=600.00
  unapplied cash: P5=50.00, P3=300.00
  warning: payment P5: invoice INV-999 unknown or belongs to another customer, treated as cash without a reference
  DSO(90 days) = 166.0 days

2) same date, oldest-first allocation of unapplied cash
as of 2026-10-31, mode oldest_first
  INV-001 due 2026-08-31 days   61 61-90    open    600.00
  INV-002 due 2026-10-01 days   30 1-30     open    500.00
  INV-003 due 2026-10-30 days    1 1-30     open    300.00
  INV-004 due 2026-09-30 days   31 31-60    open    500.00
  INV-005 due 2026-12-14 days  -44 not due  open    600.00
  INV-006 due 2026-07-15 days  108 over 90  open    600.00
  INV-007 due 2026-09-19 days   42 31-60    open    300.00  DISPUTED
  INV-008 due 2026-10-31 days    0 not due  open    400.00
  buckets: not due=1000.00  1-30=800.00  31-60=800.00  61-90=600.00  over 90=600.00
  unapplied cash: none
  warning: payment P5: invoice INV-999 unknown or belongs to another customer, treated as cash without a reference
  DSO(90 days) = 152.0 days

3) follow-up queue as of 2026-10-31
  INV-001 escalate_credit_hold (days 61, open 600.00)
  INV-002 call (days 30, open 500.00)
  INV-003 email_reminder (days 1, open 300.00)
  INV-004 call (days 31, open 500.00)
  INV-006 wait_promise_to_pay (days 108, open 600.00)
  INV-008 reminder_before_due (days 0, open 400.00)
  credit hold: C1
  disputed, listed separately: INV-007

4) append-only log
  UPDATE rejected: followups is append-only
  DELETE rejected: followups is append-only
  rows in log: 3

5) the same report for 2026-10-31 again, and one for a later date
  10-31 identical on re-run: true
as of 2026-11-30, mode oldest_first
  INV-001 due 2026-08-31 days   91 over 90  open      0.00
  INV-002 due 2026-10-01 days   60 31-60    open    500.00
  INV-003 due 2026-10-30 days   31 31-60    open    300.00
  INV-004 due 2026-09-30 days   61 61-90    open    500.00
  INV-005 due 2026-12-14 days  -14 not due  open    600.00
  INV-006 due 2026-07-15 days  138 over 90  open    600.00
  INV-007 due 2026-09-19 days   72 61-90    open    300.00  DISPUTED
  INV-008 due 2026-10-31 days   30 1-30     open    400.00
  buckets: not due=600.00  1-30=400.00  31-60=800.00  61-90=800.00  over 90=600.00
  unapplied cash: none
  warning: payment P5: invoice INV-999 unknown or belongs to another customer, treated as cash without a reference
  DSO(90 days) = 320.0 days
Output from a real run on 2026-11-21 with node --no-warnings demo.ts (Node 24)

Reading the output point by point

  1. Invoice INV-002 was due 2026-10-01. At month end it is 30 days overdue, in the 1-30 bucket. INV-004 is 31 days overdue, in the 31-60 bucket. INV-008 is due on exactly 10-31, which is day 0, so it is not yet due.
  2. The outstanding amount of INV-001 is 600, not 1,000, because 400 has been received. The other payment of 600, dated 2026-11-05, is not counted in the October month-end report. In the report as of 11-30, this invoice is 0.
  3. In named_only mode, the unapplied payments P3 (300, no reference) and P5 (50, references INV-999, which does not exist, with a warning) stay as unapplied money. The 31-60 bucket totals 1,100 and DSO is 166.0 days.
  4. In oldest_first mode, P3 is applied to INV-004, leaving 500, and P5 is applied to INV-008, leaving 400. The 31-60 bucket drops to 800, not yet due becomes 1,000, and DSO falls to 152.0 days. This shows that the payment application policy really does change the report, so it must be written down clearly.
  5. Invoice INV-007 (disputed) still appears in the aging report with an amount of 300 after the 100 credit note, but it is not in the queue. It is split out as a separate item.
  6. Queue: INV-001 is escalated (over 61 days overdue), so a credit hold is proposed for customer C1. INV-002 and INV-004 get a call. INV-003 gets an email. INV-008 gets a reminder before the due date. INV-006, which is 108 days overdue, is parked as wait_promise_to_pay because there is a log entry with a promised payment date of 2026-11-05, so it is not proposed for a credit hold.
  7. Trying to UPDATE and DELETE a follow-up log entry is rejected, while adding a new entry works. Running the 10-31 report again after adding entries gives the same result character for character (true).

DSO is high for this data set because the invoice amounts in the last 90 days are small compared with the old outstanding balances. This is a result of the sample data. It is not a reference figure for any business.

The test suite

aging.test.ts has 9 cases. Run it with node --no-warnings --test aging.test.ts and you get 9 passes. The main cases are the aging boundary between 30 and 31 (at both the function level and the whole calculation path), a partially paid invoice, an overpayment, a payment that references the wrong invoice, oldest-first application that does not apply to invoices issued after the payment date, the repeatability of a report as of the same date, skipping disputed invoices, the promised payment date, DSO, and a log that cannot be edited.

aging.test.ts · lines 19–26
test("bucket boundaries: 30 vs 31, 60 vs 61, 90 vs 91", () => {
  const cases: [number, string][] = [[-5, "not due"], [1, "1-30"], [30, "1-30"], [31, "31-60"], [60, "31-60"], [61, "61-90"], [90, "61-90"], [91, "over 90"]];
  for (const [d, b] of cases) assert.equal(bucketOf(d), b, `day ${d}`);
  // through the whole pipeline: due 2026-10-01, as of 10-31 is day 30, as of 11-01 is day 31
  const i = [inv("A", "2026-09-01", 30)];
  assert.equal(computeAging("2026-10-31", i, [], [], "named_only").rows[0].bucket, "1-30");
  assert.equal(computeAging("2026-11-01", i, [], [], "named_only").rows[0].bucket, "31-60");
});
aging.test.ts: tests the boundary between day 30 and day 31
aging.test.ts · lines 50–57
test("as-of reproducibility: later records never change an earlier report", () => {
  const before = computeAging("2026-10-31", INVOICES, PAYMENTS, CREDIT_NOTES, "oldest_first");
  const withLate = [...PAYMENTS, { id: "LATE", customerId: "C2", received: "2026-11-02", amount: 99900, invoiceId: "INV-004" }];
  const again = computeAging("2026-10-31", INVOICES, withLate, CREDIT_NOTES, "oldest_first");
  assert.deepEqual(again, before);
  const later = computeAging("2026-11-30", INVOICES, PAYMENTS, CREDIT_NOTES, "oldest_first");
  assert.equal(later.rows.find((r) => r.invoice.id === "INV-001")!.open, 0); // P4 is dated 2026-11-05
});
aging.test.ts: a payment dated after asOf does not change the earlier report
aging.test.ts · lines 59–65
test("disputed invoice is excluded from automatic actions but listed separately", () => {
  const a = computeAging("2026-10-31", INVOICES, PAYMENTS, CREDIT_NOTES, "oldest_first");
  const q = buildQueue(a.rows, [], "2026-10-31");
  assert.ok(!q.actions.some((x) => x.invoiceId === "INV-007"));
  assert.deepEqual(q.disputed.map((r) => r.invoice.id), ["INV-007"]);
  assert.ok(q.actions.some((x) => x.invoiceId === "INV-001" && x.action === "escalate_credit_hold"));
});
aging.test.ts: a disputed invoice is not in the queue but is split out as a separate item

Putting it to real use: what the example leaves out

  • Store payment applications in an allocations table (payment number, invoice number, amount, application date, who applied it) instead of recalculating each time. Allow back-dated applications only while the accounting period is still open.
  • Each invoice may have several payment installments. ERPNext has a payment-terms view that splits the amount by installment. This example uses a single due date per invoice.
  • Customer payments with withholding tax deducted, bank fees, or multiple currencies need rules for handling small differences, and the tax treatment must be checked with the company's accountant.
  • The total in the aging report must reconcile with the receivables control account in the general ledger as of the same date. If it does not, find the cause before sending the report.
  • Permissions: who can edit credit terms, mark an invoice as disputed, and lift a credit hold must be separate roles, with history (see the article on change history).
  • Sending real emails or messages should run in a separate job queue, and the result of each send should be recorded in the follow-up log.

Hypothetical examples: applying this to three businesses

A building materials distributor selling on several credit terms

Contractor customers have both 30-day and 60-day terms and often make one transfer covering several invoices. The points to decide are the rule for lump-sum payments (oldest first, or accounting matches them by hand), and keeping invoices disputed over incomplete deliveries out of the chasing.

A monthly service company

Recurring monthly invoices mean a single customer can have several overdue invoices at once. The queue should merge them into one contact per customer, not one call per invoice. This example proposes items at the invoice level. To merge them, add a grouping layer per customer.

A factory selling to corporate customers

Corporate customers often have fixed payment runs for checks or transfers. A promised payment date in the log is therefore more useful than the due date. A credit hold also needs an approval step from the sales manager and finance before it affects order intake, which connects to the related sales and inventory documentation pages.

Common mistakes and a checklist

  • Calculating aging from the invoice date even though customers have different credit terms.
  • A report that pulls the outstanding amount from a column that is updated all the time, so past reports change when new payments arrive.
  • Not deciding how to handle payments with no reference, and leaving them with no owner.
  • Applying a payment to an invoice issued after the payment date.
  • Sending automatic reminders for a disputed invoice, or for an invoice where the customer has already given a promised payment date.
  • Placing a credit hold automatically with no one approving it.
  • Editing or deleting old follow-up entries, leaving no evidence of who did what and when.
  • Reporting to executives without reconciling to the receivables control account, and without stating the date of the data.
  • Comparing DSO across months using a definition that keeps changing.
  1. Agree on the aging bucket definitions, the boundary between day 30 and day 31, and day 0 in writing.
  2. Every report takes an asOf date and filters every document type by that date.
  3. The credit term is copied onto the invoice when the document is issued.
  4. Choose a policy for payments with no reference, and record every application as a row.
  5. A disputed invoice stays in the report but not in the automatic queue, and has an owner.
  6. The follow-up log is append-only, with a promised payment date and a next step.
  7. A credit hold goes through approval.
  8. The total is reconciled to the receivables control account before the report goes out.
  9. There is a test suite for the aging boundaries, partial payment, repeatability and skipping disputed invoices.

Caution: this article is a technical example. It is not accounting or tax advice. The aging table is not a calculation of the allowance for doubtful accounts under IFRS 9 or the accounting standard your company uses. It does not cover revenue recognition, value-added tax, withholding tax, or the legal rules on debt collection. Confirm the day-count policy, payment application and bad-debt write-offs with your company's accountant before use. The example has no user permissions, no real message-sending queue, no multiple currencies, and no installment payments. Use it as a learning model, not as production-ready code.

References

  1. ERPNext — Accounts Receivable report (report date, ageing basis, payment terms) (accessed 2026-11-21)
  2. Odoo 18 — Follow-up on invoices (follow-up levels, delay in days, next reminder date) (accessed 2026-11-21)
  3. Lux Actuaries — IFRS 9 ECL for trade receivables: simplified approach and provision matrix (accessed 2026-11-21)
  4. Wikipedia — Days sales outstanding (definition and formula) (accessed 2026-11-21)
  5. Node.js — SQLite (node:sqlite, stability index) (accessed 2026-11-21)
  6. Node.js — Running TypeScript natively (type stripping) (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer