Skip to the lesson
CivOps AI Academy · M12Purchasing and Inventory: Ledger, MRP and Purchasing on Your Own Platform
0%

Chapter 1 · Sessions 1–2

What the old tool holds, and the tables that replace it

Session 1 maps the stock, planning and purchasing tool you use today from its own reports and bills, and measures how accurate its stock really is. Session 2 builds the module's fifteen tables on your Foundation spine, with one rule above all: stock is never edited, only moved by a transaction that is never changed.

25 min5 steps15 tablesAbout 8 hours hands-on across six sessions

By the end of this chapter you can

  • Map the old tool from its own reports, bills and a blind count, with no number guessed.
  • Say why every stock movement is an append-only transaction and balances are only ever derived.
  • Have Claude Code build the module's tables, their tests and a seed, and try them on the development project yourself.

What the module replaces, and what it leaves alone

Purchasing and inventory replaces the stock, material-planning and purchasing parts of a manufacturing ERP. The specification names Epicor Kinetic, Plex, NetSuite Manufacturing, Acumatica, SAP Business One, Odoo MRP, Katana, MRPeasy, Fishbowl, ECI JobBOSS2 and E2, and ProShop; many plants use a spreadsheet. Tools in this class offer the same core: MRP, lot tracking and costing [5].

It keeps an exact stock record by item, lot, serial number, location and status; plans material with MRP (material requirements planning: working out what to buy or make, and when); runs purchasing from request to receipt; and hands the invoice match status to accounting. The general ledger, paying suppliers, collections and tax stay in the accounting system.

The edge of the moduleInside the module: ledger, lots and status, planning and MRP, sales orders, purchasing, and receiving with invoice match status. Outside: the accounting system (general ledger, payment, tax), M13 warehouse tasks and M03 finite scheduling. INSIDE M12 · PURCHASING AND INVENTORYInventory ledgerevery movement a transactionLots and statusavailable, quarantine, holdPlanning and MRPparameters, planned ordersSales ordersavailable to promisePurchasingrequisition to approved orderReceiving and matchreceipt, invoice match statusOUTSIDE, WITH AN OWNERAccounting systemgeneral ledger, AP, AR, taxM13 Warehousedirected warehouse tasksM03 Schedulingfinite scheduling
The edge of the module. Inside: ledger, lots and status, planning and MRP, sales orders, purchasing, receiving with the invoice match status. Outside, each with its owner.
StandardUse in this module
ASCM/APICS CPIM body of knowledgeMRP logic, lot-sizing rules, safety stock
US GAAP ASC 330 and IAS 2How inventory is measured and costed; your accountant owns the method [1]
ISA-95 Parts 2 and 5, B2MMLExchange of schedules, material lots and performance between ERP and MES
OAGIS, UBL 2.x, ANSI X12 850, 855, 856, 810Purchase orders, acknowledgements, ship notices and invoices between companies
SOX IT general controls (where they apply)Different people approve and receive a purchase order

Session 1: the map, from the tool's own reports

Every number in this session is read, not remembered: from the tool's reports, its bill and a count on the floor. A replacement built on guesses replaces the guesses, and the day you switch over, the real tool's habits surface as problems. The map also gives Session 5 and 6 their targets: the counts and values the new module must match.

Step 1

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

40 minutes

Why

You cannot replace what you have not written down. The map names every item, lot, location, order and user the old tool holds, what it costs, and what people work around, so the module replaces real work and the saving at the end is arithmetic from real invoices, not a hope.

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 inventory/map, write docs/inventory-map.md for the stock, MRP and purchasing tool we use today. Do not invent any number: write every figure as a blank for me to fill in, with where to read it, and mark anything nobody knows as "Unknown: ask <who>".

Sections:
1. Tools: name, owner, how people sign in, who pays the bill, and the export route (CSV or API) for items, orders, transactions and the stock valuation report.
2. What it holds: counts of items, lot-tracked items, serial-tracked items, locations, and the stock statuses it has (available, quarantine, hold or others). Does a held lot stay out of available stock and out of available-to-promise?
3. How it plans, for ten items: planning method, lot-sizing rule, lead time, safety stock, planner, buyer. Do MRP messages say which demand they are for?
4. Open orders: purchase order lines, sales order lines, requisitions waiting. Who creates, approves and receives a purchase order; can one person both approve and receive? (If yes, that is a finding.)
5. Users by job, not by name: planner, buyer, approver, receiver, stock user. A person doing two of these is a finding.
6. Valuation: the costing method the valuation report uses (standard, average or FIFO), read from the report's settings.
7. Bill: amount, renewal date, notice period, from the vendor's own account page.
8. Workarounds: stock changed by editing the quantity, negative stock, late receipts, spreadsheets beside the tool, messages nobody trusts.
9. The pilot item family (about twenty items) and why.

Open a pull request titled "Inventory map" and show me the link. Do not read any export file.

Then fill in the blanks from the old tool's own reports and the vendor's account page. Save one copy of today's stock valuation report in a private company folder outside the repository: Sessions 5 and 6 reconcile to it.

You will see recreated screen

claude — acme-platform
⏺ Bash(git switch -c inventory/map)
⎿ Switched to a new branch 'inventory/map'
⏺ Write(docs/inventory-map.md)
+## 4. Open orders
+| What | Count | Read from |
+| Open purchase order lines | ____ | Purchasing > Open PO lines report |
+| Can one person approve AND receive? | ____ | User roles report. If yes: FINDING |
1
⏺ Write(docs/inventory-map.md)
+## 7. Bill
+Amount: ____ Renewal: ____ Notice: ____
+Read from the vendor's account page, not from memory. Unknown: ask finance.
2
⏺ Pull request #52 adds docs/inventory-map.md with 9 sections and 41 blanks. Every figure says which report it comes from. I did not read any export.
Claude Code writes the map as blanks to fill, never as numbers it made up.
  1. Each blank says which report holds the answer, so you are never guessing.
  2. The bill comes from the vendor's page or your invoices. Never an estimate.

Check it worked

The pull request holds docs/inventory-map.md with every blank filled from a report or marked Unknown with a name; the valuation report copy is saved outside the repository with today's date.

Fastest path

Ask the tool's owner for a read-only sign-in that can run reports before the session; reading reports yourself is quicker than asking for each number.

If it goes wrong

Claude Code filled in numbers, prices or counts itself

Say: Replace every number you wrote with a blank and the report it comes from. Nothing in this file may be a guess. A guessed count becomes a target the module is later judged against.

You cannot see the bill

Write Unknown: ask finance and the name. Do not estimate from the vendor's price list: discounts, seats and add-ons make list prices wrong for your plant.

Two reports disagree on a count

Write both numbers and which report each came from. The disagreement is a finding: it tells you the old tool is not one source of truth, which is part of why you are replacing it.

Step 2

Session 1: Count ten locations blind, then choose the pilot

30 minutes

Why

Stock accuracy is the number the module will be judged on, so you need today's figure measured the same way the module will measure it. Counting with the system quantity hidden keeps the count honest; a count that looks at the screen first only confirms the screen.

Do this

Choose a tolerance (for example plus or minus one unit, or 2%) and write it down first. Print the list of ten locations from the old tool with the quantity column hidden. Count them on the floor, then compare. Then:

Paste into Claude Code, after replacing the <...> parts
Add a section "Baseline accuracy" to docs/inventory-map.md on the branch inventory/map:
- tolerance: <your tolerance>
- locations counted: 10, counted blind on <date> by <job, not name>
- locations within tolerance: <number>
- inventory accuracy = locations within tolerance / locations counted = <result>%

Then fill section 9 with the pilot family: about twenty items including one lot-tracked bought item with an open purchase order and one made item with a bill of materials. Push to the same pull request and wait for its checks to be green before you report.

Have the planner read the pilot choice; owner two approves; merge.

You will see recreated screen

github.com/acme-ops/acme-platform/pull/52/files
ConversationCommitsFiles changed
docs/inventory-map.md
Baseline accuracyTolerance ±1 unit · 10 locations counted blind · 7 within tolerance · 70%1
Pilot familyBrackets family, 21 items: A-bracket steel (lot-tracked, open PO) and the BR-2 assembly (made, 4 components)2
The map on GitHub with the baseline. Accuracy is a fraction of locations, not a percentage of units.
  1. Seven of ten within tolerance is 70%. Write the tolerance next to it, or the number cannot be compared later.
  2. One bought lot-tracked item and one made item, so Sessions 4 to 6 exercise both purchasing and the bill of materials.

Check it worked

docs/inventory-map.md is merged with the tolerance, the blind count result and a pilot family the planner has read.

If it goes wrong

The count found negative stock in the old tool

Write it down as a finding. In the module a balance can never go below zero: a movement that would do so is refused. Negative stock in the old tool is where you will find late receipts and unrecorded issues.

The counter saw the system quantity first

Count those locations again with someone who has not seen it. A count that confirms the screen measures nothing.

Knowledge check

Ten locations are counted blind; seven are within your tolerance. What is the baseline inventory accuracy?

Session 2: every movement is a transaction

The table inv_inventory_transaction is the ledger. One row is one movement of one item (and lot, and serial unit where tracked) from a location and status to another. Nothing else changes a quantity. inv_inventory_balance holds the current quantity by item, site, location, lot, serial unit and status, and is only ever the sum of the ledger, kept current by the one route that posts (Session 4).

  • Quantity is always above zero. Direction comes from the from and to locations (and statuses), never from a negative number.
  • The ledger refuses edits. A database trigger raises an error on any update or delete of a ledger row, whatever wrote it [3].
  • A mistake is a reversal. A second row with from and to swapped, reason REVERSAL, pointing back with reversal_of_id. A row can be reversed only once.
  • A held lot stays visible. It sits in the balances with status hold, outside the view of available stock, so no order can use it.
A reversalAn original adjustment of 5 to STOCK, and a new reversal row that swaps the location, carries reason REVERSAL and points back with reversal_of_id. The balance goes 20, 25, 20 and the original row is never changed. Original, posted by mistaketxn_type: adjustment · txn 0007to_location: STOCKqty: 5 (always above zero)reason: COUNT-VARReversal, a new rowtxn_type: adjustment · txn 0008from_location: STOCK (swapped)qty: 5 · reason: REVERSALreversal_of_id: row 0007points toBalance of the item at STOCK: 20 before, 25 after the original, 20 after the reversal.The original row is never touched; the database refuses any update or delete of it.A second reversal of row 0007, or a reversal of a reversal, is refused.
A reversal. The original adjustment stays. The reversal swaps the location and points back to it, so the balance returns. History shows the mistake and its correction.
txn_typeWhat happened
po_receiptGoods arrived from a supplier against a purchase order line
production_issue, production_receiptMaterial used by production; finished goods booked in
transfer_out, transfer_inStock left one location and arrived at another
adjustmentA quantity corrected, always with a reason code (and the opening balance, reason OPENING)
scrapStock written off as unusable
shipment, customer_returnGoods left for a customer; goods came back
vendor_returnGoods sent back to a supplier
cycle_countThe difference found by a count
status_changeStock moved between statuses, such as available to hold

