Skip to the lesson
CivOps AI Academy · M22Quotes, Orders and Invoicing: Order-to-Cash Up to the Ledger
0%

Chapter 1 · Sessions 1–2

What the old tool holds, and invoices nobody can edit

Session 1 maps how quotes and orders become invoices today, from the old tool's own reports and bill, with customer codes instead of names. Session 2 builds the module's ten tables with the rules that make an invoice trustworthy: whole cents, numbers that never skip, and an issued invoice the database refuses to change.

25 min4 steps10 tablesAbout 8 hours hands-on across six sessions

By the end of this chapter you can

  • Map open invoices, unapplied payments, sources, users and the bill from the old tool's own reports.
  • Say why an issued invoice is never edited, why money is whole cents and why numbering has no gaps.
  • Have Claude Code build the tables, their tests, stand-ins and seed, and try them on the development project yourself.

What the module is for

It turns accepted quotes and shipped or completed work into correct invoices: billing terms, tax by the rate in force, credit notes, payment application and reminders, with every document posted once to the accounting system through a signed posting contract. It replaces QuickBooks Online invoicing, Xero invoicing, FreshBooks, Zoho Invoice, Invoice Ninja, Stripe Invoicing, Chargebee and Bill.com AR. The general ledger, payables, tax engines and card processing stay in the systems built for them.

Order to cash, up to the ledgerThe module listens for four events (quote accepted, sales order shipped, service work order completed, milestone accepted) and publishes four of its own (invoice issued, payment applied, invoice overdue, posting failed). LISTENS FORPUBLISHESQuote acceptedcrm.quote.acceptedSales order shippedinv.sales_order.shippedService work order completedfsm.service_work_order.completedMilestone acceptedprj.milestone.acceptedInvoice issuedbill.invoice.issuedPayment appliedbill.payment.appliedInvoice overduebill.invoice.overduePosting failedbill.posting.failedInvoicingbill_ tablesdraft, approve, issueapply paymentspost onceEverything left is owned by other modules; everything right is published for other modules.
Order to cash, up to the ledger. The module listens for an accepted quote, a shipped order, completed work and an accepted milestone, and publishes invoice issued, payment applied, invoice overdue and posting failed.
Step 1

Session 1: Map the old tool from its reports and its bill

60 minutes

Why

The open balance on a stated date is the number Session 6 must match to the cent, and today's invoice accuracy and pitfalls are what the module must beat. Reading every figure from the old tool's own reports and its invoice, with customer codes instead of names, gives a true baseline and keeps private data out of the repository.

Do this

Terminal (Mac) or PowerShell (Windows)
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
On a new branch billing/inventory, write docs/invoicing-inventory.md for how we invoice today. Do not invent any number: every figure is a blank with the report or page it comes from, and "Unknown: ask <who>" where nobody knows. Use the old tool's customer codes, never names; never a card or bank number.

Sections:
1. Which system does what: where quotes and orders live, where invoices are made, which accounting system holds the ledger.
2. Open items on a stated date and time: open invoices (count, total, oldest due date) from the receivables ageing report; unapplied payments and credits (count, total).
3. Ten customers by code: payment terms (due_on_receipt, net_15, net_30, net_45, net_60, eom, deposit, or "other: ..."), currency, tax exempt with certificate expiry, credit limit.
4. Twenty invoices from last month by source: sales order, shipment, service work order, project milestone, time and materials, by hand. How many were later credited, reissued or edited after sending (today's invoice accuracy).
5. Tax today: tool setting, tax engine, rate table or by hand; where you ship to; rate changes in the last two years and what happened to invoices already sent.
6. Users by job (invoice, record payments, approve, look only); shared logins; more access than the job needs.
7. Bill: plan, price per period, renewal date, notice, export window after cancelling, from the vendor's account page. Payment processing fees listed separately.
8. Workarounds, and which of the three pitfalls happen today.
9. The first source to replace, its approver and the person who checks what reaches the ledger.
Open a pull request titled "Invoicing inventory" and show me the link.

Fill it from the old tool's reports and account page, with the owner or bookkeeper's permission. Keep any export in a private folder outside the repository.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/invoicing-inventory.md)
+## 2. Open items as of ____ (date and time)
+| What | Count | Total | Read from |
+| Open invoices | ____ | ____ | Reports > Aged receivables |
+| Unapplied payments and credits | ____ | ____ | Reports > Unapplied payments |
1
⏺ Write(docs/invoicing-inventory.md)
+## 4. Twenty invoices by source
+Later credited, reissued or edited after sending: ____ of 20 (invoice accuracy today)
2
⏺ Pull request #101 adds docs/invoicing-inventory.md: 9 sections, 46 blanks, customer codes only, no card or bank numbers.
Blanks with their source, and codes where names would be.
  1. The as-of date and time matter: Session 6 reconciles to a moment, not a day.
  2. The number of corrected invoices is your baseline for the invoice accuracy measure.

Check it worked

docs/invoicing-inventory.md is merged with the open items on a stated date and time, twenty invoices by source, the bill from the vendor's page, the pitfalls marked, and a named approver and checker for the first source.

If it goes wrong

An export you opened shows a card or bank account number

Leave it out of every document, tell the owner, and do not paste the file anywhere. The module never stores these: the payment provider does.

You cannot see the bill

Write who can. Do not estimate from the vendor's price page; your plan, seats and discounts make list prices wrong.

Money, numbers and the rule that never bends

All money is whole numbers of the currency's smallest unit (cents for the dollar), so totals add exactly; the code and its minor unit come from ISO 4217 [4]. Invoice numbers never skip: a draft carries a temporary number and the real one is drawn only at issue, in the same transaction. Once issued, an invoice's header and lines are frozen and a hash of its content is stored; a mistake is corrected by a credit note and, if needed, a reissued invoice.

Invoice statusDraft, approved, issued, partially paid and paid in a row, a dashed arrow from draft straight to issued below the approval limit, and void and disputed branching from issued. draftapprovedissuedpartially_paidpaidbelow the limit: no second approvalvoiddisputedA sent invoice is never edited: a mistake is credited and, if needed, reissued.void and disputed keep the record; nothing is ever deleted.
Invoice status. A draft is approved when a second person must see it, then issued. After issue the status moves only with payment, dispute or void, never by changing the figures.

The rules live in the database as constraints and triggers, so they hold for every writer [3]. The columns cover what the EN 16931 semantic model says an electronic invoice must carry, so an e-invoicing export later is a mapping, not a rebuild [1]. Issued invoices are kept for as long as your record-keeping rules say [2].

The ten bill_ tablesTen tables: billing account, invoice, invoice line, tax rate, payment, payment application, credit note, posting, dunning step and dunning event, with arrows for the main links and a note that they link to the core_ spine tables. bill_billing_accountwho is billed, on what termsbill_invoiceheader, never editedbill_invoice_lineline with its taxbill_tax_ratedated rate tablebill_paymentmoney receivedbill_payment_applicationpart paid to an invoicebill_credit_notethe only correctionbill_postingone document, posted oncebill_dunning_stepthe reminder schedulebill_dunning_eventa reminder sent or skippedLinks to the spine, the core_ tables:core_party, core_item, core_uom,core_reason_code, core_approvalEvery table also carries id, site_id, created and updated stamps, row_version, archived_at and ext.
The module's ten tables. Every table also carries the standard columns; amounts are whole cents.

Every column of the ten tables

Claude Code builds the migration from these tables. money is a bigint of whole cents; quantity is numeric(18,4); a rate is numeric(9,6). An arrow is a hard foreign key; a soft link is a plain uuid with no constraint, because the module that owns the row may not be installed. Every table also has id, site_id (where the specification says tenant_id; docs/spine-map.md records the change), created_at, created_by, updated_at, updated_by, row_version, archived_at and ext.

bill_billing_account

ColumnTypeRequiredAllowed values or note
party_iduuid → core_partyyes
crm_account_iduuid, soft link to crm_accountnoScopes what a salesperson may see
currencytextyesA three-letter ISO 4217 code
payment_termstextyesdue_on_receipt, net_15, net_30, net_45, net_60, eom, deposit
tax_exemptbooleanyes
exemption_certificate_reftextnoThe certificate reference
exemption_expires_ondatenoThe day the certificate lapses
credit_limitbigint (cents)no
statustextyesactive, on_hold, closed
ext: old_customer_codetext inside extnoThe old tool's customer code, set by the import; unique when present

bill_invoice

