Skip to content
AccountancyPath

Accounting for DevelopersModule 3: Workflows and integrationIntermediate5 min read

Invoice and Payment Lifecycle in Accounting Software

Model the invoice and payment lifecycle in code: state transitions, balanced journal entries for issue, tax, partial payments, credit notes and write-offs.

Lesson 7 of 16
Course outline (16 lessons)

Before this lesson:Journal and General Ledger Database DesignReversals and Audit Trails in Accounting Systems

Billing software tracks documents like invoices and payments, while the general ledger tracks financial balances. Keeping those two layers aligned — without mutating history — is the heart of accounts receivable engineering.

Invoice states and transitions

Model an invoice as a strict state machine with six core states:

State Meaning Allowed transitions Ledger impact
draft Editable before sending issued, deleted None
issued Sent; full balance owed partially_paid, paid, void, written_off Books AR, revenue and tax
partially_paid Some cash or credit applied partially_paid, paid, written_off Reduces AR per event
paid Open balance reached zero Terminal AR on invoice is $0
void Cancelled before any payment Terminal Reverses issue entry
written_off Uncollectible remainder closed Terminal Moves open AR to bad debt
Formula · Open invoice balance

open_minor = issued_total_minor − allocated_payments_minor − credit_notes_minor − write_offs_minor

issued_total_minor
subtotal plus sales tax in integer minor units
allocated_payments_minor
sum of payment allocations applied to this invoice
credit_notes_minor
sum of credit notes issued against this invoice
write_offs_minor
uncollectible balance written off

Journal entries at each step

Under accrual accounting, revenue is recognised when earned (typically at invoice issue for delivered services, or deferred to unearned revenue if billed in advance), not when cash lands in the bank.

  • Issue: Debit Accounts Receivable for the invoice total; credit Revenue for the subtotal and credit Sales Tax Payable (a liability) for collected tax.
  • Payment: Debit Cash (or Cash at Payment Processor); credit Accounts Receivable.
  • Credit note: Debit Sales Returns and Allowances (a contra-revenue account) and debit Sales Tax Payable for any proportional tax reduction; credit Accounts Receivable.
  • Void: Only allowed when no payments are allocated. Post a reversing entry mirroring the original issue entry.
  • Write-off: When an unpaid balance becomes uncollectible, debit Bad Debt Expense (or Allowance for Doubtful Accounts if you maintain an allowance reserve) and credit Accounts Receivable.
Worked example

Cedar Digital (fictional) — full invoice lifecycle for Oakridge Retail

1. Issue invoice INV-204 (1 March): $2,000 consulting fee plus 10% sales tax ($200). Status moves draft → issued; open balance = $2,200.

Entry 1: Issue INV-204
AccountDebit (Dr)Credit (Cr)
Accounts Receivable$2,200
Service Revenue$2,000
Sales Tax Payable$200
Total✓ Balanced$2,200$2,200

2. Partial payment PAY-81 (15 March): Client pays $1,200. Status moves issued → partially_paid; open balance = $2,200 − $1,200 = $1,000.

Entry 2: Partial payment PAY-81
AccountDebit (Dr)Credit (Cr)
Cash$1,200
Accounts Receivable$1,200
Total✓ Balanced$1,200$1,200

3. Credit note CN-12 (22 March): Billing adjustment of $200 plus $20 proportional tax (10%). Status stays partially_paid; open balance = $1,000 − $220 = $780.

Entry 3: Credit note CN-12
AccountDebit (Dr)Credit (Cr)
Sales Returns and Allowances$200
Sales Tax Payable$20
Accounts Receivable$220
Total✓ Balanced$220$220

4. Final payment with overpayment PAY-94 (5 April): Client wires $900 instead of $780. The extra $120 is booked as a customer credit liability, not negative AR. Status moves partially_paid → paid; open balance = $780 − $780 = $0.

Entry 4: Final payment + $120 overpayment
AccountDebit (Dr)Credit (Cr)
Cash$900
Accounts Receivable$780
Customer Credits Payable$120
Total✓ Balanced$900$900

Check net balances: Cash is $2,100 Dr, Sales Returns is $200 Dr ($2,300 total Dr); Service Revenue is $2,000 Cr, Sales Tax Payable is $180 Cr (10% of net $1,800), Customer Credits Payable is $120 Cr ($2,300 total Cr); Accounts Receivable is $2,200 − $1,200 − $220 − $780 = $0.

Alternative step 4 (write-off): If the remaining $780 had instead proven uncollectible after 120 days, Cedar Digital would transition INV-204 to written_off with:

Alternative: Write off remaining $780
AccountDebit (Dr)Credit (Cr)
Bad Debt Expense$780
Accounts Receivable$780
Total✓ Balanced$780$780

Partial payments, allocations and overpayments

One bank transfer often pays three invoices, and one large invoice may be paid in four instalments. Model payments and invoices as a many-to-many relationship through an append-only payment_allocations table:

CREATE TABLE payment_allocations (
  id              uuid PRIMARY KEY,
  payment_id      uuid NOT NULL REFERENCES payments(id),
  invoice_id      uuid NOT NULL REFERENCES invoices(id),
  amount_minor    bigint NOT NULL CHECK (amount_minor > 0),
  journal_entry_id uuid NOT NULL REFERENCES journal_entries(id),
  created_at      timestamptz NOT NULL DEFAULT now()
);