The fifteen tables

Claude Code builds these from this list in Step 4. Every table also has the specification's standard columns: id, tenant_id, created_at, created_by, updated_at, updated_by, row_version, archived_at and ext. An arrow (→) names the table a column points at; qty is a quantity, money an amount, ts a date and time. Where a column lists its values, no other value is allowed. The specification also describes inv_cost_record and inv_demand_forecast, which this course does not build.

TableColumns: type, req = required
inv_inventory_transaction (append-only ledger)txn_no text req, unique; txn_type req: po_receipt, production_issue, production_receipt, transfer_out, transfer_in, adjustment, scrap, shipment, customer_return, vendor_return, cycle_count or status_change; item_id → core_item req; lot_id → core_lot; serial_unit_id → core_serial_unit; from_location_id, to_location_id → core_storage_location; from_status, to_status text; qty qty req; uom_id → core_uom req; unit_cost money; ref_type text; ref_id uuid; reason_code_id → core_reason_code; txn_at ts req; posted_by → core_person; reversal_of_id → inv_inventory_transaction
inv_inventory_balance (derived)item_id → core_item req; site_id → core_site req; storage_location_id → core_storage_location req; lot_id → core_lot; serial_unit_id → core_serial_unit; status req: available, quarantine, hold, allocated, in_transit, consigned or damaged; qty_on_hand qty req; uom_id → core_uom req; last_txn_at ts
inv_item_site_planitem_id → core_item req; site_id → core_site req; planning_method req: mrp, reorder_point, min_max, kanban or none; lot_size_rule req: l4l, foq, eoq, poq or min_max; fixed_qty, min_qty, max_qty, order_multiple, safety_stock qty; lead_time_days int; abc_class: a, b or c; planner_id, buyer_id → core_person; make_buy req: make, buy or transfer
inv_bom_simpleparent_item_id → core_item req; component_item_id → core_item req; qty_per qty req; uom_id → core_uom req; scrap_pct num; effective_from, effective_to date
inv_supplier_itemsupplier_party_id → core_party req; item_id → core_item req; supplier_part_no text; unit_price money; currency text; moq qty; lead_time_days int; preferred bool req; valid_from, valid_to date
inv_purchase_requisitionreq_no text req, unique; requested_by → core_person req; item_id → core_item; description text; qty qty req; uom_id → core_uom; need_by date; planned_order_id → inv_planned_order; cost_center_id → core_cost_center; status req: draft, submitted, approved, rejected or converted
inv_purchase_orderpo_no text req, unique; supplier_party_id → core_party req; order_date date req; status req: draft, pending_approval, approved, sent, acknowledged, partially_received, received, closed or cancelled; currency text req; payment_terms, incoterm text; ship_to_site_id → core_site; buyer_id → core_person; total money; approved_signature_id → core_e_signature
inv_purchase_order_linepurchase_order_id → inv_purchase_order req; line_no int req; item_id → core_item; description text; qty qty req; uom_id → core_uom req; unit_price money req; need_by date; qty_received, qty_invoiced qty; account_hint text; requisition_id → inv_purchase_requisition; project_ref → prj_project (soft link)
inv_goods_receiptreceipt_no text req, unique; purchase_order_line_id → inv_purchase_order_line req; qty qty req; lot_id → core_lot; storage_location_id → core_storage_location; received_at ts req; received_by → core_person; inspection_required bool req; inventory_transaction_id → inv_inventory_transaction
inv_invoice_matchpurchase_order_line_id → inv_purchase_order_line req; supplier_invoice_no text req; invoice_qty qty; invoice_amount money; match_status req: pending, matched, price_variance, qty_variance or rejected; exported_at ts
inv_mrp_runrun_no text req, unique; site_id → core_site; run_at ts req; horizon_days int req; parameters json; status req: running, complete or failed; triggered_by → core_person
inv_planned_ordermrp_run_id → inv_mrp_run req; item_id → core_item req; site_id → core_site req; order_type req: make, buy or transfer; qty qty req; due_at, release_at date req; status req: planned, firmed, released or cancelled; pegging json
inv_mrp_exceptionmrp_run_id → inv_mrp_run req; item_id → core_item req; exception_type req: expedite, defer, cancel, past_due, below_safety_stock, no_source or lead_time_violation; ref_type text; ref_id uuid; message text req; suggested_date date; status req: open, actioned or ignored
inv_sales_orderso_no text req, unique; customer_party_id → core_party req; order_date date req; requested_at, promised_at date; status req: draft, confirmed, in_production, partially_shipped, shipped, invoiced, closed or cancelled; currency text req; ship_to_address_id → core_address; crm_opportunity_ref, quote_ref (soft links to CRM); customer_po text
inv_sales_order_linesales_order_id → inv_sales_order req; line_no int req; item_id → core_item req; qty qty req; uom_id → core_uom req; unit_price money req; requested_at, promised_at date; qty_shipped qty; status req: open, allocated, in_production, shipped or cancelled
Step 3

Session 2: Check the spine tables the module points at

15 minutes

Why

The module has no item, site, location or supplier list of its own: it points at the spine's. If a spine table is missing, the module's migration fails, or worse, Claude Code quietly creates a second item list inside it and the plant has two. Checking first, and adding anything missing in its own migration, keeps one list of everything.

Do this

Paste into Claude Code
Read supabase/migrations/ and docs/SCHEMA-PLAN.md. Do not write anything yet.

The inventory module (spec/academy/module-library/modules/M12_inventory-mrp-purchasing.md if present, otherwise the list below) points at these spine tables: core_item, core_site, core_uom, core_storage_location, core_lot, core_serial_unit, core_party, core_person, core_cost_center, core_reason_code, core_number_sequence, core_approval, core_comment, core_e_signature; and the helpers core_current_tenant(), core_touch_row(), core_audit_row() with core_audit_log, and core_block_mutation() (a trigger function that refuses update and delete).

For each one, tell me: present (and in which migration), present under another name (for example our sites table for core_site, parts for core_item, lots for core_lot), or missing.

Rules for what comes next, so we do not need to discuss it again:
- Where our schema already holds the same thing under another name, do not create a second table. The module keeps its column names (item_id, site_id, lot_id) and points them at our existing table, with the existing id type. Write the mapping as this module's own section, "M12 Purchasing and inventory", in docs/spine-map.md, the one shared map (create it if no earlier module did; never a separate tables file).
- Whatever is truly missing goes in ONE new spine migration on a branch inventory/spine, with row-level security on and pgTAP tests, never inside the module's own migration.

Show me the list first. If anything is missing, then write the spine migration, open a pull request titled "Spine for inventory", wait for the schema check to finish and tell me the result in plain words.

You will see recreated screen

claude — acme-platform
⏺ core_site: present as sites (20261016091500). core_item: present as parts. core_lot: present as lots. core_party, core_storage_location, core_uom, core_reason_code, core_number_sequence, core_approval, core_e_signature: missing. core_block_mutation(): present as public.append_only().1
⏺ Write(docs/spine-map.md)
+## M12 Purchasing and inventory
+| Module column | Points at |
+| item_id | public.parts(id) |
+| site_id | public.sites(id) |
+| lot_id | public.lots(id) |
2
⏺ Bash(npx supabase migration new spine_for_inventory)
⎿ Created new migration at supabase/migrations/20261102081000_spine_for_inventory.sql
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m03s
⏺ Pull request #53 adds 7 spine tables with row-level security on and 22 tests. Nothing in it touches the module's tables.
The check lists every spine table and helper, then adds only what is missing.
  1. The existing Foundation tables are reused, not copied. Your names will be the ones from your schema plan.
  2. The mapping is written down, so the next prompt and every later session read it instead of guessing.

Check it worked

Pull request Spine for inventory is green (or Claude Code reported nothing missing), and the M12 section of docs/spine-map.md maps each module column to an existing table.

If it goes wrong

Claude Code created core_item although parts already exists

Say: Remove core_item. Point item_id at public.parts as the M12 section of docs/spine-map.md says. Two item lists drift apart within weeks, and every report has to choose one.

CI fails: type mismatch on a foreign key (uuid and bigint)

The module's columns must use the id type of the table they point at. Say: Use the referenced table's id type for every foreign key, push, and wait for the check.

Step 4

Session 2: One prompt: the tables, the append-only ledger and their tests

25 minutes

Why

Writing the tables, the rules and the tests that prove the rules in one pull request means the proof arrives with the change. Rules kept in the database protect every screen, route and import, including the import in Sessions 5 and 6. One complete prompt replaces a dozen rounds of adding each rule as you think of it.

Do this

Paste into Claude Code
Read the M12 section of docs/spine-map.md, docs/naming-standard.md and the table list in the M12 specification (or the lesson's table).

On a new branch inventory/tables:

1. npx supabase migration new inventory_tables. Create the fifteen tables: inv_inventory_transaction, inv_inventory_balance, inv_item_site_plan, inv_bom_simple, inv_supplier_item, inv_purchase_requisition, inv_purchase_order, inv_purchase_order_line, inv_goods_receipt, inv_invoice_match, inv_mrp_run, inv_planned_order, inv_mrp_exception, inv_sales_order, inv_sales_order_line, with every column in the list. Required means not null; listed values are check constraints; quantities numeric(18,6); money numeric(18,4); times timestamptz. Every table gets the standard columns, a site_id (our Foundation rule: every table has a site, so access is one rule per table), row-level security on with no policies, and the core_touch_row() and core_audit_row() triggers. Foreign keys only to our spine tables (by the M12 section of docs/spine-map.md) and to each other.

2. The ledger, inv_inventory_transaction: a before update or delete trigger using our existing refuse-changes function; txn_no unique per site; qty > 0; at least one of from_location_id and to_location_id set; a partial unique index on reversal_of_id so a row can be reversed only once; a unique index on ext->>'client_ref' so a retried request posts once.

3. inv_inventory_balance: unique on item, site, storage location, lot, serial unit and status with NULLS NOT DISTINCT; qty_on_hand >= 0.

4. Two views, with (security_invoker = true): inv_balance_from_ledger (sums the ledger: each row takes qty out of its from location and status and into its to location and status; an empty status means available) and inv_available (balances with status available only).

5. pgTAP tests in supabase/tests/inventory-tables.test.sql proving the database refuses: an update and a delete of a ledger row, a qty of zero, a second balance row with no lot for the same key, a status or txn_type outside the lists, a second reversal of the same row. And that row-level security is on for all fifteen tables.

6. Write the rules in plain words in docs/inventory-rules.md. Do not connect to or change any Supabase project.

Push, open a pull request titled "Inventory tables", wait for the schema check to finish, and tell me the result in plain words. If it fails, fix it and wait again before reporting.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase migration new inventory_tables)
⎿ Created new migration at supabase/migrations/20261102093000_inventory_tables.sql
⏺ Write(supabase/migrations/20261102093000_inventory_tables.sql)
+create trigger inv_txn_append_only before update or delete
+ on public.inv_inventory_transaction
+ for each row execute function public.append_only();
+create unique index inv_txn_reversed_once
+ on public.inv_inventory_transaction (reversal_of_id) where reversal_of_id is not null;
1
⏺ Write(supabase/tests/inventory-tables.test.sql)
+select throws_ok($$ update public.inv_inventory_transaction set qty = 1 $$, 'append-only');
+select throws_ok($$ insert into public.inv_inventory_balance (..., qty_on_hand) values (..., -1) $$);
2
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m41s
⏺ Pull request #54 is green. 15 tables, all with row-level security on and no policies yet. 27 tests passed, including 9 that try to store bad stock data and are refused.
The ledger table, its refusals and the tests that try to break them.
  1. The ledger refuses changes in the database itself, so no screen or import can get round it.
  2. Each rule has a test that tries to break it. A rule nobody tests is a rule a later change can quietly remove.