ColumnTypeRequiredAllowed values or note
numbertextyesUnique; DRAFT- and eight characters of the id while a draft
billing_account_iduuid → bill_billing_accountyes
statustextyesdraft, approved, issued, partially_paid, paid, void, disputed
issue_datedatenoSet at issue
due_datedatenoWorked out from the account's terms at issue
currencytextyesA three-letter ISO 4217 code
subtotalbigint (cents)yes
tax_totalbigint (cents)yes
totalbigint (cents)yesEquals subtotal plus tax_total
balance_duebigint (cents)yesNever negative and never above total; 0 when paid or void
source_typetextyessales_order, shipment, service_work_order, project_milestone, time_and_materials, manual
sales_order_iduuid, soft link to inv_sales_orderno
service_work_order_iduuid, soft link to fsm_service_work_orderno
project_iduuid, soft link to prj_projectno
quote_iduuid, soft link to crm_quoteno
approval_iduuid → core_approvalnoSet when a second person must approve
issued_hashtextnoSHA-256 of the issued content

bill_invoice_line

ColumnTypeRequiredAllowed values or note
invoice_iduuid → bill_invoiceyes
line_nointegeryes
item_iduuid → core_itemno
descriptiontextyes
quantitynumeric(18,4)yes
uom_iduuid → core_uomnoThe unit of measure
unit_pricebigint (cents)yes
discountbigint (cents)no
line_totalbigint (cents)yes
tax_codetextnoEXEMPT on an exempt line
tax_amountbigint (cents)yes

bill_tax_rate

ColumnTypeRequiredAllowed values or note
jurisdictiontextyesCountry and region, such as ZZ-T1
tax_codetextyes
ratenumeric(9,6)yesA fraction: 0.07 means 7%
valid_fromdateyes
valid_todatenoEmpty on the current row; two rows for one jurisdiction and tax_code may not overlap

bill_credit_note

ColumnTypeRequiredAllowed values or note
numbertextyesUnique
invoice_iduuid → bill_invoiceyes
reason_code_iduuid → core_reason_codeyes
amountbigint (cents)yesExcludes tax
tax_amountbigint (cents)yesThe credit is amount plus tax_amount
statustextyesdraft, approved, issued, applied
reissued_invoice_iduuid → bill_invoicenoThe corrected invoice, once reissued

bill_payment

ColumnTypeRequiredAllowed values or note
billing_account_iduuid → bill_billing_accountyes
received_ondateyes
amountbigint (cents)yes
currencytextyesMust match the account's currency
methodtextyescard, ach, wire, check, cash, other
referencetextnoA cheque number or similar; never a card or bank account number
provider_reftextnoThe payment provider's own reference
unapplied_amountbigint (cents)yesBetween 0 and amount

bill_payment_application

ColumnTypeRequiredAllowed values or note
payment_iduuid → bill_paymentyes
invoice_iduuid → bill_invoiceyes
amountbigint (cents)yesA mistake is reversed by a new row with a negative amount, never by an update
applied_ondateyes

bill_dunning_step

ColumnTypeRequiredAllowed values or note
days_overdueintegeryesUnique per site
channeltextyesemail, letter, call_task
template_keytextyes
stop_on_disputebooleanyes

bill_dunning_event

ColumnTypeRequiredAllowed values or note
invoice_iduuid → bill_invoiceyesOne event per invoice and step
dunning_step_iduuid → bill_dunning_stepyes
attimestamptzyes
outcometextyessent, skipped_dispute, skipped_paid, failed

bill_posting

ColumnTypeRequiredAllowed values or note
document_typetextyesinvoice, credit_note, payment
document_iduuidyesUnique together with document_type; a plain uuid, as the document may be in any of three tables
idempotency_keytextyesUnique
target_systemtextyesquickbooks, xero, netsuite, sage_intacct, other
statustextyesqueued, posted, failed, reversed
external_reftextnoThe accounting system's reference
attemptsintegeryesStarts at 0; one is added every time the service sends
last_errortextno
posted_attimestamptzno
Step 2

Session 2: Check the spine tables the module points at

15 minutes

Why

The module has no customer, item or approval list of its own: it points at the spine's. A missing spine table fails the migration, or tempts Claude Code to create a second customer list inside billing. Checking first, and adding only what is missing in its own migration, keeps one record per customer across sales, service and billing.

Do this

Paste into Claude Code
Read supabase/migrations/, docs/SCHEMA-PLAN.md and docs/spine-map.md if another module has written it. Do not write anything yet.

The billing module points at: core_party, core_address, core_item, core_uom, core_reason_code, core_approval, core_number_sequence, core_event_outbox, core_action_item, core_comment, core_status_history, core_audit_log; and the helpers core_current_actor(), core_touch_row(), core_audit_row().

For each, tell me: present (which migration), present under another name, or missing. Then, without asking again: reuse what exists under another name (the module keeps its column names; write the mapping as a billing section of the one shared docs/spine-map.md, creating it if no module has yet, and record there that our module tables carry site_id in place of the specification's tenant_id); put whatever is missing in ONE spine migration on a branch billing/spine, with row-level security on and pgTAP tests, never inside the module's migration. If anything was missing, open a pull request titled "Spine for billing", wait for the schema check and tell me the result in plain words.

You will see recreated screen

claude — acme-platform
⏺ Present from earlier modules: core_party, core_item, core_uom, core_reason_code, core_approval, core_number_sequence, core_event_outbox, core_comment. Missing: core_address, core_action_item, core_status_history.1
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m04s
⏺ Pull request #102 adds 3 spine tables with row-level security on and 12 tests.
Only what is missing is added.
  1. If you built M12 or M15 first, most of the spine is already there.

Check it worked

Pull request Spine for billing is green (or nothing was missing), and the billing section of docs/spine-map.md records the mapping.

If it goes wrong

Claude Code created bill_customer

Say: Remove bill_customer. The customer is a core_party; the billing account points at it with party_id.

CI fails: a foreign key type does not match

Say: Use the referenced table's id type for every foreign key, push, and wait for the check.

Step 3

Session 2: One prompt: the ten tables, the never-edit rule and their tests

30 minutes

Why

The rules that make an invoice trustworthy belong in the database: whole cents, totals that add up, a tax rate per date that cannot overlap another, one posting per document, and an issued invoice that refuses every change except its status and balance. Then no screen, import or AI-written route can break them, and the tests prove it on every change.

Do this

Paste into Claude Code
Read docs/spine-map.md, docs/naming-standard.md and the M22 specification's tables (or the lesson's column tables).

On a new branch billing/tables:
1. npx supabase migration new billing_tables. The ten tables with every column; required means not null; listed values are check constraints; money bigint cents; quantity numeric(18,4); rate numeric(9,6); currency a three-letter ISO 4217 code. Standard columns (site_id in place of tenant_id, by docs/spine-map.md), row-level security on with no policies, core_touch_row() and core_audit_row() on each. Soft links are plain uuid with a comment.
2. Rules: number unique on invoices and credit notes; total = subtotal + tax_total; 0 <= balance_due <= total; paid and void have balance_due 0; 0 <= unapplied_amount <= amount; days_overdue unique per site; one dunning event per invoice and step; bill_posting idempotency_key unique, and unique (document_type, document_id); attempts >= 0, default 0; tax rates for one jurisdiction and tax_code cannot overlap (exclusion constraint on the date range); unique on bill_billing_account (ext->>'old_customer_code') where present.
3. The never-edit trigger: once an invoice leaves draft or approved, refuse every change except status and balance_due (and the touch columns), refuse any change to its lines (except lines inserted in the same transaction as an imported invoice), refuse delete; allow only the status moves draft→approved|issued|void, approved→draft|issued|void, among issued, partially_paid, paid, disputed, and those→void. A credit note after issue may change only status and reissued_invoice_id.
4. Numbering: a draft's number is DRAFT- plus 8 characters of its id; core_number_sequence rows bill_invoice (INV-, padding 6) and bill_credit_note (CN-). A trigger writing core_status_history on every status change of invoices, credit notes and postings.
5. Write docs/bill-rules.md in plain words, including: a credit note's amount excludes tax.
6. pgTAP tests: an update of total, number, issue_date or due_date on an issued invoice is refused; a line cannot be added, changed or removed; delete refused; issued→draft refused; duplicate number refused; duplicate idempotency_key refused; a second posting for one document refused; overlapping rate refused; and a test that fails if any bill_ column is named like a card number, security code, bank account or routing number.
Do not connect to any Supabase project. Push, open a pull request titled "Billing tables", wait for the schema check to finish and report in plain words. If it fails, fix it and wait again.

You will see recreated screen

claude — acme-platform
⏺ Write(supabase/migrations/20261116091500_billing_tables.sql)
+create trigger bill_invoice_never_edit before update or delete on public.bill_invoice
+ for each row execute function public.bill_refuse_issued_change();
+alter table public.bill_posting add constraint bill_posting_one_per_document
+ unique (document_type, document_id);
1
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m58s
⏺ Pull request #103 is green: 10 tables, row-level security on, no policies; 31 tests, 12 of them try to change an issued invoice or post twice and are refused.2
The never-edit rule, kept by the database and tried by the tests.
  1. Two of the three pitfalls are closed here, in the database.
  2. Count the refusals: each is a way the old tool could be misused that this one cannot.

