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.
Session 1: Map the old tool from its reports and its bill
60 minutesWhy
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
cd ~/code/acme-platform && git switch main && git pull && claudeOn 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
- The as-of date and time matter: Session 6 reconciles to a moment, not a day.
- 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.
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].
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
| Column | Type | Required | Allowed values or note |
|---|---|---|---|
| party_id | uuid → core_party | yes | |
| crm_account_id | uuid, soft link to crm_account | no | Scopes what a salesperson may see |
| currency | text | yes | A three-letter ISO 4217 code |
| payment_terms | text | yes | due_on_receipt, net_15, net_30, net_45, net_60, eom, deposit |
| tax_exempt | boolean | yes | |
| exemption_certificate_ref | text | no | The certificate reference |
| exemption_expires_on | date | no | The day the certificate lapses |
| credit_limit | bigint (cents) | no | |
| status | text | yes | active, on_hold, closed |
| ext: old_customer_code | text inside ext | no | The old tool's customer code, set by the import; unique when present |
bill_invoice
| Column | Type | Required | Allowed values or note |
|---|---|---|---|
| number | text | yes | Unique; DRAFT- and eight characters of the id while a draft |
| billing_account_id | uuid → bill_billing_account | yes | |
| status | text | yes | draft, approved, issued, partially_paid, paid, void, disputed |
| issue_date | date | no | Set at issue |
| due_date | date | no | Worked out from the account's terms at issue |
| currency | text | yes | A three-letter ISO 4217 code |
| subtotal | bigint (cents) | yes | |
| tax_total | bigint (cents) | yes | |
| total | bigint (cents) | yes | Equals subtotal plus tax_total |
| balance_due | bigint (cents) | yes | Never negative and never above total; 0 when paid or void |
| source_type | text | yes | sales_order, shipment, service_work_order, project_milestone, time_and_materials, manual |
| sales_order_id | uuid, soft link to inv_sales_order | no | |
| service_work_order_id | uuid, soft link to fsm_service_work_order | no | |
| project_id | uuid, soft link to prj_project | no | |
| quote_id | uuid, soft link to crm_quote | no | |
| approval_id | uuid → core_approval | no | Set when a second person must approve |
| issued_hash | text | no | SHA-256 of the issued content |
bill_invoice_line
| Column | Type | Required | Allowed values or note |
|---|---|---|---|
| invoice_id | uuid → bill_invoice | yes | |
| line_no | integer | yes | |
| item_id | uuid → core_item | no | |
| description | text | yes | |
| quantity | numeric(18,4) | yes | |
| uom_id | uuid → core_uom | no | The unit of measure |
| unit_price | bigint (cents) | yes | |
| discount | bigint (cents) | no | |
| line_total | bigint (cents) | yes | |
| tax_code | text | no | EXEMPT on an exempt line |
| tax_amount | bigint (cents) | yes |
bill_tax_rate
| Column | Type | Required | Allowed values or note |
|---|---|---|---|
| jurisdiction | text | yes | Country and region, such as ZZ-T1 |
| tax_code | text | yes | |
| rate | numeric(9,6) | yes | A fraction: 0.07 means 7% |
| valid_from | date | yes | |
| valid_to | date | no | Empty on the current row; two rows for one jurisdiction and tax_code may not overlap |
bill_credit_note
| Column | Type | Required | Allowed values or note |
|---|---|---|---|
| number | text | yes | Unique |
| invoice_id | uuid → bill_invoice | yes | |
| reason_code_id | uuid → core_reason_code | yes | |
| amount | bigint (cents) | yes | Excludes tax |
| tax_amount | bigint (cents) | yes | The credit is amount plus tax_amount |
| status | text | yes | draft, approved, issued, applied |
| reissued_invoice_id | uuid → bill_invoice | no | The corrected invoice, once reissued |
bill_payment
| Column | Type | Required | Allowed values or note |
|---|---|---|---|
| billing_account_id | uuid → bill_billing_account | yes | |
| received_on | date | yes | |
| amount | bigint (cents) | yes | |
| currency | text | yes | Must match the account's currency |
| method | text | yes | card, ach, wire, check, cash, other |
| reference | text | no | A cheque number or similar; never a card or bank account number |
| provider_ref | text | no | The payment provider's own reference |
| unapplied_amount | bigint (cents) | yes | Between 0 and amount |
bill_payment_application
| Column | Type | Required | Allowed values or note |
|---|---|---|---|
| payment_id | uuid → bill_payment | yes | |
| invoice_id | uuid → bill_invoice | yes | |
| amount | bigint (cents) | yes | A mistake is reversed by a new row with a negative amount, never by an update |
| applied_on | date | yes |
bill_dunning_step
| Column | Type | Required | Allowed values or note |
|---|---|---|---|
| days_overdue | integer | yes | Unique per site |
| channel | text | yes | email, letter, call_task |
| template_key | text | yes | |
| stop_on_dispute | boolean | yes |
bill_dunning_event
| Column | Type | Required | Allowed values or note |
|---|---|---|---|
| invoice_id | uuid → bill_invoice | yes | One event per invoice and step |
| dunning_step_id | uuid → bill_dunning_step | yes | |
| at | timestamptz | yes | |
| outcome | text | yes | sent, skipped_dispute, skipped_paid, failed |
bill_posting
| Column | Type | Required | Allowed values or note |
|---|---|---|---|
| document_type | text | yes | invoice, credit_note, payment |
| document_id | uuid | yes | Unique together with document_type; a plain uuid, as the document may be in any of three tables |
| idempotency_key | text | yes | Unique |
| target_system | text | yes | quickbooks, xero, netsuite, sage_intacct, other |
| status | text | yes | queued, posted, failed, reversed |
| external_ref | text | no | The accounting system's reference |
| attempts | integer | yes | Starts at 0; one is added every time the service sends |
| last_error | text | no | |
| posted_at | timestamptz | no |
Session 2: Check the spine tables the module points at
15 minutesWhy
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
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
- 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.
Session 2: One prompt: the ten tables, the never-edit rule and their tests
30 minutesWhy
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
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
- Two of the three pitfalls are closed here, in the database.
- 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.
Session 2: Stand-ins, the seed and the hand-counted fixture, and a try on the development project
25 minutesWhy
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
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.
git fetch && git switch billing/tables && npx supabase link --project-ref tsrqponmlkjihgfedcbanpx supabase db push --include-seedThat loads the made-up rows the first time. After that, reload them with npm run seed:dev.
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
- Only the new files. If it lists anything else, answer n and ask why.
You will see recreated screen
| jurisdiction | rate | valid_from | valid_to |
|---|---|---|---|
| ZZ-T1 | 0.050000 | 2026-02-06 | 2026-08-05 |
| ZZ-T1 | 0.070000 | 2026-08-06 |
- 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
- 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
- IRS Publication 583: Starting a Business and Keeping Records. https://www.irs.gov/publications/p583
- PostgreSQL documentation: constraints (including exclusion constraints). https://www.postgresql.org/docs/current/ddl-constraints.html
- ISO 4217 currency codes. https://www.iso.org/iso-4217-currency-codes.html
- 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.
| Role | Does | Never |
|---|---|---|
| Billing clerk | Drafts, issues and corrects invoices; records and applies payments; keeps accounts, dated rates and reminder steps; chases late payers | Approves a document; updates a posting |
| Sales | Reads the invoices and balances of their own customers; comments on an invoice | Sees another salesperson's customers or any payment |
| Invoice approver | Approves invoices and credit notes above the threshold | Approves one they created; creates invoices |
| Posting service | Sends each document to the accounting system and records the answer | Is used by a person; changes an invoice |
| Cut-over importer | Loads the old tool's open items once, through the import workflow (Sessions 5 and 6), then is set to NOLOGIN | Updates anything; signs in after cut-over |
Session 3: Write the roles, routes and rules into the matrix
25 minutesWhy
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
cd ~/code/acme-platform && git switch main && git pull && claudeRead 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
- 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.
Session 3: Generate the access rules, and prove the refusals
25 minutesWhy
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
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
- A test never seen failing may never fail.
- 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.
Session 3: The billing screens, behind default-deny sign-in
25 minutesWhy
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
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
| Number | Account | Due | Balance |
|---|---|---|---|
| DRAFT-3f9a1c2e | A | 141,750 |
- A draft shows its temporary number. The real number appears only at issue.
- 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
- Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
- PostgreSQL documentation: Row security policies (restrictive). https://www.postgresql.org/docs/current/ddl-rowsecurity.html
- Next.js Docs: proxy.ts (request middleware). https://nextjs.org/docs/app/api-reference/file-conventions/proxy
- 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 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.
Session 4: Drafts from orders and work, with tax by date
30 minutesWhy
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
cd ~/code/acme-platform && git switch main && git pull && claudeRead 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
- 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.
Session 4: Approval, gapless issue and credit notes
30 minutesWhy
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
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
- The lock makes the second issue wait its turn, so the series never skips or repeats.
- 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.
Session 4: Payments, statements and reminders that stop on dispute
25 minutesWhy
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
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
- 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
Session 4: One signed posting per document, and the scenario counted by hand
35 minutesWhy
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
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.
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 secret | What it unlocks | Where it lives | Who holds it | Never |
|---|---|---|---|---|
| POSTING_SIGNING_SECRET | Signs every posting so the accounting side can check it came from you, unchanged | Vercel environment variables; the password manager | pat@acme.com, sam@acme.com | Never in a file, a chat or Claude Code; never the same value for preview and production |
| POSTING_TARGET | Which accounting system postings go to (other = the journal file) | Vercel environment variables | pat@acme.com, sam@acme.com | Never switched to the live ledger before Session 6's reconciliation is 0 |
You will see recreated screen
- Every figure here is one you can reach with a calculator from the fixture. Compare before you merge.
- 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
- OASIS: Universal Business Language (UBL) 2.1 (Invoice and CreditNote). https://docs.oasis-open.org/ubl/UBL-2.1.html
- ISO 20022: financial messaging standard (camt.053, camt.054). https://www.iso20022.org/
- PostgreSQL documentation: explicit locking (SELECT FOR UPDATE). https://www.postgresql.org/docs/current/explicit-locking.html
- 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.
Session 5: The import workflow, rehearsed on the development project with an approved copy
50 minutesWhy
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
cd ~/code/acme-platform && git switch main && git pull && claudeOn 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.
https://github.com/acme-ops/acme-platform/settings/secrets/actions
GitHub Actions secrets: BILLING_IMPORTER_PASSWORD_DEV, the value only.
https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/storage/buckets
Development project Storage: upload the approved copy to the private bucket imports.
shasum -a 256 *.csvOn 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.
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
| File | Rows | Loaded | Skipped |
|---|---|---|---|
| customers.csv | 214 | 214 | 0 |
| open_invoices.csv | 388 | 388 | 0 |
| unapplied_payments.csv | 17 | 17 | 0 |
- Only the files owner two approved, with the row counts recorded, can be imported.
You will see recreated screen
- 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.
Session 6: Cut over: import production through the workflow, reconcile to zero, switch the target yourself
45 minutesWhy
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).
https://supabase.com/dashboard/project/abcdefghijklmnopqrst/storage/buckets
Production Storage: upload the exports to the private bucket imports.
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.
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:
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
| Document | Key | Target | Status | Attempts |
|---|---|---|---|---|
| INV-100001 | invoice:7c1e… | your ledger | posted | 1 |
| Opening C-0012 | opening:88412 | your ledger | posted | 1 |
- Attempts 1: posted first time. The new series (INV-1…) cannot clash with the old tool's numbers.
- 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.
Session 6: Close the importer the same day
25 minutesWhy
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
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
- Retired, not deleted: the history of who could do what stays readable.
- 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.
Session 6: A week side by side, then cancel with the saving written
30 minutes, then a weekWhy
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.
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
| Measure | Old tool (shadow) | Platform |
|---|---|---|
| Invoice accuracy | 17 of 20 | 20 of 20 |
| Posting success | not measured | 100% |
| Time to invoice | not measured | 3.5 h |
- Illustrations: yours come from your own reports. Write "not measured" where the old tool cannot say; never guess.
- 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.
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
- IRS Publication 583: Starting a Business and Keeping Records. https://www.irs.gov/publications/p583
- Vercel Docs: Environment variables. https://vercel.com/docs/environment-variables
- 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
Your result
CivOps AI Academy
Quotes, Orders and Invoicing: Order-to-Cash Up to the Ledger
Element M22 complete · Learner
Your LMS records this completion. For the CivOps Foundation certificate, finish the Foundation Course at https://civops.io/learn.