Check it worked

Pull request Inventory tables is green on GitHub, and the summary says how many tests tried bad data and were refused.

Fastest path

"Wait for the schema check and fix it before reporting" saves a round trip: Claude Code reads the failure and fixes it while you do something else.

If it goes wrong

CI fails with: syntax error at or near "NULLS"

NULLS NOT DISTINCT needs PostgreSQL 15 or later. Say: Check the Postgres major version in supabase/config.toml matches the live project (Settings, Infrastructure) and use it in CI.

Claude Code added policies so the screens can read

Say: Remove every policy. Access comes from docs/matrix.json in Session 3. A policy written before the matrix is a guess about who may see stock and prices.

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 learned to trust the check on GitHub, never the summary.

Later, after merging main into a branch, a table or test you added has gone

Someone undid a batch on main and the undo took yours with it; no conflict is reported. We hit this. Say: I just merged main. List every schema change and test this branch added and confirm each is still there. The tests above turn this silent loss into a red check.

Step 5

Session 2: Seed the worked example, and try it on the development project yourself

20 minutes

Why

The seed is the small, made-up plant every later step is checked against: 60 on hand, 50 available, an order of 20 on the way. Trying the migration and the seed on the development project first, from your own terminal, shows they work on a real Supabase database before the deploy pipeline applies the migration to production on merge.

Do this

Paste into Claude Code
On the branch inventory/tables, write supabase/seeds/inventory.sql and list it under [db.seed] sql_paths in supabase/config.toml, after the Foundation seed. Never append to supabase/seed.sql, and never seed production. Every row is made up and marked SYNTHETIC, as Foundation Session 6 requires, and the file is safe to run twice (on conflict do nothing):
- one site with locations STOCK and LINESIDE; supplier Supplier One, customer Customer One;
- items P-100 (made), A-100 and B-100 (bought, lot-tracked); lots LOT-A-001 (released) and LOT-A-002 (on hold, the whole lot);
- reason codes OPENING, COUNT-VAR, QUALITY-HOLD, RETURN-DEFECT, REVERSAL; numbering rows for inv_txn, inv_req, inv_po, inv_receipt, inv_so, inv_mrp_run;
- preferred supplier items from Supplier One: A-100 at 1.5000, minimum 40, 14 days; B-100 at 2.5000, minimum 20, 7 days;
- plans: A-100 buy, mrp, foq 40, safety stock 10, lead time 14; B-100 buy, reorder_point, min_qty 30, foq 100, lead time 7; P-100 make, mrp, l4l, safety stock 0, lead time 7; bill of materials: P-100 needs 2 of A-100;
- opening ledger: 50 of A-100 in LOT-A-001 available and 10 in LOT-A-002 on hold, at STOCK, each one adjustment with reason OPENING, and the matching balance rows;
- one acknowledged purchase order for 20 of A-100 due 7 days from today; one confirmed sales order for 10 of A-100 due today; one complete MRP run with three firmed planned orders for P-100: 15, 20 and 12, released 14, 28 and 42 days from today.
Every date is shifted onto today: relative to the day the seed runs, read once, so the data never ages. Fixed-date hand-worked examples (the MRP example in Session 4) are test fixtures in tests/fixtures/inventory-*.json, never seed rows.

Also add supabase/tests/inventory-seed.test.sql: after the seed runs twice, A-100 has 60 on hand and 50 available, and inv_balance_from_ledger equals inv_inventory_balance on every row.

Push to the same pull request, wait for the checks and report. Do not connect to any Supabase project.

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

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

That is the first load. After it, reload the made-up rows with npm run seed:dev, never with supabase db reset.

Open

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

The development project's SQL editor. Run the query below; it must show 60 and 50.

select sum(qty_on_hand) as on_hand, sum(qty_on_hand) filter (where status = 'available') as available from inv_inventory_balance b join parts i on i.id = b.item_id where i.part_number = 'A-100'; (use your own item table and column names from the M12 section of docs/spine-map.md).

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? • 20261102081000_spine_for_inventory.sql • 20261102093000_inventory_tables.sql [Y/n] y1
Seeding data from supabase/seeds/inventory.sql...
Finished supabase db push.2
db push lists exactly what it will apply to the development project. Read the project reference before you answer y.
  1. Only the two new files. If it lists anything else, answer n and ask Claude Code why.
  2. The development project now has the tables and the made-up plant.

You will see recreated screen

supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new
SQL Editor · acme-platform-dev
1
on_handavailable
60.00000050.000000
The check in the development project's SQL editor.
  1. 60 on hand, 50 available: the 10 on hold in LOT-A-002 are on hand but not available.

Check it worked

The pull request is green, the development project shows 60 on hand and 50 available for A-100, and after owner two approves and you merge, the deploy workflow run on github.com/acme-ops/acme-platform/actions is green (it applies the migration to acme-platform-prod; the seed never goes there).

If it goes wrong

The link command shows abcdefghijklmnopqrst (production) instead of tsrqponmlkjihgfedcba

Stop and answer n to anything it asks. Run the link command again with tsrqponmlkjihgfedcba. Made-up data must never enter production, and from Session 11 production changes only through the deploy pipeline.

A week later the dates in the dev project are all in the past

The seed wrote fixed dates. We hit this: measured eleven days after seeding, the newest record was 10.9 days old and every "this week" view was empty. Say: Make every seeded date relative to the moment the seed runs, read the clock once, and add a test that the newest record is under an hour old. Then reload with npm run seed:dev.

Someone suggests supabase db reset --linked to start again

Do not. To start the made-up rows again on the development project, run npm run seed:dev.

A later step expects a number the seed does not create

Reviews of five Academy modules found this fault. Say: List every count and quantity the later inventory steps and tests expect, and show the seed line that creates each. Fix the seed, not the check.

db push says the remote has migrations that are not in the local directory

Someone changed the development project outside the files, or main moved on. Do not force anything. Run git switch main && git pull, merge main into the branch, and try again. If it persists, ask Claude Code to explain which versions differ, without changing any project.

Knowledge check

A balance row for A-100 is wrong. How is it corrected in this module?

References

  1. IFRS Foundation: IAS 2 Inventories. https://www.ifrs.org/issued-standards/list-of-standards/ias-2-inventories/
  2. PostgreSQL documentation: constraints. https://www.postgresql.org/docs/current/ddl-constraints.html
  3. PostgreSQL documentation: trigger functions. https://www.postgresql.org/docs/current/plpgsql-trigger.html
  4. Supabase Docs: Database migrations. https://supabase.com/docs/guides/deployment/database-migrations
  5. MRPeasy: features by plan (MRP II, routings, lot tracking, costing). https://www.madesmarter.uk/media/b5fpo5ai/mrpeasy_features_by_plan.pdf
  6. Supabase Docs: Testing your database (pgTAP). https://supabase.com/docs/guides/database/testing

Chapter 2 · Session 3

Who may plan, buy, approve, receive and move stock

Session 3 writes the module's roles into your role matrix, generates the access rules from it, proves that the person who approves an order cannot receive against it, and builds the six screens behind the sign-in that denies by default.

25 min3 steps5 roles + board, inv_importer, balance_check6 screens

By the end of this chapter you can

  • Write the module's roles, routes and separation rules into docs/matrix.json, as jobs not names.
  • Generate the access rules with scripts/gen-policies.mjs and prove each allowed and refused cell with a test.
  • Build the six screens behind default-deny sign-in, and pass the phone check.

Five jobs, kept apart

Where SOX applies, approving and receiving an order must be different people. Security guidance calls it separation of duties: no one person can complete a sensitive process alone [2]. The module writes it as rules in the matrix, so the database refuses, not just the screen.

Duties kept apartA grid of five roles against five actions. Buyer creates orders, approver approves them, receiver receives goods, stock user issues, moves and counts, and planner releases a hold. Blank cells are refused. The approver of an order cannot receive against it. Create POApprove POReceive goodsIssue, move, countRelease a holdBuyerApproverReceiverStock userPlannera right the matrix grants · blank: refusedWhoever approved an order cannot receive against it, and one person cannot hold both roles on a site.An approver cannot approve what they raised, and a second approval step needs a different person.
Five roles, five actions. A dot is a right the matrix grants. Everything blank is refused by the rules generated from the matrix, not just hidden on a screen.
RoleMayMay not
PlannerPlans, bills of materials, MRP runs, planned orders and messages, adjustments, release a hold, reversalsApprove or receive
BuyerSupplier prices, purchase orders while draft, submit, change need_by, invoice matchApprove an order where buyer_id is theirs
ApproverApprove or reject requisitions and orders, with an e-signatureApprove what they raised; give both steps; receive
ReceiverReceive against approved orders, create the lot, return to vendorRelease a hold; receive an order they approved
Stock userIssue, transfer, scrap, count, place a hold, raise a requisitionRelease a hold back to available
Board (read-only)Three tiles: on hand by status, open messages by age, open ordersAnything else
inv_importer (machine)Insert the old tool's records once, through the import workflow (Sessions 5 and 6), and post OPENING adjustments through the posting functionRead, change or delete anything; sign in after cut-over (set to NOLOGIN)
balance_checkRead the ledger, the balances and inv_balance_from_ledgerWrite anything
Step 6

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