Check it worked

Pull request Billing tables is green and the summary names the refused edit of an issued invoice and the refused second posting.

If it goes wrong

Claude Code used numeric(12,2) or a float for money

Say: Money is bigint whole cents, everywhere, per docs/bill-rules.md. A float cannot hold 0.07 exactly; in JavaScript 19.99 * 100 gives 1998.9999999999998.

It reports success but the check on GitHub is red

Say: The schema check is red. Run gh pr checks, read the failed log, fix the cause and wait for green before you report. We trust the check on GitHub, never the summary.

A test passes even with the trigger removed

Then it can never fail. Say: Drop the never-edit trigger in a scratch run, show me which tests fail, then restore it. We had checks green for weeks while the thing they guarded was broken.

Step 4

Session 2: Stand-ins, the seed and the hand-counted fixture, and a try on the development project

25 minutes

Why

Session 4 is proven against a scenario you count by hand on fixed dates, because its tax depends on them, so that scenario is a test fixture; the seed holds the same made-up customers, orders, work and tax rates moved onto today, so the screens on the development project look the same. Stand-ins for the sales order and service tables let the tests run before those modules exist. Trying the migration and seed on the development project from your own terminal shows they work on real Supabase before the pipeline applies the migration to production.

Do this

Paste into Claude Code
On the branch billing/tables:
1. If M12 and M18 are not installed, test/standins/billing.sql creating small stand-ins with only the columns the specifications name: inv_sales_order, inv_sales_order_line, fsm_service_site, fsm_service_work_order, fsm_service_line, crm_quote, crm_account. Applied to test and development databases only.
2. Write supabase/seeds/invoicing.sql and list it under [db.seed] sql_paths in supabase/config.toml (never in supabase/seed.sql): marked SYNTHETIC, made up, safe to run twice, all prices in whole cents, and every date below moved by the same number of days so that 2026-10-11 falls on the day the seed runs:
- customers A, B, C with shipping addresses in country ZZ, region T1; billing accounts A (net_30), B (net_15, tax exempt, certificate TEST-CERT-1 expiring 2026-12-31), C (net_30); sales users 1 and 2 owning crm accounts X (billing A) and Y (billing C);
- tax rates for ZZ-T1, code STD: 0.05 from 2026-01-01 to 2026-06-30; 0.07 from 2026-07-01 (made-up practice rates);
- reason codes price_error, quantity_error, returned_goods, duplicate; dunning steps 7 days call_task, 14 days call_task, 30 days letter, each stop_on_dispute;
- SO-1 for A (10 at 12500 and 4 at 2500, shipped 2026-03-10); SO-2 for A (3 at 20000, shipped 2026-08-10); SO-3 for B (2 at 15000, shipped 2026-08-14); SWO-1 for C at site S1 (ZZ-T1): labour 3 hours at 9000, part 1 at 4550, travel 1 at 5000 not billable, part 1 at 2000 under warranty; each with a core_status_history row.
3. The hand-counted scenario keeps these dates exactly: write the same rows, on these 2026 dates, to tests/fixtures/invoicing-scenario.json. Session 4's tests and scenario script load it into a made-up site of their own and set the clock; no test counts on the seed's dates. Add supabase/tests/billing-seed.test.sql checking the seed's counts. Push to the same pull request, wait for the checks and report.

Then, in your own terminal (not inside Claude Code), try the branch on the development project; its password is in the password manager under Supabase: acme-platform-dev database password.

Terminal (Mac) or PowerShell (Windows)
git fetch && git switch billing/tables && npx supabase link --project-ref tsrqponmlkjihgfedcba
Terminal (Mac) or PowerShell (Windows)
npx supabase db push --include-seed

That loads the made-up rows the first time. After that, reload them with npm run seed:dev.

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new

Run select jurisdiction, rate, valid_from, valid_to from bill_tax_rate order by valid_from;: two rows, 0.05 and 0.07.

You will see recreated screen

Terminal
$ npx supabase link --project-ref tsrqponmlkjihgfedcba
Finished supabase link.
$ npx supabase db push --include-seed
Do you want to push these migrations to the remote database? • 20261116080000_spine_for_billing.sql • 20261116091500_billing_tables.sql [Y/n] y1
Finished supabase db push.
db push on the development project. Read the reference before answering y.
  1. Only the new files. If it lists anything else, answer n and ask why.

You will see recreated screen

supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new
SQL Editor · acme-platform-dev
1
jurisdictionratevalid_fromvalid_to
ZZ-T10.0500002026-02-062026-08-05
ZZ-T10.0700002026-08-06
The made-up rates in the development project, moved onto the day the seed ran (here 2026-11-16).
  1. ZZ-T1 is not a real place, so nobody mistakes a practice rate for a real one.

Check it worked

The pull request is green; the development project shows the two made-up rates; after owner two approves and you merge, the deploy workflow run on github.com/acme-ops/acme-platform/actions is green (stand-ins and seed never go to acme-platform-prod).

If it goes wrong

The link command shows abcdefghijklmnopqrst

Stop and answer n. Link again with tsrqponmlkjihgfedcba. Made-up data never enters production.

The stand-ins were added to supabase/migrations

Say: Move the stand-ins to test/standins/; they must never reach production, where the real modules' tables will be.

A later step expects a figure the fixture does not create

Reviews of five Academy modules found this fault. Say: List every figure the later billing steps expect, and show the line of tests/fixtures/invoicing-scenario.json that creates each. Fix the fixture, not the check.

Knowledge check

A customer reports a wrong quantity on an invoice issued last week. What does the module do?

Knowledge check

Why does a draft invoice carry a temporary number?

References

  1. European Commission: EN 16931, the European standard on electronic invoicing. https://ec.europa.eu/digital-building-blocks/sites/display/DIGITAL/Obtaining+a+copy+of+the+European+standard+on+eInvoicing
  2. IRS Publication 583: Starting a Business and Keeping Records. https://www.irs.gov/publications/p583
  3. PostgreSQL documentation: constraints (including exclusion constraints). https://www.postgresql.org/docs/current/ddl-constraints.html
  4. ISO 4217 currency codes. https://www.iso.org/iso-4217-currency-codes.html
  5. Supabase Docs: Database migrations. https://supabase.com/docs/guides/deployment/database-migrations

Chapter 2 · Session 3

Who may bill, approve, pay and post

Session 3 writes the billing roles into your role matrix, generates the access rules from it, proves that nobody approves a document they created and only the posting service touches a posting, and builds the screens behind the sign-in that denies by default.

25 min3 steps3 people roles + 2 service roles7 screens

By the end of this chapter you can

  • Write the billing roles, routes and rules into docs/matrix.json, as jobs not names.
  • Generate the access rules and prove each allowed and refused cell with a test.
  • Build the billing screens behind default-deny sign-in and pass the phone check.
RoleDoesNever
Billing clerkDrafts, issues and corrects invoices; records and applies payments; keeps accounts, dated rates and reminder steps; chases late payersApproves a document; updates a posting
SalesReads the invoices and balances of their own customers; comments on an invoiceSees another salesperson's customers or any payment
Invoice approverApproves invoices and credit notes above the thresholdApproves one they created; creates invoices
Posting serviceSends each document to the accounting system and records the answerIs used by a person; changes an invoice
Cut-over importerLoads the old tool's open items once, through the import workflow (Sessions 5 and 6), then is set to NOLOGINUpdates anything; signs in after cut-over
Step 5

Session 3: Write the roles, routes and rules into the matrix

25 minutes

Why

Row-level security, the route guard and their tests are generated from docs/matrix.json, so a right that is not there is refused later, in the middle of the build. Writing every operation Sessions 4 to 6 need now, and checking it with a script, prevents those refusals and keeps money rights as narrow as each job needs.

Do this

Terminal (Mac) or PowerShell (Windows)
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
Read docs/matrix.json and docs/bill-rules.md. On a new branch billing/matrix, add the billing module to docs/matrix.json. No delete anywhere.