When allocating a payment, cap the amount applied to each invoice at its open_minor. Any remaining payment.amount_minor − SUM(allocated) stays in Customer Credits Payable (a liability) until refunded or allocated to a future invoice. Never allow an invoice’s open balance to drop below zero.

State machine and idempotency in TypeScript

Guard every transition in code, derive deterministic idempotency keys from domain IDs, and write the invoice update, allocation row and balanced journal entry inside one database transaction:

type InvoiceStatus = "draft" | "issued" | "partially_paid" | "paid" | "void" | "written_off";

interface Invoice {
  id: string;
  customerId: string;
  currency: string;
  status: InvoiceStatus;
  subtotalMinor: bigint;
  taxMinor: bigint;
  openMinor: bigint;
}

const ALLOWED: Record<InvoiceStatus, InvoiceStatus[]> = {
  draft: ["issued"],
  issued: ["partially_paid", "paid", "void", "written_off"],
  partially_paid: ["partially_paid", "paid", "written_off"],
  paid: [],
  void: [],
  written_off: [],
};

function assertTransition(from: InvoiceStatus, to: InvoiceStatus): void {
  if (!ALLOWED[from].includes(to)) {
    throw new Error(`Invalid invoice transition: ${from} -> ${to}`);
  }
}

function buildPaymentEntry(invoice: Invoice, paymentId: string, paidMinor: bigint) {
  if (paidMinor <= 0n) throw new Error("Payment must be positive");
  const appliedMinor = paidMinor > invoice.openMinor ? invoice.openMinor : paidMinor;
  const excessMinor = paidMinor - appliedMinor;
  const nextStatus: InvoiceStatus = appliedMinor === invoice.openMinor ? "paid" : "partially_paid";

  assertTransition(invoice.status, nextStatus);

  const postings = [
    { accountId: "cash", amountMinor: paidMinor, currency: invoice.currency },
    { accountId: "accounts_receivable", amountMinor: -appliedMinor, currency: invoice.currency },
  ];
  if (excessMinor > 0n) {
    postings.push({
      accountId: "customer_credits_payable",
      amountMinor: -excessMinor,
      currency: invoice.currency,
    });
  }

  return {
    nextStatus,
    appliedMinor,
    entry: {
      idempotencyKey: `invoice:${invoice.id}:payment:${paymentId}`,
      sourceType: "payment",
      sourceId: paymentId,
      postings,
    },
  };
}

Because idempotencyKey combines the invoice ID and payment ID, a retried webhook or double-clicked button hits the unique constraint on journal_entries and posts exactly once.

Real-world application

In production SaaS and B2B billing platforms, the invoice subledger powers customer statements, aging reports (30/60/90 days overdue) and dunning reminders, while the general ledger summarizes total Accounts Receivable on the balance sheet. At month-end, finance reconciles the sum of all open invoices in the billing tables against the Accounts Receivable control account in the general ledger — if both are written atomically from the same transitions, they match to the cent.

Recap

  • Keep invoice workflow states (draft, issued, partially_paid, paid, void, written_off) strictly aligned with immutable ledger entries.
  • Post balanced entries for issue (AR, revenue, tax), payments, credit notes, voids and write-offs.
  • Use a payment_allocations table for partial and multi-invoice payments, and route overpayments to a liability account.
  • Enforce transitions, row locking and idempotency keys inside a single transaction.

Try it yourself

Active recall

Quick check · Test yourself

Work out each answer in your head first, then reveal the explanation and mark whether you got it right.

  1. 1A SaaS company issues a $1,000 invoice plus 10% sales tax ($100), totalling $1,100. What balanced journal entry should be posted on issue?

    Show worked answer

    Debit Accounts Receivable $1,100, credit Revenue $1,000, and credit Sales Tax Payable $100. Sales tax is a liability collected for the tax authority, not revenue. Total debits ($1,100) equal total credits ($1,000 + $100).

  2. 2A customer owes $800 on an invoice and transfers $950 by mistake. How should the ledger record the extra $150?

    Show worked answer

    Debit Cash $950, credit Accounts Receivable $800 (reducing the invoice's open balance to $0 so it moves to paid), and credit Customer Credits Payable (a liability) $150. That $150 can later be refunded or applied to a future invoice.

  3. 3Why should a draft invoice post nothing to the ledger, and how does voiding an issued invoice differ?

    Show worked answer

    A draft has not created a legal claim or obligation, so it can be edited or deleted freely. Once issued, its receivable and revenue live in the immutable ledger, so voiding must post a reversing entry rather than deleting rows.

Key terms in this lesson

Lesson 7 of 16 · Accounting for Developers

Finished this lesson?

Mark it complete to track your progress through the course. Progress is saved in this browser only.

Previous lesson: Reversals and Audit Trails in Accounting Systems

Subject GuideAccounting Systems & Personal Finance

Mei-Ling Chen(陈美玲)

Turns accounting invariants into clean code—and everyday personal money clarity.

  • Double-Entry Ledger Engineering
  • SQL Schemas & Financial APIs
  • Multi-Currency & Billing Code

More lessons with Mei-Ling

Published:

Educational content only—not accounting, tax, legal or investment advice. See our editorial policy or report an error via our corrections policy.

Search