25 minutes

Why

The access rules, the route guard and their tests are all generated from docs/matrix.json, so a right that is not written there does not exist, and a later session that needs it is refused. Writing every role, route and separation rule now, checked by the planner and a receiver, prevents the refusals you would otherwise meet one by one in Sessions 4 to 6.

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, docs/inventory-rules.md and the M12 section of docs/spine-map.md. On a new branch inventory/matrix, add the inventory module to docs/matrix.json. Scope for every right: own site. No delete right anywhere.

Roles (jobs, not people): planner, buyer, approver, receiver, stock_user; plus board (read-only), inv_importer (the import workflow's insert-only database login) and balance_check (read-only service identity). In a separate migration create inv_importer with NOLOGIN, no BYPASSRLS, owning nothing; I set its password myself on each project, and you list it by name (never a value) in docs/KEYS.md.
- planner: read every inv_ table and inv_available; insert/update inv_item_site_plan, inv_bom_simple, inv_sales_order(_line); update status on inv_planned_order and inv_mrp_exception; insert inv_purchase_requisition.
- buyer: insert/update inv_supplier_item; insert inv_purchase_order(_line) and update them while draft; update status only (pending_approval, sent, acknowledged, closed, cancelled); update need_by only on open lines; insert inv_invoice_match.
- approver: read orders, lines, requisitions; update status (and approved_signature_id) only; insert core_e_signature and core_comment.
- receiver: read approved and later orders and their lines; insert inv_goods_receipt and core_lot through the receive route only.
- stock_user: read balances and inv_available; insert own requisitions and update them while draft.
- board: read inv_inventory_balance, inv_mrp_exception, inv_purchase_order(_line), inv_goods_receipt, items and units.
- balance_check: select only on inv_inventory_transaction, inv_inventory_balance, inv_balance_from_ledger.
- inv_importer: insert only on units, items, suppliers, locations, lots, plans, bills of materials, supplier items and open order headers and lines, and execute on the posting function for adjustments with reason OPENING only; never select, update or delete.
- No role: insert, update or delete on inv_inventory_transaction or inv_inventory_balance.

Routes, each its own row with its callers: /api/inventory/post (stock_user, receiver, planner; each caller only its own transaction types), /receive (receiver), /po (stock_user and planner for requisitions, buyer for orders), /mrp (planner), /match (buyer). No import page or route: real records arrive only through the import workflow in Sessions 5 and 6.

Restrictive rules (they can only take rights away): whoever approved an order cannot receive against it; one person cannot be approver and receiver on one site; an approver cannot approve a requisition they raised or an order where buyer_id is theirs; a second approval step needs a different person; stock_user and receiver cannot release a hold; an ended role assignment is refused at once.

Screens: /inventory/receive (receiver) and /inventory/stock (stock_user) on the operator surface; /inventory/approvals, /inventory/purchasing, /inventory/planning on the desk; /inventory/board (board).

Next to each right, in docs/inventory-rules.md, write the later step that needs it. Do not generate anything yet. Open a pull request titled "Inventory roles" and show me the link.

Read the pull request with the planner and one receiver for ten minutes each: is every job they do there, and nothing more?

You will see recreated screen

claude — acme-platform
⏺ Write(docs/matrix.json)
+"inv_goods_receipt": {
+ "receiver": { "insert": "via /api/inventory/receive", "scope": "own site" },
+ "restrictive": ["receiver is not an approver of the order"]
+}
1
⏺ Write(docs/inventory-rules.md)
+| Right | Needed by |
+| receiver: insert inv_goods_receipt | Session 4 step: purchasing journey |
+| inv_importer: insert, OPENING through the posting function | Sessions 5 and 6; NOLOGIN at cutover |
2
⏺ Pull request #57 adds 8 roles, 5 routes, 6 screens and 6 restrictive rules. No role has delete or a direct write on the ledger or balances.
The matrix grows by rows; the separation rules are written as restrictive rules.
  1. The separation of duties is a rule the database applies, not a screen that hides a button.
  2. Each right says which later step needs it, so a missing cell shows now, not halfway through Session 5.

Check it worked

The pull request adds the eight roles, five routes and six screens; no cell grants delete or a direct write on the ledger or balances; the planner and receiver have read it.

If it goes wrong

The receiver says they also release held stock today

That is a finding, not a right to add. Releasing a hold is the planner's (or quality's) decision; write it in docs/inventory-map.md as a change in how the plant works and tell the quality lead.

Claude Code wrote rights by folder (everything under /inventory/planning)

Say: Write rights by what the action does (approve, receive, release, post), not by where the screen lives. We hit this: an operator account could delete a whole site because the role check only looked inside the admin folder.

Step 7

Session 3: Generate the access rules, and prove the duties are apart

25 minutes

Why

A right written in the matrix only protects anything once it is a row-level security policy and a route rule, and only stays protected if a test tries the refused cell on every change. Generating them, never hand-writing them, means the rules and the matrix cannot drift apart.

Do this

Paste into Claude Code
On the branch inventory/matrix:
1. Run node scripts/gen-policies.mjs to generate the row-level security migration for the new inventory rows, and node scripts/gen-routes.mjs to regenerate lib/access/routes.ts, as Session 9 does. Do not edit the generated files by hand.
2. Add supabase/tests/inventory-access.test.sql generated from the matrix: for every inventory cell, one test that the allowed role can do it and one that a refused role cannot (a refused read returns zero rows). Plus, explicitly:
   - the approver of an order is refused a goods receipt against it;
   - receiver and stock_user get an error on a direct update of inv_inventory_balance;
   - an approver cannot give the second approval step after giving the first;
   - a user of another site sees zero inventory rows;
   - an update by a role whose read rule does not cover the changed row is checked by reading the row back, not by the response.
3. For each new test, show it fails with its rule removed, then passes with the rule back.
Push, wait for every check on the pull request to finish, and tell me the counts in plain words. Never loosen a test to make it pass: if one fails, explain why and wait.

You will see recreated screen

claude — acme-platform
⏺ Bash(node scripts/gen-policies.mjs)
⎿ wrote supabase/migrations/20261103101500_policies_inventory.sql (61 policies, 6 restrictive)
⏺ Bash(npx supabase test db)
⎿ inventory-access.test.sql .. ok 128/128
⏺ Shown red first: with the rule 'receiver is not an approver of the order' removed, test 'approver cannot receive' fails; with it back, it passes.1
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 3m12s clamps pass 1m05s
⏺ Pull request #57 is green: 61 policies generated from the matrix, 128 access tests, 64 of them refusals. The approver of an order cannot receive against it.2
Generated, not hand-written; and each test shown red before green.
  1. A test that has never been seen to fail may never fail. We had checks green for weeks while the thing they guarded was broken.
  2. Read the refusal count. Half the tests prove someone is kept out.

Check it worked

Pull request Inventory roles is green; the summary names the separation test; owner two approves and you merge; the deploy workflow applies the policies to acme-platform-prod.

If it goes wrong

A button says Saved but nothing changed

In Postgres an update only finds rows the role can read, and the changed row must still pass the read rule. We hit this in three modules. Say: For each role that updates rows in this table, check its read rule covers the row before and after the change, and make the test read the row back.

A check named for a list fails, not for your code

Some checks compare a generated list with the code. We hit this: a fix was held up because the route list was stale. 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.

Claude Code suggests relaxing a refusal test because it is "too strict"

Say no. Standing rule: never edit, skip or loosen a test to get to green. If a refusal is wrong, the matrix is wrong: change the matrix row, with the planner, and regenerate.

Step 8

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

30 minutes

Why

Receivers and stock users work on a phone on the floor; planners, buyers and approvers at a desk. Building the screens on the Foundation surfaces, behind the route guard that refuses everything not in lib/access/routes.ts, means a new screen is invisible to everyone until the matrix says otherwise.

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). Then, on a new branch inventory/screens, using the operator surface (Session 12) and the desk and manager surfaces (Session 13):

- /inventory/receive (phone): open order lines for my site; large targets; enter lot and quantity; return to vendor.
- /inventory/stock (phone): issue, transfer, place a hold, count.
- /inventory/approvals: requisitions and orders waiting for me, with approve and reject.
- /inventory/purchasing: supplier prices, orders, change need_by, invoice match.
- /inventory/planning: plans, MRP runs, planned orders and the exception queue.
- /inventory/board: three read-only tiles: on hand by status, open exceptions by age, open purchase orders.

Every screen and every /api/inventory/ route is listed in lib/access/routes.ts (generated) and refused by proxy.ts for everyone else. The server takes the user from the session, never from anything the page sends. No screen shows a number that is not stored: an empty table shows "No data".

Add screen tests: each screen at 360 and 390 px wide (no sideways scroll, 44 px targets, 16 px fields, 15 px text), each screen and route signed out lands on sign-in, and each role sees only its screens. Push, open a pull request titled "Inventory screens", wait for every check and the Vercel preview, and tell me the preview address.

You will see recreated screen

acme-platform-git-inventory-screens-acme-ops.vercel.app/inventory/receive
Receive · Cleveland
PO-000001 · Supplier OneLine 1 · A-100 · 20 ordered · 0 received · due in 7 days1
LotLOT-A-003
Quantity20
Inspection required
Receive2
Return to vendor
The receive screen on a phone, on the preview with the made-up seed.
  1. Only orders that are approved or later, for your site, appear here.
  2. One large button per action: it works with gloves on.

You will see recreated screen

Terminal
✓ /inventory/receive signed out → /sign-in
✓ /api/inventory/post signed out → 401
✓ /api/inventory/report.pdf signed out → 4011
48 passed
The screen tests that refuse signed-out visits.
  1. A path ending in .pdf or .md is still checked. We hit a gate that skipped every dotted path.

Check it worked

Pull request Inventory screens is green, the preview shows each screen at phone width, and a signed-out visit to any inventory screen or route lands on sign-in.

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.

A route under /api/ answers signed out

We found 376 of 449 route handlers in a prior build with no sign-in check. Say: Add the route to lib/access/routes.ts through the matrix and regenerate; never add a check inside the route alone.

Every receipt is recorded as made by the same person

The page sent the user and the server trusted it. We hit this. Say: Take the user from the signed-in session on the server and ignore any user the page sends; add a test with two users.

The preview answers 401 before any sign-in page

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

Knowledge check

Who may receive goods against an order you approved?

Knowledge check

Why is the access test shown failing with its rule removed before it is trusted?

References

  1. Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
  2. NIST SP 800-53 Rev. 5: security and privacy controls (AC-5, separation of duties). https://csrc.nist.gov/pubs/sp/800/53/r5/upd1/final
  3. PostgreSQL documentation: Row security policies (permissive and restrictive). https://www.postgresql.org/docs/current/ddl-rowsecurity.html
  4. Next.js Docs: proxy.ts (request middleware). https://nextjs.org/docs/app/api-reference/file-conventions/proxy