Roles: billing_clerk, sales, invoice_approver; service roles posting_service and cutover_importer.
- billing_clerk: read/insert/update bill_billing_account and bill_dunning_step; bill_tax_rate insert, and update only valid_to; bill_invoice insert as draft, update while draft or approved, after issue only status and balance_due; lines only while draft; credit notes insert, update while draft or approved, after issue only status and reissued_invoice_id; bill_payment insert, update only unapplied_amount; bill_payment_application insert (a mistake is a new negative row); bill_dunning_event insert; read bill_posting; spine: core_party insert (customer only), core_comment, core_approval (pending step), core_number_sequence update next_value, core_event_outbox insert bill.* only, core_action_item; read other modules' quote, order and work order tables, never update them.
- sales: read billing accounts, invoices, lines, credit notes and core_party for own customers only (crm_account.owner_id = me); read crm_account; insert core_comment on an invoice; no bill_payment.
- invoice_approver: read accounts, invoices, lines, credit notes, postings, core_party, status history; approve (draft↔approved) invoices and credit notes; decide core_approval steps naming their role.
- posting_service: read the documents; insert bill_posting, update its status, external_ref, attempts, last_error, posted_at, and target_system while queued; update core_event_outbox published_at, attempts, last_error; insert core_action_item.
- cutover_importer (insert only; set to NOLOGIN at cut-over): insert core_party (customer), bill_billing_account, bill_invoice as issued or partially_paid with ext.imported true, its lines, bill_payment, bill_posting with keys starting opening:; read core_number_sequence; no update.
Restrictive rules: nobody approves a document they created; the clerk cannot set approved; only posting_service updates bill_posting; sales sees own customers only; the importer inserts only imported documents.
Screens: /billing/invoices, /billing/payments, /billing/setup (clerk, phone); /billing/approvals (approver); /billing/board (clerk, approver; read); /billing/accounts (clerk, sales, approver; payments section clerk only); /billing/postings (clerk; retry runs as posting_service).
Routes: /api/billing/invoices, /credit-notes, /payments, /remind, /quote-accepted, /accounts, /tax-rates, /dunning-steps (as billing_clerk); /api/billing/post (posting_service). The import runs as a workflow (cutover_importer), with no screen and no route.
Then docs/bill-operations.md (one row per operation, screen and route: session, acting role, table, right, status) and scripts/check-operations.mjs that fails if a row has no matrix cell, skipping rows marked "retired <date>". Do not generate policies yet. Open a pull request titled "Billing roles" and show me the link.

Read it with the approver you named in Session 1.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/bill-operations.md)
+| Session | Route | Acting role | Table | Right | Status |
+| 4 | /api/billing/post | posting_service | bill_posting | update status | |
+| 5 | import-invoicing.yml | cutover_importer | bill_invoice | insert (imported) | |
1
⏺ Bash(node scripts/check-operations.mjs)
⎿ OK: 64 operations, each has a matrix cell
⏺ Pull request #106 adds 5 roles, 7 screens, 9 routes and 5 restrictive rules. No delete anywhere.
Every operation listed and checked against the matrix before anything is built.
  1. A route acting for a role needs that role's cell too. The script finds a missing one now, not in Session 5.

Check it worked

The pull request adds the five roles, screens and routes; scripts/check-operations.mjs passes; no cell grants delete; the approver has read it.

If it goes wrong

Sales is given read on bill_payment "to answer customers"

Say no. Payments show how and when a customer paid; sales sees the balance on the invoice. Write the reason in docs/access-review.md.

Claude Code grants the posting service update on bill_invoice

Say: The posting service never changes a document; it only records postings. A role that can post and edit can hide its own mistake.

Step 6

Session 3: Generate the access rules, and prove the refusals

25 minutes

Why

Money rights only protect anyone once they are policies and route rules, and only stay protected if a test tries every refused cell on every change. The two rules that matter most, nobody approves their own document and only the posting service touches a posting, each get a test shown failing before it is trusted.

Do this

Paste into Claude Code
On the branch billing/matrix:
1. Run node scripts/gen-policies.mjs and regenerate lib/access/routes.ts with node scripts/gen-routes.mjs, as Session 9 does. Do not edit generated files.
2. supabase/tests/billing-access.test.sql generated from the matrix: one allowed and one refused test per cell. Plus: sales user 1 sees billing account A, its invoices and customer A's party, and not C (the reverse for sales user 2); the clerk cannot update a bill_posting row; the approver cannot insert an invoice and cannot approve one they created; no role can delete; the importer cannot update; every update test reads the row back.
3. Show each new test failing with its rule removed, then passing. Never loosen a test to make it pass.
Push, wait for every check on the pull request, and report the counts in plain words.

You will see recreated screen

claude — acme-platform
⏺ Bash(node scripts/gen-policies.mjs)
⎿ wrote supabase/migrations/20261118100000_policies_billing.sql (58 policies, 5 restrictive)
⏺ Shown red first: without 'nobody approves what they created', the self-approval test fails; restored, it passes. Same for 'only posting_service updates bill_posting'.1
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 3m22s clamps pass 59s
⏺ Pull request #106 is green: 58 policies; 118 access tests, 59 refusals. Sales user 1 sees customer A only.2
Generated rules, and the refusals shown red first.
  1. A test never seen failing may never fail.
  2. Sales seeing only its own customers is a test against the seed, not an assumption.

Check it worked

Pull request Billing roles is green with the refusal counts; owner two approves and you merge; the deploy workflow applies the policies to acme-platform-prod.

If it goes wrong

The approve button says Done but the status did not change

In Postgres an update only finds rows the role can read, and the new row must still pass the read rule. We hit this in three modules. Say: Check the approver's read rule covers the invoice before and after approval; make the test read it back.

A check named for a list fails, not your code

Some checks compare a generated list with the code. We hit this. Say: Open the failed check's log, tell me which file it compares, regenerate it with the command the log prints, and show me what changed.

Step 7

Session 3: The billing screens, behind default-deny sign-in

25 minutes

Why

Billing clerks record payments at a counter or on a phone, approvers work a queue, managers read a board. Building the screens on the Foundation surfaces, behind the route guard that refuses everything not in lib/access/routes.ts, means a new billing screen is invisible to everyone until the matrix opens it.

Do this

Paste into Claude Code
Before writing any page or route, read the guides in node_modules/next/dist/docs/ for this version of Next.js (request middleware lives in proxy.ts). On a new branch billing/screens, on the surfaces from Sessions 12 and 13, build read-only screens against the seed: /billing/invoices (status, number, account, due date, balance), /billing/payments (a form), /billing/setup, /billing/approvals (drafts waiting), /billing/board (open balance per account), /billing/accounts (statement; payments section for the clerk only), /billing/postings. Every button calls a route that answers "built in Session 4". Every screen and /api/billing/ route is in lib/access/routes.ts and refused by proxy.ts for everyone else. The server takes the user from the session, never from the page. No screen shows a number that is not stored.
Screen tests: each at 360 and 390 px (no sideways scroll, 44 px targets, 16 px fields, 15 px text); signed out each lands on sign-in or 401; sales sees only /billing/accounts. Push, open a pull request titled "Billing screens", wait for every check and the Vercel preview, and give me its address.

You will see recreated screen

acme-platform-git-billing-screens-acme-ops.vercel.app/billing/invoices
Invoices · Cleveland
1
NumberAccountDueBalance
DRAFT-3f9a1c2eA141,750
Issue2
The invoice list on a phone, with the made-up seed.
  1. A draft shows its temporary number. The real number appears only at issue.
  2. Buttons say "built in Session 4" until the routes exist; no button pretends to work.

Check it worked

Pull request Billing screens is green, the preview shows each screen at phone width, and sales sees only the accounts screen.

If it goes wrong

Claude Code wrote middleware.ts

This version of Next.js calls it proxy.ts. Say: Read node_modules/next/dist/docs/ for request middleware in this version and use proxy.ts as Session 9 did.

An /api/billing/ route ending in .pdf opens signed out

We hit a gate that skipped every dotted path. Say: Check every /api/ path whatever it ends with; add a signed-out test for /api/billing/statement.pdf.

The preview answers 401 before any sign-in page

That can be Vercel's preview protection, not your code. Sign in to Vercel in the same browser and open it again.

Knowledge check

Who may update a bill_posting row?

Knowledge check

Sales user 1 owns customer A. What can they see?

References

  1. Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
  2. PostgreSQL documentation: Row security policies (restrictive). https://www.postgresql.org/docs/current/ddl-rowsecurity.html
  3. Next.js Docs: proxy.ts (request middleware). https://nextjs.org/docs/app/api-reference/file-conventions/proxy
  4. Vercel Docs: Environment variables. https://vercel.com/docs/environment-variables

Chapter 3 · Session 4

From draft to posting, counted by hand

Session 4 builds order-to-cash end to end: drafts from orders and work, tax by the rate in force on the date, approval and gapless issue, credit notes, payments, reminders, and one signed posting per document. Then a scripted scenario is counted by hand, cent by cent.

30 min4 stepsAbout 2 hoursThe hand-counted scenario

By the end of this chapter you can

  • Have Claude Code build drafts, dated tax, issue and credit notes, and check the totals by hand.
  • Apply payments and run reminders that stop on dispute.
  • Post each document once with an idempotency key and a signing secret only a person handles.
Tax follows the dateA year drawn to scale with two dated rate rows: 6.00 percent until 30 June and 6.50 percent from 1 July. An invoice issued on 15 March uses 6.00 and one issued on 10 August uses 6.50. Example rates in bill_tax_rate (not a real jurisdiction)6.00% · valid_from 2026-01-016.50% · valid_from 2026-07-01JanFebMarAprMayJunJulAugSepOctNovDecissued 15 Maruses 6.00%issued 10 Auguses 6.50%The March invoice keeps 6.00% for ever. Looking up today's rate for it would rewrite history.
Tax follows the date. An invoice issued on 15 March keeps the March rate for ever; a rate change applies only to invoices dated on or after it.

