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.
| Standard | Use in this module |
|---|---|
| ASCM/APICS CPIM body of knowledge | MRP logic, lot-sizing rules, safety stock |
| US GAAP ASC 330 and IAS 2 | How inventory is measured and costed; your accountant owns the method [1] |
| ISA-95 Parts 2 and 5, B2MML | Exchange of schedules, material lots and performance between ERP and MES |
| OAGIS, UBL 2.x, ANSI X12 850, 855, 856, 810 | Purchase 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.
Session 1: Map the old tool from its reports and its bill
40 minutesWhy
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
cd ~/code/acme-platform && git switch main && git pull && claudeOn 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
- Each blank says which report holds the answer, so you are never guessing.
- 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.
Session 1: Count ten locations blind, then choose the pilot
30 minutesWhy
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:
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
- Seven of ten within tolerance is 70%. Write the tolerance next to it, or the number cannot be compared later.
- 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.
| txn_type | What happened |
|---|---|
| po_receipt | Goods arrived from a supplier against a purchase order line |
| production_issue, production_receipt | Material used by production; finished goods booked in |
| transfer_out, transfer_in | Stock left one location and arrived at another |
| adjustment | A quantity corrected, always with a reason code (and the opening balance, reason OPENING) |
| scrap | Stock written off as unusable |
| shipment, customer_return | Goods left for a customer; goods came back |
| vendor_return | Goods sent back to a supplier |
| cycle_count | The difference found by a count |
| status_change | Stock 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.
| Table | Columns: 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_plan | item_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_simple | parent_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_item | supplier_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_requisition | req_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_order | po_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_line | purchase_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_receipt | receipt_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_match | purchase_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_run | run_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_order | mrp_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_exception | mrp_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_order | so_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_line | sales_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 |
Session 2: Check the spine tables the module points at
15 minutesWhy
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
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
- The existing Foundation tables are reused, not copied. Your names will be the ones from your schema plan.
- 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.
Session 2: One prompt: the tables, the append-only ledger and their tests
25 minutesWhy
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
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
- The ledger refuses changes in the database itself, so no screen or import can get round it.
- 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.
Session 2: Seed the worked example, and try it on the development project yourself
20 minutesWhy
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
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.
git fetch && git switch inventory/tables && npx supabase link --project-ref tsrqponmlkjihgfedcbanpx supabase db push --include-seedThat is the first load. After it, reload the made-up rows with npm run seed:dev, never with supabase db reset.
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
- Only the two new files. If it lists anything else, answer n and ask Claude Code why.
- The development project now has the tables and the made-up plant.
You will see recreated screen
| on_hand | available |
|---|---|
| 60.000000 | 50.000000 |
- 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
- IFRS Foundation: IAS 2 Inventories. https://www.ifrs.org/issued-standards/list-of-standards/ias-2-inventories/
- PostgreSQL documentation: constraints. https://www.postgresql.org/docs/current/ddl-constraints.html
- PostgreSQL documentation: trigger functions. https://www.postgresql.org/docs/current/plpgsql-trigger.html
- Supabase Docs: Database migrations. https://supabase.com/docs/guides/deployment/database-migrations
- MRPeasy: features by plan (MRP II, routings, lot tracking, costing). https://www.madesmarter.uk/media/b5fpo5ai/mrpeasy_features_by_plan.pdf
- 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.
| Role | May | May not |
|---|---|---|
| Planner | Plans, bills of materials, MRP runs, planned orders and messages, adjustments, release a hold, reversals | Approve or receive |
| Buyer | Supplier prices, purchase orders while draft, submit, change need_by, invoice match | Approve an order where buyer_id is theirs |
| Approver | Approve or reject requisitions and orders, with an e-signature | Approve what they raised; give both steps; receive |
| Receiver | Receive against approved orders, create the lot, return to vendor | Release a hold; receive an order they approved |
| Stock user | Issue, transfer, scrap, count, place a hold, raise a requisition | Release a hold back to available |
| Board (read-only) | Three tiles: on hand by status, open messages by age, open orders | Anything 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 function | Read, change or delete anything; sign in after cut-over (set to NOLOGIN) |
| balance_check | Read the ledger, the balances and inv_balance_from_ledger | Write anything |
Session 3: Write the roles, routes and separation rules into the matrix
25 minutesWhy
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
cd ~/code/acme-platform && git switch main && git pull && claudeRead 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
- The separation of duties is a rule the database applies, not a screen that hides a button.
- 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.
Session 3: Generate the access rules, and prove the duties are apart
25 minutesWhy
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
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
- 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.
- 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.
Session 3: The six screens, behind default-deny sign-in
30 minutesWhy
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
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
- Only orders that are approved or later, for your site, appear here.
- One large button per action: it works with gloves on.
You will see recreated screen
- 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
- Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
- 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
- PostgreSQL documentation: Row security policies (permissive and restrictive). https://www.postgresql.org/docs/current/ddl-rowsecurity.html
- Next.js Docs: proxy.ts (request middleware). https://nextjs.org/docs/app/api-reference/file-conventions/proxy
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.
Session 4: The one route that moves stock, with reversals
20 minutesWhy
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
cd ~/code/acme-platform && git switch main && git pull && claudeOn 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
- Two requests at once, from the same starting stock: exactly one may win.
- 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
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.
Session 4: Purchasing routes, and the B-100 journey as a test
25 minutesWhy
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
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
- 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.
Session 4: Walk one purchase yourself on the preview, as each role
20 minutesWhy
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
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:
| Who | Does | Expect |
|---|---|---|
| You (stock user) | Raise a requisition: 40 of B-100, need by in 14 days; submit | Status submitted |
| Owner two (approver) | Approve the requisition in /inventory/approvals | Approved |
| You (buyer) | Create the order from it, submit | Total 100.0000 from Supplier One's price; one approval step |
| Owner two (approver) | Approve, re-entering the password | Approved, with a signature |
| Owner two | Open /inventory/receive | The order is not there, or Receive is refused |
| You (receiver) | Receive 40 into a new lot | On hand for B-100 goes up by 40 |
You will see recreated screen
| Order | Supplier | Total | Steps |
|---|---|---|---|
| PO-000002 | Supplier One | 100.0000 | 1 of 1 |
- The total was computed by the server from the price list, not typed.
- 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
- 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.
Session 4: Available to promise, and the daily ledger check
20 minutesWhy
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
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):
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.
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 secret | What it unlocks | Where it lives | Who holds it | Never |
|---|---|---|---|---|
| BALANCE_CHECK_DB_URL | Read-only access to the ledger and balances on acme-platform-prod | GitHub Actions secret; password in the password manager | pat@acme.com, sam@acme.com | Never in a file, a chat or Claude Code; never given write rights |
You will see recreated screen
- Exit 1 and the row named: the check can say no. A check that only ever says yes is no check.
- The key's name, not its value, goes in the register.
You will see recreated screen
| Run | Event | Result |
|---|---|---|
| #1 | workflow_dispatch | ✓ 0 differences |
- 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_rule | In 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_max | When stock falls to the minimum, order up to the maximum |
| Date | Gross need | Scheduled receipt | Planned receipt | Projected stock after |
|---|---|---|---|---|
| 2026-11-02 | 10 | 40 | ||
| 2026-11-09 | 20 | 60 | ||
| 2026-11-16 | 30 | 30 | ||
| 2026-11-30 | 40 | 40 | 30 | |
| 2026-12-14 | 24 | 40 | 46 |
Session 4: The MRP engine, proven against the worked example
30 minutesWhy
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
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
- Compare each line with the table above: quantity, due date, release date and the demand it is pegged to.
You will see recreated screen
| Item | Type | Message | Status |
|---|---|---|---|
| A-100 | expedite | PO-000001 line 1 arrives 12-07; 40 needed 11-30 for P-100 | open |
- 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
- ASCM: CPIM certification (MRP, lot sizing and safety stock). https://www.ascm.org/learning-development/certifications-credentials/cpim/
- X12: ANSI X12 transaction sets (850, 855, 856, 810). https://x12.org/
- OASIS: Universal Business Language (UBL) 2.1. https://docs.oasis-open.org/ubl/UBL-2.1.html
- PostgreSQL documentation: explicit locking (SELECT FOR UPDATE). https://www.postgresql.org/docs/current/explicit-locking.html
- 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.
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].
| Method | How an issue is costed |
|---|---|
| Standard | One fixed cost per item; what was paid above or below it is a variance |
| Moving average | The running average of what is on hand, recalculated at each receipt |
| FIFO layers | Each receipt is a layer; issues use the oldest layer first |
Session 5: The import, rehearsed on the development project with an approved copy
40 minutesWhy
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
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):
shasum -a 256 ~/private/inventory-export.zipOn 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:
https://github.com/acme-ops/acme-platform/actions/workflows/import-inventory.yml
Run workflow from main: target development, apply false. Read the summary.
| Do | Expect |
|---|---|
| Run with apply false; read the summary | Counts per file equal the approved counts; every unmatched row with its reason |
| Fix the mapping (docs/import-map.md), never the data; dry run again | Nothing unmatched, or every reject explained |
| Run with apply true; then again | The second run adds nothing |
| Run the reconciliation query Claude Code wrote | Quantity 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
| File | Approved | Rows | Would load | Rejected |
|---|---|---|---|---|
| items.csv | 1,204 | 1,204 | 1,201 | 3 |
| on_hand.csv | 2,388 | 2,388 | 2,388 | 0 |
| open_po_lines.csv | 146 | 146 | 146 | 0 |
| Row | Reason |
|---|---|
| items.csv 377 | unit 'BX' is not in docs/import-map.md |
- It ran only because the file is the approved one, and it wrote nothing.
- 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.
Session 6: Count, load production, and run side by side for a week
60 minutes, then a weekWhy
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:
https://supabase.com/dashboard/project/abcdefghijklmnopqrst/storage/buckets
Production Storage: upload the zip to the private bucket imports.
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.
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".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
| Item | Old qty | Counted | Unit cost | Old value | New value |
|---|---|---|---|---|---|
| A-bracket | 412 | 410 | 1.9200 | 791.0400 | 787.2000 |
| BR-2 | 96 | 96 | 14.5000 | 1,392.0000 | 1,392.0000 |
- 791.0400 + (410 − 412) × 1.9200 = 787.2000. Every row must work out exactly.
- 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.
Session 6: Cut over, set the import login to NOLOGIN, and cancel with the saving written
40 minutesWhy
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:
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
- Closing the import login is a change like any other: reviewed, tested, applied by the deploy workflow.
- 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.
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
- IFRS Foundation: IAS 2 Inventories. https://www.ifrs.org/issued-standards/list-of-standards/ias-2-inventories/
- ASCM: CPIM certification (inventory, planning and control). https://www.ascm.org/learning-development/certifications-credentials/cpim/
- Supabase Docs: Connecting to your database (poolers). https://supabase.com/docs/guides/database/connecting-to-postgres
- 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
Your result
CivOps AI Academy
Purchasing and Inventory: Ledger, MRP and Purchasing on Your Own Platform
Element M12 complete · Learner
Your LMS records this completion. For the CivOps Foundation certificate, finish the Foundation Course at https://civops.io/learn.