Chapter 3 · Session 4

Post, buy, receive, promise and plan

Session 4 builds the workflow end to end: the one route that moves stock, purchasing from requisition to receipt and invoice match, the answer to "how many can we promise", the nightly proof that the ledger and balances agree, and the MRP engine checked against numbers you can work by hand.

30 min5 stepsAbout 90 minutesThe worked MRP example

By the end of this chapter you can

  • Have Claude Code build the posting route and prove a reversal and a race for the last unit.
  • Run a purchase from requisition to match yourself, as each role, and see the refusals.
  • Check available-to-promise and an MRP run against a hand calculation.
The posting routeA caller reaches the inventory-post route. In one database transaction it locks balance rows, takes the next transaction number, inserts the ledger row and changes the balance rows. It refuses a negative balance, a type the caller may not post, and a repeated client_ref. Phone or deskstock, receiver, plannerONE DATABASE TRANSACTION · inventory-post1 · Lock the balance rows (select for update)2 · Take the next txn_no3 · Insert the ledger row4 · Change the balance rowsLedger rowappend-onlyBalance rowsderived, never editedRefused: a negative balance, a type the caller may not post, a repeated client_ref
One route posts. In one database transaction it locks the balance rows it touches, numbers the transaction, inserts the ledger row and changes the balances. The lock makes two phones that try to take the last unit wait in turn [4].
Step 9

Session 4: The one route that moves stock, with reversals

20 minutes

Why

Every quantity change in the module goes through this route, so it carries the rules: no negative balance, only the types each role may post, and one result per request even when a phone retries. Testing two posts for the last unit at once proves the lock; without it, two people can take the same last unit and the balance goes wrong silently.

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 inventory/post, write the route /api/inventory/post (inventory-post) as a security definer database function called by the route. In one database transaction it:
- locks the balance rows it touches (select ... for update);
- takes the next txn_no from core_number_sequence (inv_txn);
- inserts the ledger row, then changes the balance rows;
- refuses a result below zero, a txn_type the caller's role may not post (from docs/matrix.json), and a repeated ext client_ref (returns the first result instead);
- for a reversal: copies the original with from and to swapped, reason REVERSAL, reversal_of_id set; refuses a second reversal and the reversal of a reversal; if a status_change moved a whole lot, also sets the lot's status.

Tests (Vitest and pgTAP):
- two posts for the last unit at the same time: exactly one succeeds;
- a reversal restores the balance and leaves the original row unchanged;
- an SQL update of the ledger is refused by the database;
- the same client_ref twice changes the stock once.
Show each test failing with its rule removed, then passing. Push, open a pull request titled "Inventory posting", wait for every check and report in plain words.

You will see recreated screen

claude — acme-platform
⏺ Write(tests/inventory-post.test.ts)
+const [a, b] = await Promise.allSettled([post(issue1), post(issue1b)]);
+expect([a, b].filter((r) => r.status === 'fulfilled')).toHaveLength(1);
1
⏺ Shown red first: without 'for update', both posts succeeded and the balance went to -1 (refused by the check, so one post failed with a database error instead of a clear message). With the lock, the second waits, then gets 'Not enough stock: 0 available'.2
⏺ Bash(gh pr checks --watch)
⎿ ci pass 2m10s schema pass 3m01s clamps pass 58s
⏺ Pull request #59 is green: 14 tests, 6 of them refusals.
The race test: two phones, one last unit.
  1. Two requests at once, from the same starting stock: exactly one may win.
  2. The red run shows what the lock prevents. Ask for it every time a test is added.

Check it worked

Pull request Inventory posting is green and the summary says the race test and the reversal test were each shown failing first.

If it goes wrong

The app says Saved, and a minute later the movement is not there

Two saves read the same starting copy and the second overwrote the first. We hit this on the platform. The lock above and the client_ref prevent it here; if it appears on another screen, say: Find where this screen reads, changes and writes back; update only the affected row, refusing a stale save.

Claude Code says "all tests pass" but did not show the red run

Say: Remove the lock, run the race test, show me it fails with its exit code; restore it and show it passes. We recorded a run that printed npm: not found and, minutes later, a report of 1,326 tests passing.

From need to order to match

The purchase order statusesEight statuses in two rows: draft, pending approval, approved, sent, acknowledged, partially received, received and closed, with who moves each on. Cancelled is a status too. draftbuyer builds itpending_approvalapprovers askedapprovedsignature recordedsentbuyer sends itacknowledgedsupplier confirmspartially_receivedreceiver books goodsreceivedall lines inclosedbuyer closes itcancelled is also a status; nothing is ever deleted.
The purchase order statuses. Amber steps are approvals; green steps are receipts. Each step is a different person's job. Nothing is deleted; cancelled is a status.

A requisition (inv_purchase_requisition) is a request to buy. The buyer turns an approved one into a purchase order, taking supplier, price and lead time from the preferred inv_supplier_item row; the server computes the total, never the browser. At or under your approval amount an order needs one approval step; over it, two steps by two different people. Each approver confirms their password and an e-signature stores a hash of the order, so a later change shows. A goods receipt posts a po_receipt; inspection sends the goods to quarantine until the planner releases them; a return is a vendor_return, never an edit.

Matching the invoiceA purchase order line for 100 at 2.5000 is 250.0000. Goods received total 90, worth 225.0000. An invoice for 100 units sets qty_variance; a corrected invoice for 90 units and 225.0000 sets matched, and matched rows are exported to accounting. PO lineordered 100 of B-100price 2.5000 each100 × 2.5000 = 250.0000Goods receiptsqty_received 9060 − 10 returned + 4090 × 2.5000 = 225.0000Supplier invoiceINV-DEMO-1 · 100 unitsinvoiced 250.0000qty_varianceInvoice quantity 100 is above received 90The buyer asks for a corrected invoicematchedCorrected invoice: 90 units, 225.0000Quantity and price agree: exported to accountingThe module hands match status and amounts over. Accounting posts them,pays the supplier and keeps the general ledger.
Three-way match. 100 ordered, 90 received after a return. An invoice for 100 sets qty_variance; a corrected invoice for 90 sets matched, and matched rows go to accounting as a CSV file.
Step 10

Session 4: Purchasing routes, and the B-100 journey as a test

25 minutes

Why

The purchasing routes carry the money rules: totals computed on the server, the approval threshold, receipts that cannot exceed the order, and a match that pays only for what arrived. Writing the whole B-100 journey as one test, with the numbers you will check by hand, means every later change proves the journey still works.

Do this

Paste into Claude Code
On a new branch inventory/purchasing, using /api/inventory/post for every movement:

1. /api/inventory/po: numbers inv_req and inv_po from core_number_sequence; builds an order from an approved requisition with the preferred inv_supplier_item (supplier, price, lead time), links the line and sets the requisition to converted; computes every line amount and the total on the server and ignores any price or total a browser sends; reads the approval amount from config/po-approval.json (set it to 200.0000); on submit inserts the pending core_approval rows (one step at or under the amount, two steps by two different approvers over it) and sets pending_approval.
2. Approval: the approver re-enters their password; a core_e_signature (meaning approved) stores a hash of the header and lines; the last one goes in approved_signature_id and the order becomes approved.
3. /api/inventory/receive: creates the core_lot (quarantine if inspection_required, else released), inserts inv_goods_receipt numbered from inv_receipt, posts a po_receipt with the line price as unit_cost, raises qty_received and sets partially_received or received; refuses a receipt above the ordered quantity; a return posts a vendor_return and lowers qty_received.
4. /api/inventory/match: compares invoice quantity with qty_received and the amount with quantity times line price; writes inv_invoice_match (qty_variance, price_variance or matched) and updates qty_invoiced; an export of matched rows as CSV sets exported_at. No general ledger.

Then one end-to-end test with the seed, as separate users per role: requisition for 100 of B-100, approved; order total 250.0000 needing two approvers; the buyer, the first approver giving step two, and an approver receiving are each refused; receive 60 into LOT-B-001, return 10 (RETURN-DEFECT), receive 40 into LOT-B-002 with inspection, planner releases it (90 on hand); hold 20 of LOT-B-002 (inv_available falls by 20); issue 30 from LOT-B-001; count LOT-B-001 as 19 (COUNT-VAR, difference 1): expect 59 on hand, 39 available; invoice for 100 gives qty_variance, corrected to 90 (225.0000) gives matched.

Push, open a pull request titled "Inventory purchasing", wait for every check and report the journey's numbers in plain words.

You will see recreated screen

claude — acme-platform
☒ /api/inventory/po with server totals and threshold 200.0000
☒ approval with e-signature
☒ /api/inventory/receive and returns
☒ /api/inventory/match and CSV export
☒ B-100 journey test
⏺ Bash(gh pr checks --watch)
⎿ ci pass 3m44s schema pass 3m20s
⏺ Pull request #61 is green. Journey: total 250.0000, two approvals by different people; three refusals as expected; after receipts, return, hold, issue and count: 59 on hand, 39 available while 20 are held; invoice for 100 → qty_variance, corrected to 90 at 225.0000 → matched.1
The journey test reads like the paragraph above, with every number checked.
  1. Every number here is one you can check by hand from the seed. If any differs, ask which step produced it.

Check it worked

Pull request Inventory purchasing is green and the summary gives 250.0000, the three refusals, 59 on hand, 39 available, and matched at 225.0000.

If it goes wrong

A "Send to supplier" button reports success

The module does not email suppliers; a button that claims it did is a stand-in pretending. We hit this: "Send all" marked every recipient sent and no email left the building. Say: Remove the send action. The buyer sends the order the way the business does today and sets the status to sent.

The order total changes when the page is edited in the browser

The route trusted a price from the page. Say: Compute every amount on the server from inv_supplier_item and ignore any price or total in the request. Add a test that sends a wrong total and expects the server's.

An approval works, but the approver could also receive

The restrictive rule from Step 7 is missing from the route. Say: The receive route must check the restrictive rule too, not only row-level security; add a test. A route running with more rights must apply the rule itself.

Step 11

Session 4: Walk one purchase yourself on the preview, as each role

20 minutes

Why

A test proves the rules; walking them yourself proves the screens make sense to the people who will use them. Doing it with owner two, each signed in as yourselves with different roles on the made-up development data, shows the refusals the way a buyer or approver will meet them.

Do this

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/editor

The development project's Table Editor. In your memberships table give yourself stock_user, buyer and receiver for cle, and owner two approver. Development project only, never acme-platform-prod.

Open the preview Vercel posted on pull request Inventory purchasing (previews read the development project, never production). Then, each in your own browser:

WhoDoesExpect
You (stock user)Raise a requisition: 40 of B-100, need by in 14 days; submitStatus submitted
Owner two (approver)Approve the requisition in /inventory/approvalsApproved
You (buyer)Create the order from it, submitTotal 100.0000 from Supplier One's price; one approval step
Owner two (approver)Approve, re-entering the passwordApproved, with a signature
Owner twoOpen /inventory/receiveThe order is not there, or Receive is refused
You (receiver)Receive 40 into a new lotOn hand for B-100 goes up by 40

You will see recreated screen

acme-platform-git-inventory-purchasing-acme-ops.vercel.app/inventory/approvals
Waiting for you
1
OrderSupplierTotalSteps
PO-000002Supplier One100.00001 of 1
Password••••••••
Approve and sign2
Reject
The approvals queue, as owner two sees it.
  1. The total was computed by the server from the price list, not typed.
  2. Signing re-asks the password, so a signature is a deliberate act, and the hash of the order is stored with it.

You will see recreated screen

acme-platform-git-inventory-purchasing-acme-ops.vercel.app/inventory/receive
Owner two, trying to receive the order they approved.
  1. A plain refusal that says why. The database refuses it too, whatever the screen shows.

Check it worked

You and owner two completed the six rows; the approver's receipt was refused with a message that says why; B-100's on hand rose by 40 on the development project.

Fastest path

Do this on a call with owner two sharing screens: the whole walk takes fifteen minutes, against a day of emails.

If it goes wrong

The preview shows no orders at all

Check the preview reads the development project: in Vercel, Project Settings, Environment Variables, the Preview values must be the development project's. If it reads production, stop and fix that first: previews must never touch real data.

Changing your role has no effect until you sign out

The session keeps your roles until it refreshes. Sign out and in again after each change in the memberships table.

How many can we promise, and are the books straight?

Available to promise (ATP) is the quantity you can promise a customer for a date: available stock, plus open order lines due by then, minus confirmed sales order lines due by then. Held and quarantined stock is never in it. For the seed's A-100: 40 today (50 available less the sales order of 10) and 60 once the order of 20 arrives; the 10 on hold are left out.

Stock by lot and statusA bar to scale of 59 units on hand for item B-100: 19 available in lot LOT-B-001, 20 available in lot LOT-B-002 and 20 on hold in lot LOT-B-002. Available is 39 while the hold stands. Item B-100 at STOCK, drawn to scale (one unit = 12 px)LOT-B-001 · available 19LOT-B-002 · available 20LOT-B-002 · hold 20On hand: 59Available: 39, the only stock an order or allocation can useHeld: 20Quarantine, allocated, in_transit, consigned and damaged are not available either.When the planner releases the hold, the 20 return to available: 59 on hand and 59 available.
B-100 at STOCK after the hold. 59 on hand, 39 available while 20 are held, drawn to scale. Releasing the hold returns the 20.
Step 12

Session 4: Available to promise, and the daily ledger check

20 minutes

Why

The specification's first promise is that balances recomputed from the ledger equal the stored balances on every row. A script that checks it in CI and every day on production turns that promise into an alarm; it reads with its own read-only identity, whose password only a person ever handles.

Do this

Paste into Claude Code
On a new branch inventory/atp-check:
1. A database function atp(item, date): inv_available for the item, plus open purchase order lines (qty less qty_received) with need_by on or before the date, minus open confirmed sales order lines (qty less qty_shipped) with requested_at on or before the date. Nothing from planned orders; nothing on hold or in quarantine. pgTAP test on the seed for A-100: 40 today and 60 in 7 days; after releasing LOT-A-002, 50 and 70.
2. scripts/check-balances.mjs: compares inv_balance_from_ledger with inv_inventory_balance on every row and exits 1 naming any row that differs. It reads the connection from the environment variable BALANCE_CHECK_DB_URL, checks it is present and shaped like a Postgres address, and if not, says which and never prints it.
3. A migration creating the role balance_check with no login and select only on inv_inventory_transaction, inv_inventory_balance and inv_balance_from_ledger. No password anywhere in the repository.
4. .github/workflows/balance-check.yml: on every pull request against the CI database, and daily at 05:17 UTC against production using the secret BALANCE_CHECK_DB_URL.
5. Add BALANCE_CHECK_DB_URL to docs/KEYS.md (name, what it unlocks, where it lives, who holds it; never the value).
Show check-balances failing on a hand-edited balance in the CI database, then passing. Push, open a pull request titled "Inventory ATP and ledger check", wait for every check and report.

After it merges and the deploy has applied the migration, a person gives balance_check a password. In the production SQL editor, with a password generated by the password manager (saved there first as Supabase: acme-platform-prod balance_check):

Open

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

Run: alter role balance_check with login password '<paste from the password manager>'; then close the tab without saving the query.

Open

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

New repository secret: name BALANCE_CHECK_DB_URL; value the Session pooler connection string from Supabase's Connect panel, with the user changed to balance_check.abcdefghijklmnopqrst and the password from the password manager. Paste the value only, no NAME=.

Key or secretWhat it unlocksWhere it livesWho holds itNever
BALANCE_CHECK_DB_URLRead-only access to the ledger and balances on acme-platform-prodGitHub Actions secret; password in the password managerpat@acme.com, sam@acme.comNever in a file, a chat or Claude Code; never given write rights

You will see recreated screen

claude — acme-platform
⏺ Bash(node scripts/check-balances.mjs)
⎿ OK: 6 balance rows equal the ledger
⏺ Bash(psql ... -c "update inv_inventory_balance set qty_on_hand = 49 ..." && node scripts/check-balances.mjs; echo exit=$?)
⎿ DIFFERENT: A-100 LOT-A-001 STOCK available: ledger 50, balance 49 exit=1
1
⏺ Write(docs/KEYS.md)
+| BALANCE_CHECK_DB_URL | read-only ledger check on production | GitHub Actions secret | owners | never in a file |
2
⏺ Pull request #63 is green. ATP for A-100: 40 today, 60 in 7 days; the held 10 are excluded. The ledger check fails on a hand-edited balance (exit 1) and passes on the seed.
The check proven both ways, and the key registered by name only.
  1. Exit 1 and the row named: the check can say no. A check that only ever says yes is no check.
  2. The key's name, not its value, goes in the register.

You will see recreated screen

github.com/acme-ops/acme-platform/actions/workflows/balance-check.yml
balance-check
1
RunEventResult
#1workflow_dispatch✓ 0 differences
The daily run on GitHub after you add the secret.
  1. Run it once by hand (Run workflow) to prove the secret works, rather than waiting for tomorrow.

Check it worked

ATP gives 40 and 60 for A-100 in the test; the balance-check workflow, run once by hand on production, is green; docs/KEYS.md lists BALANCE_CHECK_DB_URL by name.

If it goes wrong

The workflow says BALANCE_CHECK_DB_URL is missing or not a Postgres address

The secret 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 an empty string. Open the secret again and paste only the connection string.

password authentication failed for user balance_check

Check the user part is balance_check.abcdefghijklmnopqrst for the pooler, and that the alter role was run on acme-platform-prod, not the development project. Copy the password again from the password manager.

The check passes even with a hand-edited balance

Then it can never fail. Say: The check passed against a planted difference. Find why it cannot see it, fix it, and show me the planted difference failing.

MRP, worked by hand

MRP reads each item's row in inv_item_site_plan [1]. It explodes demand for made items through the bill of materials, nets it against available stock and scheduled receipts, keeps projected stock at or above safety stock, rounds each shortfall with the lot-sizing rule, offsets the lead time to get a release date, and pegs each planned order to the demands it covers.

lot_size_ruleIn plain words
l4l (lot for lot)Order exactly what is short
foq (fixed order quantity)Order a fixed amount; a bigger shortfall rounds up to whole multiples
eoq (economic order quantity)The amount that balances ordering cost against holding cost
poq (period order quantity)Enough to cover a set number of periods
min_maxWhen stock falls to the minimum, order up to the maximum
From orders to gross requirementsA sales order for 10 of A-100 and three firmed P-100 orders of 15, 20 and 12. Each P-100 needs 2 of A-100, so the gross requirements for A-100 are 10, 30, 40 and 24 on 2 November, 16 November, 30 November and 14 December. Sales order10 of A-100 · 2026-11-02taken as isNeed 10 of A-100on 11-02P-100 order: 15released 2026-11-16× 2 per P-100Need 30 of A-100on 11-16P-100 order: 20released 2026-11-30× 2 per P-100Need 40 of A-100on 11-30P-100 order: 12released 2026-12-14× 2 per P-100Need 24 of A-100on 12-14inv_bom_simple: parent P-100, component A-100, qty_per 2.Gross requirements for A-100: 10, 30, 40 and 24.
From orders to gross requirements. A sales order for 10 of A-100 and three firmed orders for P-100; each P-100 needs 2 of A-100, taken at its release date.
Projected stock of A-100A step line to scale. Available stock is 50. It falls to 40 after the sales order, rises to 60 when the open purchase order arrives, falls to 30 on 16 November, then to minus 10 on 30 November, which is 20 below the safety stock of 10, answered by a planned order of 40. On 14 December it falls to 6, 4 below safety stock, answered by a second planned order of 40. A-100 projected on-hand stock (units), from 2026-11-020204060safety 10−10 order+20 due−30−40−24short 20 → +40 plannedshort 4 → +40 planned11-0211-0911-1611-3012-14
Projected stock of A-100, to scale. On 30 November it would fall to −10, 20 short of safety stock 10, so MRP plans a buy of 40; on 14 December it would fall to 6, 4 short, so a second buy of 40.
DateGross needScheduled receiptPlanned receiptProjected stock after
2026-11-021040
2026-11-092060
2026-11-163030
2026-11-30404030
2026-12-14244046
Lead-time offset and peggingTwo bars to scale. Planned buy 1 is released on 16 November and due on 30 November, a lead time of 14 days. Planned buy 2 is released on 30 November and due on 14 December. Each planned order stores pegging, the demand it covers. 11-1611-3012-14lead time 14 daysBuy 1 · 40lead time 14 daysBuy 2 · 40Planned buy 1: 40due 11-30 · release 11-16peggingDemand it coversP-100 order of 20 (released 11-30) needs 40 of A-100Planned buy 2: 40due 12-14 · release 11-30peggingDemand it coversP-100 order of 12 (released 12-14) needs 24 of A-100
Release dates and pegging. A buy due 30 November is released 16 November; one due 14 December is released 30 November. Each stores the demands it covers.
Step 13

Session 4: The MRP engine, proven against the worked example

30 minutes

Why