Tax is computed in whole numbers: the line total times the rate in millionths, divided by a million, rounded half up per line (an exact half goes up: 812.5 cents becomes 813). The rate is the one row for the tax address's jurisdiction and tax code whose dates cover the issue date; none or two stops the draft. An exempt account with a certificate in date carries zero tax and the certificate reference.

Step 8

Session 4: Drafts from orders and work, with tax by date

30 minutes

Why

Most invoices come from something already priced: a shipped order or finished work. Drafting from them, billing only what shipped and was not billed before, and taking the tax rate in force on the issue date from a dated row, removes retyping and makes the third pitfall, recalculating old invoices, impossible.

Do this

Terminal (Mac) or PowerShell (Windows)
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
Read docs/bill-rules.md. On a new branch billing/drafts, as billing_clerk:
1. One clock function every date comes from, so tests can set "today".
2. Draft from a sales order: per line, qty_shipped minus what earlier non-void invoices billed (ext.source_line_id); skip lines with nothing left; account by customer_party_id; refuse a closed or on-hold account; keep quote_ref as quote_id; temporary number DRAFT- plus 8 characters of the id.
3. Draft from a service work order: tax address from the work order's service site; bill lines that are billable and not under warranty; refuse a line with no price, in words the clerk can read.
4. The consumer /api/billing/quote-accepted: if no billing account exists for the quote's account, a core_action_item for the clerk; never invent terms.
5. Tax step: jurisdiction from the tax address (order ship-to; work order site; for a manual invoice the address the clerk picks, kept in ext.tax_address_id); tax_code STD (EXEMPT on an exempt line with the certificate in ext; an expired certificate stops the draft); the one rate row covering the issue date; whole-number arithmetic, half up per line. Issuing on a different day from the draft's pricing date refuses and asks for a new draft.
6. /billing/setup and its routes: accounts with terms only from the list; a new rate is a new row, an old one only gets valid_to; dunning steps.
Tests load tests/fixtures/invoicing-scenario.json into a made-up site of their own, with the clock set: SO-1 on 2026-03-12 drafts subtotal 135000, tax 6750, total 141750; SO-2 on 2026-08-12 tax 4200, total 64200; SO-3 exempt, total 30000; SWO-1 on 2026-08-20 subtotal 31550, tax 2209, total 33759 (travel and warranty left out); an overlapping rate through /billing/setup is refused; a term not on the list is refused. Show each failing first. Push, open a pull request titled "Billing drafts", wait for every check and report the totals.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase test db)
⎿ billing-drafts.test.sql .. ok 16/16
⏺ SO-1 on 2026-03-12: 135000 + 6750 tax (0.05) = 141750. SO-2 on 2026-08-12: tax 4200 (0.07), total 64200. SO-3: exempt (TEST-CERT-1), 30000. SWO-1: 27000 labour + 4550 part = 31550, tax 2209 (2208.5 rounded half up), 33759.1
⏺ Bash(gh pr checks --watch)
⎿ ci pass · schema pass · clamps pass
The drafts' totals, checked against the hand count.
  1. Work one line yourself: 31550 × 0.07 = 2208.5, which rounds half up to 2209.

Check it worked

Pull request Billing drafts is green and its totals equal the four in the prompt.

If it goes wrong

The tax is one cent out on some lines

The rounding is not half up per line, or the arithmetic used a decimal. Say: Compute tax as line total times rate in millionths, divide by a million, round half up, in integers only; add a test with a line ending in exactly half a cent.

A draft was priced with today's rate for an old date

Say: Take the rate row whose dates cover the issue date, never the newest row; test an invoice dated 2026-03-12 after the July rate exists. This is the third pitfall.

A correction is a credit noteThree boxes in a row: the issued invoice, a credit note against it with a reason code, and a reissued corrected invoice linked back by reissued_invoice_id. Issued invoiceINV-000123 · total 23,850status issued, hash storedCredit noteCN-000001 · full creditamount 22,500 + tax 1,350Reissued invoiceINV-000124 · correctedreissued_invoice_id links itNothing is overwritten: three documents, three numbers, one reason code on the credit note.A partial credit follows the same path and credits only the wrong part, tax included.
Invoice, credit note, reissue. Three documents each keep their own number; the credit note's reason feeds the invoice accuracy measure.
Step 9

Session 4: Approval, gapless issue and credit notes

30 minutes

Why

Issue is the moment a document becomes a record others rely on: it takes the next number, freezes the content with a hash and starts the clock on payment. A manual invoice above the threshold needs a second person who sees exactly what will be issued; a correction is a credit note at the original date's tax, never an edit.

Do this

