27 分鐘閱讀 · ERP 與 CRM

月底,經理要帳齡報表。會計部跑出一個數字,三天後業務部再跑一次,得到另一個數字,因為這期間又有收款進來,也有人改了發票日期。有位客戶已經付款,卻仍被電話催收;另一位客戶因貨品瑕疵存在爭議,卻收到了第三封自動催款電子郵件;還有一筆轉帳沒有附發票編號,就一直躺在暫記帳戶裡,沒有人替它沖銷。
本文帶你把應收帳款追蹤的核心部分寫得正確且可測試,使用 Node 24 可直接執行的 TypeScript,以及 Node 內建的 SQLite,不需安裝任何東西。經理讀說明和表格就能理解,工程師可以直接跟著執行程式碼。
實際問題:數字隨執行日期而變,被催的人也找錯了
應收帳款的麻煩不在於加總,而在於資料不整齊、日期不穩定。來看三個假設情境,它們不是 BT San 任何客戶的專案。
- 批發商提供 30 天和 60 天兩種信用期:舊報表從開立發票日起算帳齡,所以信用期 60 天的客戶看起來拖欠很久,其實還沒到期。業務部卻打電話去催了並未違約的客戶。
- 承包商分期付款,並有一張貸項通知單:發票金額 800,已付 200,另有一張貸項通知單。如果報表顯示全額或重複扣減,月底數字就會和試算表對不上。
- 沒有參考編號的轉帳:客戶轉了 300,卻沒說付的是哪一張發票,整個客戶的未收餘額因此虛高好幾個星期,以致有人去追討已經付清的款項。
根本原因有三個,都可以靠設計解決:一是明確且在指定日期可重複的到期日與帳齡計算規則;二是直接寫明的收款沖銷規則;三是事後無法修改的追蹤紀錄。至於誰要在何時被聯絡,則是企業的政策,程式碼的作用是讓這項政策每次都以同樣的方式執行。
一般 ERP 系統怎麼做:哪些已知,哪些不能假設
| 事項 | 文件怎麼說 | 對我們程式碼的影響 |
|---|---|---|
| 報表的基準日期 | ERPNext 文件指出,Accounts Receivable 報表可以選擇報表日期(Report Date),未收餘額依該日期顯示,晚於報表日期入帳的收款不會計入,除非選擇顯示未來付款。 | 每個函式都接收參數 asOf,並用該日期過濾所有類型的單據 |
| 帳齡的計算基準 | ERPNext 文件允許選擇依到期日(Due Date)或過帳日期(Posting Date)計算帳齡,並提供依付款條件(Payment Terms)分期拆分金額的檢視。文件沒有規定起始天數區間,需要看設定。 | 範例選擇從到期日起算,並自行設定區間,需要與會計部門商定 |
| 追蹤等級與天數 | Odoo 18 文件允許為每個等級(follow-up level)設定天數,從到期日起算;填負值可在到期前提醒。每個等級可選擇寄送電子郵件、信函或 SMS,並可為負責人設定活動。 | 我們的佇列規則思路相同:到期前提醒、到期後提醒、電話、升級 |
| 下次追蹤日期 | Odoo 18 文件指出,下次提醒日期(Next reminder date)會在處理時自動設定,也可以手動修改,並建議在開始追蹤前先核對銀行明細。 | 把約定付款日和下一步保存在追蹤紀錄裡,而不是根據日期去猜 |
| 發票的排除 | 所查閱的 Odoo 18 文件頁面沒有說明如何把有爭議的發票排除在自動追蹤之外。 | 本文中跳過爭議發票的規則是我們自己的設計,並不宣稱某個系統是這樣做的 |
| 帳齡表與預期信用損失評估 | 解釋 IFRS 9 的文章指出,大多數短期應收帳款使用簡化方法(simplified approach),在初始認列時就衡量整個存續期間的預期信用損失,而依帳齡分組的準備矩陣(provision matrix)是常見做法。 | 我們的帳齡表是提供給會計的基礎資料,不是呆帳準備的計算 |
Wikipedia 對 DSO(Days Sales Outstanding,應收帳款周轉天數)的定義是:某一時點的應收帳款餘額,除以平均每日銷售額,結果以天為單位,而不是金額。這個定義留有多種選擇(用期末應收還是平均應收,銷售額取多少天),本文只選一種並寫在程式碼裡,見步驟 5。
範例概覽
全部程式碼都在 examples/accounts-receivable-aging-follow-up/ 資料夾中,只使用 Node 24 的內建功能,包括 node:sqlite 模組,不需 npm install。TypeScript 直接用指令 node 檔案.ts 執行(Node 只是去掉型別,不做型別檢查,所以不使用 enum 或 namespace,並且依 Node 文件要求,import 敘述中必須寫 .ts 副檔名)。金額以 satang(整數)保存,以避免小數誤差。
| 檔案 | 作用 |
|---|---|
| aging.ts | 純函式:到期日、帳齡區間、收款沖銷、貸項通知單、DSO |
| followup.ts | 追蹤佇列規則,以及跳過爭議發票 |
| schema.sql | SQLite 資料表,以及讓追蹤紀錄只增不改的 trigger |
| data.ts | 含邊界情況的假設資料,以及讀寫資料庫的函式 |
| demo.ts / aging.test.ts | 產生報表和佇列的腳本,以及 9 個案例的 node:test 測試套件 |
假設資料包含 4 位客戶、8 張發票,信用期為 30 天和 60 天,部分付款,1 張貸項通知單,沒有參考編號的收款,引用了不存在的發票編號的收款,入帳日期晚於月底的收款,以及 1 張被提出異議的發票。
步驟 1:到期日,以及界線清楚的帳齡區間
到期日是開立發票日加上信用期的天數。逾期天數是報表日期減去到期日。到期日當天是第 0 天,還不算逾期。約定的帳齡區間是:未到期(0 及以下)、1 至 30、31 至 60、61 至 90 以及超過 90。
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";
}- 所有日期都綁定為 YYYY-MM-DD 文字,先轉成 UTC 的天數再相減,不使用本地時間,避免時區或日光節約時間讓天數之差出現偏差。
- 信用期在開立發票時就複製到發票上。如果在執行報表時才去讀取客戶資料,之後修改客戶的信用期,就會讓上個月的報表跟著改變。
- 界線必須以書面方式約定。業務部有時把 30 天算作第一個區間並包含第 30 天,有時只算到第 29 天。程式碼和測試套件把界線鎖定,誰要改就必須同時修改測試。
步驟 2:截至指定日期的報表,每次都可重複
月底報表不論哪天執行,都必須得到同樣的數字,唯一的做法是用報表日期(asOf)過濾一切:該日期之後開立的發票、該日期之後入帳的收款、該日期之後入帳的貸項通知單都不計入,而不是讀取列的目前狀態再去減。從一直在更新的 balance 欄位取未收餘額,是無法回溯的。
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 };
}這個函式裡有三處容易出錯。
- 超過餘額的貸項通知單會被限制,並發出警告,而不是悄悄讓餘額變成負數。
- 引用了不存在的發票編號,或屬於其他客戶的發票編號的收款,會被當作沒有參考編號的收款並附上警告,而不是沖銷到不屬於他的發票上。
- 付款超過所指定的發票時,多出的部分不會消失,而是變成未沖銷款項(unapplied),交給人工檢查。
步驟 3:收款沖銷:指定發票,最舊優先
指定了發票編號的收款沖銷該發票。沒有參考編號的收款有兩種選擇。第一種(named_only)保留為未沖銷款項,直到有人指定,報表會暫時顯示高於實際的未收餘額,但不替客戶猜測。第二種(oldest_first)先沖銷該客戶到期日最舊的發票,並且只沖銷開立發票日不晚於收款日的發票。兩種方式的結果在範例中差別明顯,見下面的執行結果。
最舊優先的沖銷方式是許多企業採用的預設做法,但並非通行規則。客戶可能有意先付新的發票,或有特別約定;而且如果最舊的發票是有爭議的發票,把款項沖銷給它可能不符合付款人的本意。應由會計部門選定其中一種作為政策,並且在真實系統裡每一筆沖銷都應記錄成獨立的一列。本範例每次重新計算,是為了便於重複。
步驟 4:追蹤佇列:可以寫成程式碼的規則
範例政策是:到期前 7 天內(含到期日)提醒;逾期 1 至 14 天寄送電子郵件;逾期 15 天以上打電話;逾期 45 天以上升級並建議暫停信用。7、15、45 這幾個數字是假設值,需要與企業商定。
// 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() };
}- 有異議的發票完全不進入自動佇列,但不會從報表中消失,而是單獨列為一項,讓有人負責去釐清爭議。向正在提出異議的客戶反覆發催款提醒,會破壞關係,也無助於收到款項。
- 如果最新一筆紀錄裡有約定付款日(promise-to-pay),而約定日還沒過,佇列顯示 wait_promise_to_pay,而不是再次催收。約定日當天仍算等待,過了約定日才重新催收。
- 暫停信用是佇列末端的建議,不是自動動作。應經過核准(參見關於多級核准與授權委託的文章),因為它會立刻影響該客戶的銷售。
步驟 5:只增不改的追蹤紀錄,以及 DSO
追蹤紀錄必須能回答:誰聯絡的、什麼時候、透過什麼管道、客戶怎麼回覆、約定哪天付款、下一步是什麼。常見的問題是有人為了好看去改舊紀錄,或把它刪掉。本範例使用 SQLite 的 trigger 拒絕 UPDATE 和 DELETE,如果記錯了,就新增一列來更正理解。
-- 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;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[];
}讀取紀錄時同樣用 asOf 過濾,所以 10 月 31 日的追蹤佇列看不到 11 月新增的紀錄。
範例中的 DSO 只採用一種明確的定義:報表日期當天所有發票的未收餘額(已扣除貸項通知單和已沖銷款項,包含未到期的發票和有爭議的發票,不扣除未沖銷款項),除以截至報表日(含報表日)最近 90 天內開立的發票總額,再乘以 90。其他公司可能使用平均應收帳款,或不同的銷售額區間。請約定一種定義,並每個月都沿用,因為不同定義的數字無法相互比較。
// 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;
}實際執行:月底報表、佇列與紀錄
demo.ts 用假設資料在記憶體中建立資料庫,然後產生 2026-10-31 的兩種模式報表、追蹤佇列、嘗試修改和刪除紀錄,以及 2026-11-30 的報表。
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;
};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逐項解讀輸出
- 發票 INV-002 到期日為 2026-10-01,月底逾期 30 天,處於 1-30 區間;INV-004 逾期 31 天,處於 31-60 區間。INV-008 到期日恰好是 10-31,為第 0 天,所以尚未到期。
- INV-001 的未收餘額是 600,而不是 1,000,因為已經收了 400。另一筆 600 的收款入帳日期是 2026-11-05,不計入十月底的報表,但在 11-30 的報表中,該發票餘額為 0。
- named_only 模式:未沖銷款項 P3(300,沒有參考編號)和 P5(50,引用了不存在的 INV-999,並附有警告)以 unapplied 形式掛著,31-60 區間合計 1,100,DSO 為 166.0 天。
- oldest_first 模式:P3 沖銷 INV-004,剩餘 500;P5 沖銷 INV-008,剩餘 400。31-60 區間降為 800,未到期為 1,000,DSO 降為 152.0 天。可見沖銷政策確實會改變報表,所以必須寫清楚。
- 發票 INV-007(有爭議)仍出現在帳齡報表中,扣除 100 的貸項通知單後餘額為 300,但不在佇列裡,而是被單獨列為一項。
- 佇列:INV-001 升級(逾期 61 天以上),因此建議暫停客戶 C1 的信用;INV-002 和 INV-004 打電話;INV-003 寄送電子郵件;INV-008 到期前提醒;而逾期 108 天的 INV-006 因為有約定付款日 2026-11-05 的紀錄,被擱置為 wait_promise_to_pay,所以不會被建議暫停信用。
- 嘗試對追蹤紀錄執行 UPDATE 和 DELETE 都被拒絕,而新增紀錄可以。新增紀錄後重新執行 10-31 的報表,結果逐個字元都與原來一致(true)。
這組資料的 DSO 偏高,是因為 90 天內的發票金額相對於陳舊的未收餘額很少。這是假設資料造成的結果,不是任何企業的參考數字。
測試套件
aging.test.ts 有 9 個案例,用 node --no-warnings --test aging.test.ts 執行,結果 9 pass。主要案例包括:帳齡區間在 30 與 31 的界線(函式層面和整條計算鏈路)、部分付款的發票、多付以及引用了錯誤發票、不沖銷晚於收款日開立發票的最舊優先沖銷、在同一日期重複產生的報表、跳過爭議發票、約定付款日、DSO,以及無法修改的紀錄。
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");
});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
});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"));
});用於實際環境:範例略去了什麼
- 把沖銷保存為 allocations 資料表(收款編號、發票編號、金額、沖銷日期、沖銷人),而不是每次重新計算,並且只允許在帳期尚未結帳時回溯修改沖銷日期。
- 每張發票可能有多個付款期。ERPNext 有依付款條件分期拆分金額的檢視,本範例每張發票只用一個到期日。
- 客戶的收款若扣了扣繳稅款、銀行手續費,或以多種幣別付款,需要有處理小額差異的規則,並且必須與公司的會計師核對稅務問題。
- 帳齡報表的合計必須在同一日期與總分類帳中的應收帳款控制帳戶核對。如果不一致,先找出原因再發出報表。
- 權限:誰可以修改信用期、設定爭議狀態、取消暫停信用,要分開,並且要有歷史紀錄(參見關於變更歷程的文章)。
- 真正寄送電子郵件或訊息應放在獨立的工作佇列裡,並把寄送結果記入追蹤紀錄。
假設範例:套用到三種業務
多種帳期賒銷的建材經銷商
承包商客戶既有 30 天也有 60 天的信用期,並且常常一次轉帳付多張發票。需要決定的是合併付款的沖銷規則(最舊優先,還是由會計部門自行配對),並讓因貨物送達不全而被提出異議的發票從催收中分離出來。
按月提供服務的公司
每月重複開立的發票,會讓同一位客戶同時有多張逾期發票。佇列應合併成每位客戶一次聯絡,而不是每張發票一通電話。本範例給出的是發票層級的清單,如果要合併,需要增加依客戶分組的一層。
向企業客戶銷售的工廠
企業客戶往往有固定日期的支票或轉帳付款週期,所以紀錄中的約定付款日比到期日更有用;而暫停信用必須先經過業務經理和財務的核准,才能影響接單,這與相關的銷售和庫存文件頁面相銜接。
常見錯誤與檢查清單
- 從開立發票日起算帳齡,而客戶的信用期各不相同。
- 報表從一直在更新的欄位取未收餘額,因此有新收款時,歷史報表就會改變。
- 不決定沒有參考編號的收款如何處理,放著沒人負責。
- 把款項沖銷給收款日之後才開立的發票。
- 向被提出異議的發票,或客戶已給出約定付款日的發票自動發送催款提醒。
- 沒有人核准就自動暫停信用。
- 修改或刪除舊的追蹤紀錄,結果沒有證據說明誰在什麼時候做了什麼。
- 向管理層報告時沒有與應收帳款控制帳戶核對,也沒有標明資料日期。
- 用不斷變化的定義來跨月比較 DSO。
- 以書面方式約定帳齡區間的定義、第 30 天與第 31 天的界線,以及第 0 天。
- 每份報表都接收日期 asOf,並用該日期過濾所有類型的單據。
- 信用期在開立發票時複製到發票上。
- 選定處理沒有參考編號收款的政策,並把每一筆沖銷記錄成一列。
- 爭議發票出現在報表中,但不在自動佇列裡,並且有人負責。
- 追蹤紀錄只增不改,有約定付款日和下一步。
- 暫停信用要經過核准。
- 合計在發出報表前先與應收帳款控制帳戶核對。
- 有測試套件,涵蓋帳齡區間界線、部分付款、重複執行,以及跳過爭議發票。
注意:本文是技術範例,不是會計或稅務建議。帳齡表不是依 IFRS 9 或公司所用會計準則計算的呆帳準備,也不涵蓋收入認列、加值稅、扣繳稅款或催收債務的法律規定。天數界線政策、款項沖銷和呆帳沖銷,應先與公司的會計師確認再使用。範例沒有使用者權限,沒有真正發送訊息的佇列,沒有多幣別,也不支援依期付款。它是學習用的範例,不是可直接用於實際環境的程式碼。
參考資料
- ERPNext — Accounts Receivable report (report date, ageing basis, payment terms) (accessed 2026-11-21)
- Odoo 18 — Follow-up on invoices (follow-up levels, delay in days, next reminder date) (accessed 2026-11-21)
- Lux Actuaries — IFRS 9 ECL for trade receivables: simplified approach and provision matrix (accessed 2026-11-21)
- Wikipedia — Days sales outstanding (definition and formula) (accessed 2026-11-21)
- Node.js — SQLite (node:sqlite, stability index) (accessed 2026-11-21)
- Node.js — Running TypeScript natively (type stripping) (accessed 2026-11-21)