Planners only act on MRP if its answers are right and explained. Fixing the worked example as a test, with the dates of the table above, proves the engine nets, sizes, offsets and pegs exactly as the hand calculation does, and that a firmed order is never planned twice. This is the specification's second promise.

Do this

Paste into Claude Code
On a new branch inventory/mrp, write /api/inventory/mrp (planner only) for one site, a start date and a horizon in days:
- inserts inv_mrp_run numbered from inv_mrp_run: running, then complete (failed on an error);
- explodes inv_bom_simple one level: component demand = qty_per x each firmed or released parent planned order at its release date, plus confirmed sales order lines at requested_at;
- nets each item: start from inv_available (held and quarantined excluded), add open purchase order lines at need_by, firmed planned orders, and released planned orders whose requisition is not yet on an order line; take demands in date order; keep projected stock >= safety_stock; round each shortfall up to whole fixed_qty; release_at = due_at - lead_time_days; insert inv_planned_order (planned) with pegging listing the demands it covers;
- writes inv_mrp_exception: expedite when an open order arrives after its stock is needed, no_source for a bought item with no preferred supplier, below_safety_stock; the message text names the demand;
- never changes a firmed or released order.

Hand-worked example in tests/fixtures/inventory-mrp.json with FIXED dates (week 1 starts Monday 2026-11-02) and the same A-100 and P-100 data as the seed, never seed rows; the test supabase/tests/inventory-mrp.test.sql loads that fixture into an empty database: run from 2026-11-02 for 56 days and expect exactly two planned buys of 40: due 2026-11-30 released 2026-11-16, due 2026-12-14 released 2026-11-30, with pegging. Move the open order's need_by to 2026-12-07: same two buys and one expedite naming the 40 needed on 2026-11-30. Firm the first, release it to a requisition, run again: nothing planned twice.

Write the planned-quantity rule in docs/mrp-rules.md. Push, open a pull request titled "Inventory MRP", wait for every check and report the planned orders in plain words.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase test db)
⎿ inventory-mrp.test.sql .. ok 9/9
⏺ Run on the worked example: buy 40 A-100 due 2026-11-30, release 2026-11-16 (pegged: P-100 order released 11-30, 40). Buy 40 due 2026-12-14, release 2026-11-30 (pegged: P-100 released 12-14, 24). With the open order moved to 12-07: same two buys, plus 'expedite PO-000001 line 1: 40 needed 2026-11-30 for P-100'. After firming: nothing planned twice.1
⏺ Bash(gh pr checks --watch)
⎿ ci pass · schema pass · clamps pass
The engine's answer, in the same words as the hand calculation.
  1. Compare each line with the table above: quantity, due date, release date and the demand it is pegged to.

You will see recreated screen

acme-platform-git-inventory-mrp-acme-ops.vercel.app/inventory/planning
PlansMRP runsPlanned ordersExceptions
1
ItemTypeMessageStatus
A-100expeditePO-000001 line 1 arrives 12-07; 40 needed 11-30 for P-100open
Mark actioned
Ignore
The planner's exception queue on the preview.
  1. The message says which demand it protects. Without that, the planner cannot judge it.

Check it worked

Pull request Inventory MRP is green; the summary gives the two buys of 40 with the dates in the table, the expedite message naming its demand, and nothing planned twice.

If it goes wrong

A buy is planned on top of an order the planner already firmed

The engine did not count firmed or released orders as supply. Say: Count firmed planned orders, and released ones not yet on an order line, as supply. Add the test.

The first run on real data gives hundreds of messages

Most come from missing data: a lead time of zero, no preferred supplier. Sort them by type, fix the data in the plans, run again. Session 5 does this on the rehearsal copy.

Claude Code proposes changing the test's expected numbers to match its output

Say no. The hand calculation is the specification. Say: Show me, row by row, where your projection differs from the table, and fix the engine.

Knowledge check

Projected stock of A-100 would fall to −10 with safety stock 10 and a fixed order quantity of 40. What does MRP plan?

Knowledge check

Twenty units of a lot of 40 are on hold. What does ATP count?

References

  1. ASCM: CPIM certification (MRP, lot sizing and safety stock). https://www.ascm.org/learning-development/certifications-credentials/cpim/
  2. X12: ANSI X12 transaction sets (850, 855, 856, 810). https://x12.org/
  3. OASIS: Universal Business Language (UBL) 2.1. https://docs.oasis-open.org/ubl/UBL-2.1.html
  4. PostgreSQL documentation: explicit locking (SELECT FOR UPDATE). https://www.postgresql.org/docs/current/explicit-locking.html
  5. GitHub Docs: Using secrets in GitHub Actions. https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions

Chapter 4 · Sessions 5–6

Move the real records in, and switch the old tool off

Session 5 builds the import and rehearses the whole move on the development project with a copy IT has approved in writing, removed the same day. Session 6 does it for real, through the import workflow a person starts from main: the counted opening balance into production, a week side by side, the cutover, the import login set to NOLOGIN, and the old subscription cancelled with the saving written as arithmetic.

25 min3 stepsA week side by sideEnds with the module gate

By the end of this chapter you can

  • Load items, plans, open orders and a counted opening balance through the import workflow and the posting function, safe to run twice.
  • Reconcile quantity and value to the old valuation report, first on the development project, then on production.
  • Run side by side, cut over, set the import login to NOLOGIN and record the saving from real invoices.
From the old tool to cutoverEight steps in order: export from the old tool, dry run, blind count, post the opening balance, reconcile quantity and value, run side by side, cut over, and cancel last, once the final export is stored. Exportfrom the old tool's pagesDry runcounts and rejects onlyBlind countsystem quantity hiddenOpening balanceadjustment, reason OPENINGReconcilequantity and value agreeSide by sideone week or moreCut overold tool read-onlyCancel lastafter final export storedA difference you cannot explain means you are not ready to cut over.
From the old tool to cutover. Session 5 rehearses export, dry run and reconciliation on the development project with an approved copy; Session 6 does the count, the opening balance and the rest on production.

The opening balance

Stock goes in as one dated opening transaction per item, lot and location: an adjustment with reason OPENING at the cut-off time, posted through the same route as every other movement, never written into a balance. A counted quantity is better than the old tool's number. The key (item, lot, location; add status if a lot has two statuses in one place) is the client reference, so a second run adds nothing. IAS 2 and ASC 330 govern how inventory is valued; your accountant owns the method, and the module records the unit cost from the old valuation report [1].

MethodHow an issue is costed
StandardOne fixed cost per item; what was paid above or below it is a variance
Moving averageThe running average of what is on hand, recalculated at each receipt
FIFO layersEach receipt is a layer; issues use the oldest layer first
One issue, costed by layersTwo receipts of 40 units, at 1.5000 and then 1.8000, drawn to scale. A first-in first-out issue of 50 takes 40 from the first layer and 10 from the second, costing 78.0000 and leaving 30 worth 54.0000. A moving average of 1.6500 would cost the issue at 82.5000. Received40 × 1.5000 first40 × 1.8000 secondIssued 5040 × 1.5000 = 60.000010 × 1.8000 = 18.0000FIFO cost of the issue: 78.0000Left on hand30 × 1.8000 = 54.0000Moving average: (40 × 1.5000 + 40 × 1.8000) ÷ 80 = 1.6500, so the same issue costs 82.5000 and 49.5000 stays.Standard cost: one fixed value per item; what was paid above or below it is shown as a variance.
One issue, costed by layers. Made-up receipts of 40 at 1.5000 and 40 at 1.8000. Issuing 50 costs 78.0000 by FIFO and 82.5000 by moving average.
Step 14

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

40 minutes

Why

Loading real records is where a replacement usually goes wrong: a mapped unit is off by a thousand, a supplier appears twice, the stock doubles on a second run. An import that dry-runs by default, posts stock only through the posting function, refuses a file nobody approved, and is rehearsed end to end on the development project finds those faults where they cost nothing.

Do this

Paste into Claude Code
Read docs/matrix.json and the M12 section of docs/spine-map.md. On a new branch inventory/import:
1. docs/import-map.md: how each old export column maps to ours (items, units, locations, suppliers, lots, plans, bills of materials, supplier items, open purchase order lines, open sales order lines, on-hand by item, lot, location and status).
2. scripts/import/inventory-import.mjs: reads one export file (a zip of the export files), connects as the database login inv_importer with the password from the environment variable INV_IMPORTER_PASSWORD (never printed), and runs as a DRY RUN unless --apply is given, printing counts per file, rows it would load, and every row it cannot match with the reason. It loads in order: units, items, suppliers, locations, lots (status released, quarantine or on_hold as the old tool shows), plans, bills of materials, supplier items, open orders (old numbers kept, ext imported true, original prices, status as the old tool shows; no approval needed because the old tool approved them). It only inserts, with on conflict do nothing; it never reads back, updates or deletes. Opening stock goes through the posting function as one adjustment per item, lot and location, reason OPENING, ref_type opening_balance, txn_at the cut-off, unit_cost from the valuation export, with client_ref = item + lot + location (+ status where a lot has two). A second run adds nothing. Every row carries ext.import_run.
3. supabase/snippets/inventory-remove-run.sql, for the development project only: removes only the rows whose ext.import_run is the run id I type in (opening stock by reversals, never by editing the ledger). I paste it into that project's SQL editor myself.
4. .github/workflows/import-inventory.yml: started by hand only (workflow_dispatch) and refusing to run from any branch but main; inputs target (development or production) and apply (false is a dry run). It downloads the export from the private Storage bucket imports of the target and computes its sha256; it refuses unless that sha256 and the expected row count per file are recorded for that target in docs/imports/inventory-approved.md on main; it runs the script with INV_IMPORTER_PASSWORD_DEV or INV_IMPORTER_PASSWORD_PROD; it fails on any count mismatch (each file must equal its approved count, and loaded plus rejected must equal the rows in the file); it writes the counts to the job summary and uploads the report as an artifact. No GitHub environment with required reviewers. Never print a secret.
5. Tests with ten MADE-UP rows per file only, never real data: counts agree; a second run adds nothing; an unmatched unit is reported, not guessed; the opening rows reconcile to a made-up valuation total; an export whose sha256 is not approved is refused; a count that differs from the approved counts fails the run.
Push, open a pull request titled "Inventory import", wait for every check and report. Do not run the workflow.

Then ask IT to approve, in writing, a copy of the exports for the rehearsal (what it holds: supplier prices and customer orders, redacted where it holds personal or pay data; where it goes: acme-platform-dev only; when it is removed: the end of this session). Zip the copy and work out its fingerprint (on Windows, Get-FileHash in PowerShell):