Paste into Claude Code
On a new branch billing/issue:
1. Manual invoices above the threshold (50000 cents for practice; the real one from the owner, in config/billing.json): submitting inserts a pending core_approval step with a SHA-256 hash of the content in its ext; the approver approves at /billing/approvals; refused when the approver is the creator; issue refuses if the content no longer matches the hash.
2. Issue, one transaction: lock the bill_invoice row of core_number_sequence, take next_value and add one; set the number; due_date from terms (net_N adds N days; due_on_receipt and deposit on the issue date; eom the month's last day); issued_hash over number, account, dates, currency, totals and lines in order; status issued; balance_due = total; bill.invoice.issued to the outbox.
3. Credit notes: reason code; amount + tax_amount no more than the balance due; tax at the ORIGINAL invoice's date; approval above the threshold; issue takes the next CN- number and in the same transaction lowers the invoice's balance_due, voids it on a full credit, and sets the credit note applied. A reissue is a new invoice linked by reissued_invoice_id.
Tests: two issues at once get consecutive numbers with no gap; a failed issue uses no number; a 60000 manual draft cannot issue unapproved; a changed approved draft cannot issue; the creator cannot approve; an SQL update of an issued total is refused; a credit note on an August invoice uses 0.07 even if dated later. Show each failing first. Push, open a pull request titled "Billing issue", wait for every check and report.

You will see recreated screen

claude — acme-platform
⏺ Two issues started together: INV-000001 and INV-000002, consecutive. An issue made to fail after taking a number rolled back: the next issue was INV-000003, no gap.1
⏺ Manual draft 60000: issue refused without approval; approved, then subtotal changed: issue refused, 'content differs from what was approved'.2
⏺ Bash(gh pr checks --watch)
⎿ ci pass · schema pass · clamps pass
Gapless numbers under load, and the approval tied to what was approved.
  1. The lock makes the second issue wait its turn, so the series never skips or repeats.
  2. The approver approves a fingerprint of the content; any change after that needs a new approval.

Check it worked

Pull request Billing issue is green; the summary shows consecutive numbers, no gap after a failed issue, and the changed-after-approval refusal.

If it goes wrong

Two invoices got the same number

The sequence row was read without a lock. We hit the same kind of fault as a lost save: two writers read the same starting value. Say: Lock the core_number_sequence row (select ... for update) inside the issue transaction; add the two-at-once test.

Claude Code made a credit note by editing the invoice's lines

Say: Revert. An issued invoice is never edited; a correction is a credit note and, if needed, a new invoice. This is the first pitfall.

Applying one paymentA bar to scale for a payment of 30,000 cents, split into 23,850 applied to one invoice, 4,000 applied to a second and 2,150 left unapplied. One payment received: 30,000 cents (bill_payment.amount)to INV-000123 · 23,850INV-0001254,000unapplied2,150bill_payment_application rows: 23,850 + 4,000 = 27,850bill_payment.unapplied_amount: 30,000 - 27,850 = 2,150, held as unapplied cashBalance due: INV-000123 23,850 to 0, INV-000125 4,000 to 0. Always: amount = applied + unapplied.
One payment, three outcomes. Most settles one invoice, some a second, the rest stays unapplied until someone decides.
The reminder ladderDays overdue from 0 to 60 drawn to scale with reminders at day 3, 14, 30 and 45. When the invoice stays unpaid all four are sent; when it is disputed on day 10 the later ones are skipped_dispute; when it is paid on day 20 the invoice leaves the ladder and nothing more is recorded (skipped_paid is recorded only for a reminder queued before the payment arrived). Example schedule: bill_dunning_step rows you chooseday 0day 10day 20day 30day 40day 50day 60Stays unpaidsent · emailsent · emailsent · call tasksent · letterDisputed on day 10sent · emailskipped_disputeskipped_disputeskipped_disputePaid on day 20sent · emailsent · emailnone: paidnone: paid
The same reminders, three histories. Days overdue to scale; a disputed invoice records skipped_dispute instead of a reminder.
Step 10

Session 4: Payments, statements and reminders that stop on dispute

25 minutes

Why

Cash rarely arrives one payment per invoice. Applying a payment across invoices, holding the rest as unapplied, refusing card numbers in a reference, and chasing late payers by a schedule that stops on dispute turns the clerk's memory into a record, and keeps card details out of the module entirely.

Do this

Paste into Claude Code
On a new branch billing/payments, as billing_clerk:
1. /billing/payments: account, received date, amount, method, reference; currency must match the account; refuse a reference holding 13 or more digits once spaces and dashes are removed (test 4111 1111 1111 1111 and 4111-1111-1111-1111 refused, cheque 004512 accepted); unapplied_amount starts at amount.
2. Apply: one bill_payment_application per invoice, never above its balance or the payment's unapplied amount; lower balance_due; partially_paid or paid; bill.payment.applied to the outbox; the rest stays unapplied.
3. /api/billing/remind (date from the clock): for each open invoice past due, one bill.invoice.overdue the first time; per reached step with no event yet: not disputed → a core_action_item and a dunning event sent; disputed → skipped_dispute, no task. The module sends no email: tasks tell the clerk whom to call or write to.
4. A statement on /billing/accounts: open invoices by age bucket; unapplied payments for the clerk only; printable from the browser.
Tests for each rule, shown failing first. Push, open a pull request titled "Billing payments", wait for every check and report.

You will see recreated screen

acme-platform-git-billing-payments-acme-ops.vercel.app/billing/payments
AccountA ▾
Amount100,000
Reference4111 1111 1111 1111
Record payment
Recording a payment on the preview: the reference refuses anything that looks like a card number.
  1. Refused before it is stored, with a reason the clerk can act on.

Check it worked

Pull request Billing payments is green; on the preview a spaced card number is refused and a cheque number is accepted.

If it goes wrong

A Send reminder button reports the email was sent

The module sends no email; a button claiming it did is a stand-in pretending. We hit this: "Send all" marked every recipient sent and no email left the building. Say: Reminders create a task for the clerk; remove any send action.

A payment's applications plus its unapplied amount do not equal its amount

Say: Add a test that, for every payment, amount equals the sum of its applications plus unapplied_amount, and fix the route it finds.

Posting once

The posting contractSix steps: a document is issued, a bill_posting row is queued with an idempotency key, the posting service sends it, the accounting system makes one ledger entry, the acknowledgement returns an external reference, and the status becomes posted. Below, the statuses: queued goes to posted when acknowledged, or to failed after the last attempt, from which a retry returns it to queued; posted can later go to reversed. Document issuedinvoice, credit note or paymentPosting row queuedbill_posting + idempotency_keyPosting service sendsthe document and its keyAccounting systemone ledger entry per keyAcknowledgementexternal_ref comes backStatus postedattempts and posted_at keptbill_posting.status as the answer arrivesqueuedrow made before sendingpostedledger entry confirmedreversedundone by a reversalfailedafter the last attemptacknowledgedreversalretryNo acknowledgement: attempts + 1 and last_error kept, then a retry with backoff.After the last attempt: status failed and bill.posting.failed published.Every retry sends the same idempotency key.
The posting contract. The row exists before anything is sent, so a crash cannot lose a document; it is queued until the answer arrives, then posted, or failed after the last attempt.
A retry does not post twiceA sequence: the posting service sends a document with key K, the accounting system creates ledger entry E1, the reply is lost, the service retries with the same key K, and the accounting system returns E1 without creating a second entry. Posting serviceAccounting systemattempt 1 · key Kcreates E1Ledger1 entry (E1)reply lost: timeout, attempt recordedattempt 2 · the same key Kkey K already posted: returns E1Two attempts, one entry. A new key on each retry would have made two.
Two attempts, one entry. The reply to attempt 1 is lost; attempt 2 carries the same key, so the accounting system returns the entry it already made.
Step 11

Session 4: One signed posting per document, and the scenario counted by hand

35 minutes

Why

A retry after a lost reply is normal; posting twice is the second pitfall, and it overstates receivables until someone finds it. A key built from the document, one row per document, and a signing secret only a person handles make a retry harmless; the hand-counted scenario then proves the whole workflow, cent by cent.

Do this

Paste into Claude Code
On a new branch billing/posting:
1. The posting service (/api/billing/post, posting_service only): for each issued invoice, issued credit note and first application of a payment, one bill_posting with idempotency_key from the document (invoice:<id>), insert on conflict do nothing; reuse any existing row for the same document (including opening: rows); if already posted return its external_ref and send nothing; attempts + 1 on every send; record posted with external_ref and posted_at; otherwise last_error and retry with backoff; after the last attempt failed, bill.posting.failed and a core_action_item. Set target_system to the target in force when sending a queued row.
2. The adapter signs each request with the secret in the environment variable POSTING_SIGNING_SECRET and reads the target from POSTING_TARGET. Target "other" appends to a journal file and says plainly in every result that it is a journal, not the ledger. A start-up check names a missing or malformed variable without printing it.
3. Add POSTING_SIGNING_SECRET and POSTING_TARGET to docs/KEYS.md by name.
4. scripts/scenario-flow.mjs: loads tests/fixtures/invoicing-scenario.json into a made-up site of its own on the test database and runs the scenario from docs/bill-rules.md with the clock set before each step (the five invoices, three payments, two credit notes, the reissue, reminders on 2026-09-30 and 2026-10-11, INV-000002 disputed in between).
Tests: the adapter records then fails to answer, retry: one journal entry; a second forced run of the service adds nothing; the scenario ends with open balances A 42800 and C 24129 (66929), 8250 unapplied for A, ten postings each once, five dunning events (four sent, one skipped_dispute), two overdue events, and INV-000001 still showing 6750 tax. Show the retry test failing with a time-based key first. Push, open a pull request titled "Billing posting", wait for every check and report the numbers.

Then a person, not Claude Code, sets the two variables for the Preview environment in Vercel. Generate the secret in the password manager and save it there as Billing: posting signing secret (preview); set POSTING_TARGET to other.

Open

https://vercel.com/acme-ops/acme-platform/settings/environment-variables

Add POSTING_SIGNING_SECRET (value from the password manager, Preview only) and POSTING_TARGET = other (Preview and Production). Paste the value only, no NAME=.

Key or secretWhat it unlocksWhere it livesWho holds itNever
POSTING_SIGNING_SECRETSigns every posting so the accounting side can check it came from you, unchangedVercel environment variables; the password managerpat@acme.com, sam@acme.comNever in a file, a chat or Claude Code; never the same value for preview and production
POSTING_TARGETWhich accounting system postings go to (other = the journal file)Vercel environment variablespat@acme.com, sam@acme.comNever switched to the live ledger before Session 6's reconciliation is 0

You will see recreated screen

claude — acme-platform
⏺ Bash(node scripts/scenario-flow.mjs && echo exit=$?)
⎿ INV-000001..INV-000005, CN-000001..CN-000002, 3 payments open: A 42800, C 24129, total 66929; unapplied A 8250 postings: 10, each once (second run: +0) dunning events: 4 sent, 1 skipped_dispute; overdue events: 2 exit=0
1
⏺ Shown red first: with a time-based key, the lost-reply retry wrote two journal entries; with invoice:<id>, one. INV-000001 still shows 6750 tax; recalculated at 0.07 it would be 9450.2
⏺ Write(docs/KEYS.md)
+| POSTING_SIGNING_SECRET | signs postings | Vercel env; password manager | owners | never in a file |
The scenario, counted by the script and compared with your hand count.
  1. Every figure here is one you can reach with a calculator from the fixture. Compare before you merge.
  2. The test that matters most: two attempts, one entry.

Check it worked

Pull request Billing posting is green; the scenario's numbers equal your hand count; the retry test was shown failing with a time-based key; both variables are set in Vercel by you and listed by name in docs/KEYS.md.

Fastest path

Do the hand count on paper while Claude Code writes the code: by the time the check is green you have the numbers to compare.

If it goes wrong

The start-up check says POSTING_SIGNING_SECRET is malformed or missing

The value is empty or holds its own name. We hit both: a key whose value was its name pasted in, and a secret never created that resolved to empty. Paste the value again in Vercel, value only.

The journal shows two entries for one invoice

The key is built from the attempt, not the document. Say: Build the key from document type and id only; add the lost-reply test.

Claude Code reports the scenario passed but did not show the exit code

Say: Run scripts/scenario-flow.mjs without piping it into anything and show me its exit code. We had a red suite read as green because the output was piped through tail.

Knowledge check

A posting times out after the accounting system recorded it. What makes the retry safe?

Knowledge check

An invoice issued in March at 0.05 is opened in August, after a rate change to 0.07. What tax does it show?

References

  1. OASIS: Universal Business Language (UBL) 2.1 (Invoice and CreditNote). https://docs.oasis-open.org/ubl/UBL-2.1.html
  2. ISO 20022: financial messaging standard (camt.053, camt.054). https://www.iso20022.org/
  3. PostgreSQL documentation: explicit locking (SELECT FOR UPDATE). https://www.postgresql.org/docs/current/explicit-locking.html
  4. Peppol BIS Billing 3.0 (OpenPeppol). https://docs.peppol.eu/poacc/billing/3.0/

Chapter 4 · Sessions 5–6

Move the open items in, and switch the old tool off

Session 5 builds the import workflow and rehearses the move on the development project with an approved copy, reconciling to the cent, and removes the rehearsal the same day. Session 6 imports into production through the workflow on the cut-over day, reconciles to zero against the accounting system, switches the posting target to the real ledger, closes the importer, runs a week with the old tool as the shadow, and cancels it.

25 min4 steps0 cents differenceEnds with the module gate

By the end of this chapter you can

  • Load open invoices and unapplied payments as issued documents with one opening posting each, safe to run twice, only from files owner two approved.
  • Reconcile every account to the accounting system's receivables at 0 cents.
  • Switch the posting target yourself, set the importer to NOLOGIN, compare a week with the old tool and record the saving.
Reconciliation at cut-overTwo boxes, the platform's open balance per account and the accounting system's receivables, both point to a third box: the difference must be zero cents before the cut-over continues. Platform open balancesum of balance_due per accountat the cut-over momentAccounting receivablessame accounts, same momentfrom the accounting systemDifference: 0 centscontinue only at zeroAny other number is stopped and explained account by account, never rounded away.
Reconcile before you continue. The platform's open balance per account must equal the accounting system's receivables at the same moment. The only acceptable difference is zero cents.
Step 12

Session 5: The import workflow, rehearsed on the development project with an approved copy

50 minutes

Why

The open balance must move across without losing or doubling a cent. An importer that only inserts, keys every document so a second run adds nothing, loads old tax as exported instead of recalculating it, runs only from main on files owner two approved, and is rehearsed on the development project with a copy IT has approved finds every fault before production sees a row.

Do this

Terminal (Mac) or PowerShell (Windows)
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
On a new branch billing/import, acting as cutover_importer only:
1. scripts/import-map.mjs: reads the exports and writes a mapping report only: old customer to core_party (customer); old term to the list, listing any it cannot match and never choosing; currency; exemption; old_customer_code in the account's ext. Drops any card or bank column without logging its value.
2. scripts/import-invoicing.mjs, signed in as the cutover_importer account with the password from the environment variable BILLING_IMPORTER_PASSWORD (never printed), insert only: a dry run by default (counts per file, every skipped row and why, no names). A real run, one transaction per document: generate the uuid; insert bill_posting with key opening:<old id>, on conflict do nothing returning id; if nothing returned, it was loaded before: stop and count it; else look up the account by old_customer_code (insert only if missing), then insert the invoice (old number, dates, totals and tax AS EXPORTED, status issued or partially_paid, ext.imported true, issued_hash) with its lines (or one line "Opening balance, old invoice <number>"), or the unapplied payment. Posting status per case A (posted, external_ref) or case B (queued, target other), from config/billing.json. If the export has no tax split: all in subtotal, tax 0, ext.tax_split_unknown true. Loaded plus skipped must equal each file's rows, or the run fails.
3. .github/workflows/import-invoicing.yml: started by hand only (workflow_dispatch) from main, inputs target (dev or production) and dry_run; downloads the exports from the private Storage bucket imports of the target; refuses any file whose sha256 and expected row count are not recorded in docs/imports/invoicing-approved.md on main; fails on any count mismatch; prints the counts as the job summary.
4. supabase/queries/billing-reconcile.sql (read-only), which I run in the target project's SQL editor: per account by old_customer_code, open balance and unapplied, then the business total. scripts/reconcile.mjs reads the codes and cents I put in docs/cutover.md beside the named report's figures and prints the difference in cents per account and for the business, failing unless every one is 0.
5. Tests with MADE-UP rows only: a file whose sha256 or row count is not approved is refused; a second run adds no row to any table; an imported invoice cannot be edited; an imported payment applied later adds no second posting; reconcile shows 0 on the made-up set.
Push, open a pull request titled "Billing import", wait for every check and report.

When it is merged, ask IT in writing to approve a copy of the exports for one rehearsal on acme-platform-dev, removed the same day. Contact names, emails and phone numbers in an export are personal data: redact them first. As a person, create the cutover_importer account on the development project with a password from the password manager, type it into GitHub as BILLING_IMPORTER_PASSWORD_DEV, and list the name in docs/KEYS.md.

Open

https://github.com/acme-ops/acme-platform/settings/secrets/actions

GitHub Actions secrets: BILLING_IMPORTER_PASSWORD_DEV, the value only.

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/storage/buckets

Development project Storage: upload the approved copy to the private bucket imports.

Terminal (Mac), in the export folder
shasum -a 256 *.csv
Paste into Claude Code, after pasting the values
On a new branch billing/import-approval, write docs/imports/invoicing-approved.md: each export file's name, sha256 and row count (I paste them below), the date and time taken, and IT's approval for one rehearsal on acme-platform-dev (date and role). Open a pull request titled "Billing: approve import files".

<paste the shasum lines and row counts>

Owner two approves and you merge. Run the workflow with target dev: dry run, fix the mapping (never the data) through a pull request, run for real, then once more (it must add nothing). Run the reconcile query in the development project's SQL editor, write account codes and cents only in docs/cutover.md, run scripts/reconcile.mjs, and check three invoices by eye against the old tool. The same day, remove the rehearsal rows (Claude Code gives you the statements by ext.imported; you run them in the development project's SQL editor) and the files in the bucket, and record the date in docs/cutover.md.