Terminal (Mac)
shasum -a 256 ~/private/inventory-export.zip
Paste into Claude Code, after filling the <...> parts
On a new branch inventory/import-approval-dev, create docs/imports/inventory-approved.md with a section "development rehearsal": export file inventory-export.zip, sha256 <paste the value>, expected rows per file <paste them>, IT's written approval for one rehearsal on acme-platform-dev given on <date> by <role>, redacted where it held personal or pay data, and a line "removed on:" left empty. Open a pull request titled "Inventory: approve rehearsal export".

Owner two approves and you merge. On acme-platform-dev, set the import login's password yourself in the SQL editor (alter role inv_importer login password '…', the value from the password manager), type it as the GitHub secret INV_IMPORTER_PASSWORD_DEV (the value only), and upload the zip to the private bucket imports. Then:

Open

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

Run workflow from main: target development, apply false. Read the summary.

DoExpect
Run with apply false; read the summaryCounts per file equal the approved counts; every unmatched row with its reason
Fix the mapping (docs/import-map.md), never the data; dry run againNothing unmatched, or every reject explained
Run with apply true; then againThe second run adds nothing
Run the reconciliation query Claude Code wroteQuantity and value per item equal the valuation report
The same day: paste the removal snippet with the run id, delete the zip from the bucket and your computer, record the date on "removed on:"IT told it is gone

You will see recreated screen

github.com/acme-ops/acme-platform/actions/workflows/import-inventory.yml
import-inventory · target development · apply false
2
FileApprovedRowsWould loadRejected
items.csv1,2041,2041,2013
on_hand.csv2,3882,3882,3880
open_po_lines.csv1461461460
RowReason
items.csv 377unit 'BX' is not in docs/import-map.md
The dry run on the rehearsal: counts and every reject, nothing written.
  1. It ran only because the file is the approved one, and it wrote nothing.
  2. Counts per file, so you can compare with the old tool's own report row counts; any mismatch fails the run.

Check it worked

The import's pull request is green with made-up rows only; on the rehearsal a second run with apply true added nothing; the reconciliation matched the valuation report; the same day the rows were removed, the file deleted, the date recorded, and IT told.

If it goes wrong

IT will not approve a copy for the development project

Then rehearse with the made-up rows only, and make Session 6's first production run the rehearsal: dry run, read every count with IT watching, then apply. Do not copy real data anywhere IT has not agreed to.

The run refuses: sha256 not approved

The file in the bucket is not the one recorded on main (a re-export changes it). Record the new value through a pull request owner two approves, or upload the approved file.

The second run doubled the stock

The client_ref was not used as the key. Stop; remove the rehearsal with the snippet and say: The second run doubled the opening stock. Make client_ref the item, lot and location key and add the test that a second run adds nothing.

Two old suppliers become one, or one becomes two

A rename that was half done. We hit three names for one demo company live at once. Say: List every supplier that matches another by name or tax number, and let me decide each one in docs/import-map.md.

Step 15

Session 6: Count, load production, and run side by side for a week

60 minutes, then a week

Why

Real records go into production only now, through the import workflow a person starts from main, for an export whose fingerprint and counts were approved in a reviewed pull request, after a rehearsal; never from an upload page, a laptop or an agent. Running the old tool and the module side by side for a week, with the same people entering the same movements in both, shows every difference while the old tool can still answer for it.

Do this

Invite the real planner, buyers, approvers, receivers and stock users with the invitation flow from Session 9. Choose the cut-off and stop movements in the old tool from the start of the count until then. Count the pilot family blind; write differences from the old tool in docs/opening-differences.md. Zip the final exports with the counted quantities, work out the sha256, and add a "production" section to docs/imports/inventory-approved.md (file, sha256, expected rows per file, date) through a pull request; owner two approves and you merge. Set inv_importer's password on production yourself in its SQL editor and type it as the secret INV_IMPORTER_PASSWORD_PROD. Then:

Open

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

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

Open

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

Run workflow from main: target production, apply false. Read the counts against the old tool's report row counts, then run once with apply true.

Paste into Claude Code
Production now holds the pilot family's opening balance. Write docs/reconciliation.md as a table I fill from two sources: the old valuation report (old quantity, unit cost, old value) and the module (counted quantity, new value from the opening transactions, by the query you wrote in Session 5). The rule: new value = old value + (counted - old quantity) x unit cost for every item, and the totals agree. Add a second table for open orders: count of lines and value still to receive, old and new. Do not read any export file or connect to production yourself; give me the query to run in the SQL editor. Open a pull request titled "Inventory reconciliation".
Open

https://github.com/acme-ops/acme-platform/actions/workflows/balance-check.yml

Run the ledger check by hand on production: it must be green.

For the next week, every receipt, issue, hold and count for the pilot family goes into both systems. Each day, compare on-hand and open orders and write each difference and its cause in docs/cutover.md.

You will see recreated screen

github.com/acme-ops/acme-platform/pull/66/files
docs/reconciliation.md
1
ItemOld qtyCountedUnit costOld valueNew value
A-bracket4124101.9200791.0400787.2000
BR-2969614.50001,392.00001,392.0000
The reconciliation, filled in. Every item agrees once the counted difference is applied.
  1. 791.0400 + (410 − 412) × 1.9200 = 787.2000. Every row must work out exactly.
  2. A difference you cannot explain means you are not ready to cut over. It is an error to find, not a rounding to accept.

Check it worked

The run's sha256 matched the approved production entry and every count matched; production holds one OPENING adjustment per item, lot and location counted; the ledger check is green; docs/reconciliation.md agrees to 0.0000 unexplained; docs/cutover.md has a line for each day of the week.

If it goes wrong

The import run on production stopped halfway

Start it again from main: the client_ref makes the second run add only what is missing. Then run the ledger check and compare the counts with the dry run.

The run fails on a count mismatch

Do not edit the approved counts to make it pass. Read the report, find which rows are missing or extra, and record a corrected export through a reviewed pull request.

Reconciliation is out by a small amount on many items

A unit cost was rounded in the export, or the old tool values at a different date. Do not accept it as rounding. Ask Claude Code: For the items that differ, show old value, quantity times unit cost to four places, and the difference; which rule explains each?

A page fails on production with "column does not exist"

A migration did not reach production. We hit this: production fell nine migrations behind main. Open the Actions tab: the deploy and the daily freshness check from Session 11 name the missing migration; fix that run, never by hand.

Step 16

Session 6: Cut over, set the import login to NOLOGIN, and cancel with the saving written

40 minutes

Why

The module is only finished when the old tool is off and nobody can load around the routes any more. Setting inv_importer to NOLOGIN through a reviewed migration, with a test that proves it, closes the one account that could insert records without the normal screens. Cancelling last, with the final export stored, means nothing is lost.

Do this

Count the pilot family blind again and compute accuracy for both systems with the Session 1 tolerance. Take a final export of items, orders, transaction history and the valuation report into company storage, and set the old tool read-only. Then:

Paste into Claude Code
Cutover is done. On a new branch inventory/close-import:
1. A migration that sets inv_importer to NOLOGIN (the deploy workflow applies it to production on merge), a test that inv_importer cannot log in, and in docs/KEYS.md the date it was set to NOLOGIN; its rights stay in docs/matrix.json, so a later import is a reviewed pull request that sets LOGIN again for a day.
2. In docs/cutover.md, add the three promises with the result of each: balances recomputed from the ledger equal stored balances (the balance-check run); a held lot is in inv_inventory_balance but not in inv_available nor ATP (the query); an MRP message names its demand (the planning screen).
3. Add the accuracy of both systems from the final blind count, the cutover date and the rollback plan (who tells the floor, the last old-tool transaction time, where the final export is kept).
4. Update docs/inventory-map.md: mark each tool and spreadsheet replaced or retired, with the date.
Push, open a pull request titled "Inventory cutover", wait for every check and report.

Last: read the vendor's cancellation terms on your own account page, cancel (or write the date the plan ends), and write the saving in docs/cutover.md as arithmetic from the invoice: the old annual cost minus what the module adds to the services you already pay for.

You will see recreated screen

claude — acme-platform
⏺ Write(supabase/migrations/20261130090000_close_inv_importer.sql)
+alter role inv_importer nologin;
1
⏺ Bash(npx supabase test db)
⎿ inventory-access.test.sql .. ok (inv_importer: rolcanlogin false)
⏺ Bash(gh pr checks --watch)
⎿ ci pass · schema pass · clamps pass
⏺ Pull request #70 is green. inv_importer is NOLOGIN once the deploy applies the migration, and docs/KEYS.md records the date. docs/cutover.md records the three promises: ledger check green on 12 runs, the held lot excluded from available and ATP, and the expedite message naming its demand.2
The import login closed by a reviewed migration, and the proof it cannot sign in.
  1. Closing the import login is a change like any other: reviewed, tested, applied by the deploy workflow.
  2. The three promises from the specification, each with its evidence.

Check it worked

Pull request Inventory cutover is merged; inv_importer is NOLOGIN on production; the old tool is read-only with its final export stored; the cancellation (or end date) and the saving are written from the invoice.

If it goes wrong

The module is less accurate than the old tool in the final count

Do not cut over yet. Read each miss with the stock user: late receipts and unrecorded issues are habits, not software. Fix the habit or the screen, count again in a week.

Someone asks to keep the import login open "just in case"

No: an account that writes records around the normal screens is the riskiest thing in the module. Any later load is a new pull request that sets LOGIN for a day, a new approved export in docs/imports/inventory-approved.md, and a migration that sets NOLOGIN again.

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

Knowledge check

The import workflow is run twice on production by mistake. What happens to the opening stock?

Knowledge check

Where are the real records first loaded, and when?

References

  1. IFRS Foundation: IAS 2 Inventories. https://www.ifrs.org/issued-standards/list-of-standards/ias-2-inventories/
  2. ASCM: CPIM certification (inventory, planning and control). https://www.ascm.org/learning-development/certifications-credentials/cpim/
  3. Supabase Docs: Connecting to your database (poolers). https://supabase.com/docs/guides/database/connecting-to-postgres
  4. PostgreSQL documentation: CREATE ROLE. https://www.postgresql.org/docs/current/sql-createrole.html

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. Which of these does the module leave to the accounting system?
2. A quantity on the ledger is always above zero. How does a transaction show direction?
3. What makes the ledger append-only?
4. A balance row is wrong. What does the module do?
5. 20 units of a lot are on hold and 40 are on hand in total. Which statement is right?
6. Why does the posting route lock the balance rows it touches?
7. In gross-to-net for A-100, available stock is 50 and projected stock would fall to −10 with a safety stock of 10. The shortfall is:
8. What does lead-time offsetting produce?
9. Why does each planned order store pegging?
10. Who should approve a purchase order and who should receive against it?
11. Which statement about the opening balance is right?
12. Where do you first try the module's migration and seed?