Open

https://github.com/acme-ops/acme-platform/actions/workflows/import-invoicing.yml

Run workflow: target dev, dry_run true, then false.

You will see recreated screen

github.com/acme-ops/acme-platform/actions/workflows/import-invoicing.yml
import-invoicing · target dev · dry_run false
FileRowsLoadedSkipped
customers.csv2142140
open_invoices.csv3883880
unapplied_payments.csv17170
The rehearsal's run on the development project: only approved files, and counts that add up.
  1. Only the files owner two approved, with the row counts recorded, can be imported.

You will see recreated screen

Terminal
$ node scripts/reconcile.mjs
C-0012 open 412,300 unapplied 0 report 412,300 difference 0
C-0031 open 88,950 unapplied 12,000 report 76,950 difference 0
Business: open 1,204,775 · unapplied 31,400 · report 1,173,375 · difference 01
Reconcile on the rehearsal: every account at zero.
  1. Codes and cents only. A difference that is not 0 is a cause to find (a void still in the report, a credit memo, another currency, a different as-of time), never a number to adjust.

Check it worked

The import's pull request is green with made-up rows only; on the rehearsal a second run added nothing and reconcile showed 0 for every account; three invoices match the old tool by eye; the rehearsal rows were removed the same day and the date is in docs/cutover.md.

If it goes wrong

IT will not approve a copy for the development project

Then rehearse with made-up rows only, and make Session 6's production import the rehearsal: the workflow's dry run, the counts read with IT watching, the real run, and continue only at 0.

Reconcile is out by a few cents on one account

Usually a credit memo, an invoice in another currency, or a different as-of time. Fix the cause and run it again. Never book the difference to an adjustment.

The importer recalculated tax on old invoices

Say: Load tax exactly as exported; an old invoice keeps the tax it had. This is the third pitfall.

Step 13

Session 6: Cut over: import production through the workflow, reconcile to zero, switch the target yourself

45 minutes

Why

On the cut-over day the open balance moves once, into production, through the import workflow a person starts from main, with files owner two approved. Continuing only at 0 cents, and switching the posting target to the real ledger yourself, on Vercel's site, keeps the one irreversible step, writing to the ledger, in a person's hands.

Do this

Take fresh exports and the accounting system's receivables ageing at the cut-over time. As a person: create the cutover_importer account on production, type its password into GitHub as BILLING_IMPORTER_PASSWORD_PROD, and record each file's sha256 and row count in docs/imports/invoicing-approved.md through a pull request owner two approves (target production, date and time).

Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/storage/buckets

Production Storage: upload the exports to the private bucket imports.

Open

https://github.com/acme-ops/acme-platform/actions/workflows/import-invoicing.yml

Run workflow from main: target production, dry run; read the counts against the old tool's reports; then for real, once.

Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/sql/new

Run the reconcile query on production, write codes and cents in docs/cutover.md beside the receivables ageing, and run scripts/reconcile.mjs.

Continue only at 0 for every account. Then create the accounting connection your system's developer pages describe (any paid plan it needs is on its own pricing page), and set the production values yourself:

Open

https://vercel.com/acme-ops/acme-platform/settings/environment-variables

Production: POSTING_TARGET = your accounting system; POSTING_SIGNING_SECRET = a new value from the password manager (not the preview one); the accounting connection's credentials as its documentation names them. Then redeploy from the Deployments tab.

In case B let the posting service send the queued opening postings once; in both cases read the accounting system's receivables ageing for the same moment and confirm each account equals reconcile's total. Load your real tax rates from your accountant's written statement through /billing/setup, issue the first real invoice, and watch its posting come back posted.

You will see recreated screen

https://acme-platform.vercel.app/billing/postings
1
DocumentKeyTargetStatusAttempts
INV-100001invoice:7c1e…your ledgerposted1
Opening C-0012opening:88412your ledgerposted1
The first real posting, acknowledged by the ledger.
  1. Attempts 1: posted first time. The new series (INV-1…) cannot clash with the old tool's numbers.
  2. The acceptance test from the specification, met on the day.

Check it worked

Production holds the open items with one opening posting each, loaded by import-invoicing.yml from approved files; reconcile and the ledger's receivables agree at 0 for every account; the first real invoice is posted with attempts 1.

If it goes wrong

Reconcile is not 0 on the day

Do not switch the target. Keep invoicing from the old tool, leave POSTING_TARGET as other, find the cause account by account, and try again. That is the rollback plan.

The accounting API answers 403

Before changing any credential, find who refused it: the service, a company proxy or a rate limit. We hit a rate limit that came back as 403 and was read as a wrong key; it cleared in minutes.

Someone suggests running the import from a laptop against production

No. Production changes only through the workflow, started by a person from main, with the importer's password in GitHub's secrets. We hit a laptop deploy that sent local settings to production and broke three live pages.

Step 14

Session 6: Close the importer the same day

25 minutes

Why

The importer can insert issued documents around the normal rules, so it must not outlive the cut-over. Setting it to NOLOGIN and removing its rights through a reviewed pull request, with a test that proves it is refused, closes the one door that went around the rules on the day it was used.

Do this

Paste into Claude Code
Cut-over is done. On a new branch billing/close-importer:
1. Remove cutover_importer from docs/matrix.json; mark the importer's rows in docs/bill-operations.md "retired <today's date>"; regenerate with scripts/gen-policies.mjs, and lib/access/routes.ts with scripts/gen-routes.mjs; add a migration that sets the cutover_importer role to NOLOGIN, applied by the deploy workflow; disable import-invoicing.yml; add a test that the importer can neither sign in nor insert; run scripts/check-operations.mjs.
2. In docs/cutover.md, record the three guarantees with their evidence (the refused update test, the retry test, the reconcile output at 0), the cut-over date, the last old invoice number and the new prefix, and the rollback plan.
3. Mark BILLING_IMPORTER_PASSWORD_DEV and BILLING_IMPORTER_PASSWORD_PROD retired in docs/KEYS.md and tell me which GitHub secrets to delete.
Push, open a pull request titled "Billing cut-over", wait for every check and report.

Owner two approves and you merge the same day; the deploy workflow applies the NOLOGIN migration. Then delete the importer's two secrets on GitHub yourself.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/bill-operations.md)
-| 5 | import-invoicing.yml | cutover_importer | bill_invoice | insert (imported) | |
+| 5 | import-invoicing.yml | cutover_importer | bill_invoice | insert (imported) | retired 2026-11-30 |
1
⏺ Bash(gh pr checks --watch)
⎿ ci pass · schema pass · clamps pass
⏺ Pull request #118 is green. The importer is NOLOGIN and its insert is refused. docs/cutover.md records: issued-invoice update refused (test), retry leaves one entry (test), reconcile 0 at 2026-11-30 17:00. Delete the GitHub secrets BILLING_IMPORTER_PASSWORD_DEV and BILLING_IMPORTER_PASSWORD_PROD.2
The importer closed and the guarantees on record.
  1. Retired, not deleted: the history of who could do what stays readable.
  2. Each guarantee from the specification with its evidence.

Check it worked

Pull request Billing cut-over is merged on the cut-over day; the importer is NOLOGIN and refused; its secrets are deleted on GitHub.

If it goes wrong

scripts/check-operations.mjs fails after removing the importer

A row was not marked retired. Say: Mark each importer row "retired" with the date; never delete rows from the operations list.

Someone wants to keep the importer for "one more load"

A later load is a new pull request that gives the role back its login for a day, with the test and the migration that close it again. An account that inserts issued documents around the rules does not stay open.

Step 15

Session 6: A week side by side, then cancel with the saving written

30 minutes, then a week

Why

A week in which every document is also entered in the old tool shows every difference in rounding, tax dates and terms while the old tool can still answer for it. The old tool is the shadow: its ledger connection and its emails are off, so no customer is invoiced twice and the ledger never receives a document twice. Cancelling only after its export is stored for the years the records must be kept finishes the module without losing anything.

Do this

On the cut-over day, switch off the old tool's connection to your accounting system and its automatic invoice emails, so it can no longer post or send.

Paste into Claude Code
On a new branch billing/side-by-side, write docs/cutover.md sections for the week: per invoice, platform and old-tool columns for lines, subtotal, tax, total, due date and balance, with a line per difference and its cause; and the four measures with their definitions: DSO (receivables ÷ credit sales × days), invoice accuracy (issued without a later credit note ÷ issued), time to invoice (median hours from shipped or completed to issued, from core_status_history; "not measured" where there is no start), posting success (posted with attempts 1 ÷ issued, opening postings left out). Add the three guarantees with how to show each. Update docs/invoicing-inventory.md: each source replaced, retired or still in the old tool, with the date. Open a pull request titled "Billing side by side".

Each day of the week, enter the same orders, work, payments and credits in the old tool as were made on the platform, and write the differences. At the end, read the four measures from /billing/board next to the old tool's. Then export everything from the old tool and store it for as long as your accountant says (IRS Publication 583 is the US starting point). Read the cancellation terms on the vendor's account page, cancel or write the end date, and write the saving: the old tool's cost from its invoice, minus anything the accounting plan or the module adds. Payment processing fees continue with the provider and are not part of the saving.

You will see recreated screen

https://acme-platform.vercel.app/billing/board
1
MeasureOld tool (shadow)Platform
Invoice accuracy17 of 2020 of 20
Posting successnot measured100%
Time to invoicenot measured3.5 h
The board on production at the end of the week.
  1. Illustrations: yours come from your own reports. Write "not measured" where the old tool cannot say; never guess.
  2. Only the platform posts to the ledger and sends to customers.

Check it worked

docs/cutover.md holds a line for every invoice of the week with each difference explained, and the four measures beside the old tool's; the old tool's export is stored; it is cancelled (or its end date written) with the saving from its invoice.

If it goes wrong

An invoice differs by one cent

A rounding rule: per line or on the total, and which way a half goes. Write which rule each tool uses; if your accountant says the old rule is right, change docs/bill-rules.md and the test, through a pull request.

The old tool sent an invoice to a customer during the week

Its automatic emails were still on. Tell the customer which document counts (the platform's), void the old tool's copy there, and switch its emails off.

Before you go on · The module is done whenTick each one

Knowledge check

On the cut-over day reconcile shows a 37-cent difference on one account. What do you do?

Knowledge check

Who switches POSTING_TARGET to the live accounting system, and where?

References

  1. IRS Publication 583: Starting a Business and Keeping Records. https://www.irs.gov/publications/p583
  2. Vercel Docs: Environment variables. https://vercel.com/docs/environment-variables
  3. European Commission: EN 16931, the European standard on electronic invoicing. https://ec.europa.eu/digital-building-blocks/sites/display/DIGITAL/Obtaining+a+copy+of+the+European+standard+on+eInvoicing

Chapter 5 · 12 questions · 80% passes

Final assessment

Twelve questions across the element. Score 80% (10 of 12) to pass. Your LMS records your score and each answer; you can review the chapters and try again.

15 min12 questions≈ 15 minutesRetake allowed

Choose one answer for each question, then submit. You will see the right answer and why for every question.

1. What is the only way to correct an issued invoice?
2. A posting times out and the service retries. What stops the accounting system recording it twice?
3. A tax rate changes on 1 July. Which rate does an invoice issued on 15 March use when it is reopened in August?
4. A payment of 30,000 cents is applied 23,850 to one invoice and 4,000 to another. What is its unapplied_amount?
5. Which of these stays outside the module and is integrated instead?
6. Why does a draft invoice carry a temporary number?
7. Where are card and bank account details held?
8. A reminder falls due on an invoice marked disputed, and the step has stop_on_dispute true. What is recorded in bill_dunning_event?
9. Which KPI is invoices issued without a later credit note divided by invoices issued?
10. At cut-over the platform's open balance differs from the accounting system's receivables. What is the correct action?
11. Which standard defines the semantic model of an electronic invoice?
12. Why is money held as whole numbers of cents?