# Stock & warehouses — module spec (generated from modules/inventory/module.yaml)
# A starting vocabulary for phase 2: correct it with the customer, then write ERP_INVENTORY.md.
# START HERE: read dodil://erp/build (the map) first; this spec is a vocabulary, not the method.
# WORKING CODE EXISTS — run `code.init` below (uvx --from git+https://git.dodil.io/dodil/erp-platform.git@v0.9.13 erp-compose init inventory): it composes these bricks; do not rewrite the module.
schema: dodil.module-spec/v1
code:
  start_here: 'START HERE: read dodil://erp/build (the map) first; this spec is a vocabulary, not the method. Then, in the project folder: (1) uvx --from git+https://git.dodil.io/dodil/erp-platform.git@v0.9.13 erp-compose init inventory; (2) SHOW the customer the diagram — `erp-compose process --module inventory --playbook <playbook>` for a brick with playbooks (hr), else `erp-compose bpmn --from ERP_INVENTORY.md --out processes/inventory.bpmn` — and paste its step names, in order with who does each, into your message. The signed artifact is the BPMN: never prose, never "open bpmn.io".'
  status: This module has working, tested code. COMPOSE it; do not rewrite it.
  how: "Run: uvx --from git+https://git.dodil.io/dodil/erp-platform.git@v0.9.13 erp-compose init inventory  (in a fresh folder; no DODIL login needed). It pins the bricks at these tags, installs them, writes compose.yaml, requirements.txt and tests/test_composition.py, and runs the checks. Then configure rows through the bricks' use cases. Write a new brick only for a need no brick covers."
  init: uvx --from git+https://git.dodil.io/dodil/erp-platform.git@v0.9.13 erp-compose init inventory
  repos:
    - name: erp-brick-inventory
      role: brick
      tag: v0.1.2
      clone: git clone --depth 1 --branch v0.1.2 https://git.dodil.io/dodil/erp-brick-inventory.git
    - name: erp-brick-product
      role: brick
      tag: v0.2.2
      clone: git clone --depth 1 --branch v0.2.2 https://git.dodil.io/dodil/erp-brick-product.git
    - name: erp-platform
      role: platform
      tag: v0.9.13
      clone: git clone --depth 1 --branch v0.9.13 https://git.dodil.io/dodil/erp-platform.git
  compose_yaml: |-
    # compose.yaml: what `uvx --from git+https://git.dodil.io/dodil/erp-platform.git@v0.9.13 erp-compose init inventory` writes (for reference; run the command, do not
    # hand-write this). The exact format erp_platform.compose loads; check it: erp-compose check compose.yaml
    name: <customer>-inventory
    version: 0.1.0
    tier: 1
    bricks:
      - { name: inventory, brick: "brick_inventory.application.use_cases:INV", version: 0.1.2 }
      - { name: product, brick: "brick_product.application.use_cases:PRODUCT", version: 0.2.2 }
    # capabilities: omit to let each capability's only provider be used; a capability no brick
    # provides becomes a manual task. Map one only to choose between two providers.
  test_composition_py: |
    """The composition boots, its bricks answer through HTTP together, and a signed-in caller can read each one."""
    import inspect
    import pathlib
    from contextlib import ExitStack

    import anyio
    import httpx
    from sqlalchemy import create_engine
    from erp_platform import compose, seam
    from erp_platform.scenarios import Catalogue
    from erp_platform.scenarios.inprocess import stage

    COMPOSE = pathlib.Path(__file__).resolve().parent.parent / "compose.yaml"


    def test_composition_boots_and_every_brick_answers_a_signed_in_read(tmp_path):
        comp = compose.load(COMPOSE)
        assert compose.check(comp)["problems"] == []
        engine = create_engine(f"sqlite:///{tmp_path / 'bucket.db'}", connect_args={"check_same_thread": False})
        perms = sorted({u.permission for m in comp.members for u in m.brick.use_cases if u.permission})
        me = {"sub": "tester.1", "email": "tester@test", "app_roles": ["tester"], "permissions": perms}

        async def get(app, path):
            async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t") as c:
                return await c.get(path, headers=seam.gateway_headers(me))

        with ExitStack() as st:
            app = stage(Catalogue("t", compose=comp, roles=None), st, lambda name: engine).app
            assert anyio.run(get, app, "/healthz").status_code == 200
            for m in comp.members:
                reads = [u for u in m.brick.use_cases if u.kind == "query" and u.method == "GET" and u.tool
                         and not u.path_params and all(d is not inspect.Parameter.empty for _, _, d in u.inputs)]
                assert reads, f"{m.name}: no plain read use case to call"
                # The first plain read may refuse an empty question (activity's GET /contacts wants a bp_id or an
                # email: 422). A refusal is the use case answering; a 5xx is the composition broken. So: no read
                # may 5xx, and at least one must answer 200.
                answers = []
                for u in reads:
                    r = anyio.run(get, app, f"/{m.name}{u.path}")
                    assert r.status_code < 500, f"{m.name} {u.path}: {r.status_code} {r.text[:200]}"
                    answers.append(f"{u.path} {r.status_code}")
                    if r.status_code == 200:
                        break
                else:
                    raise AssertionError(f"{m.name}: no plain read answered 200 ({', '.join(answers)})")
id: inventory
name: Stock & warehouses
short: Inventory
version: 7
maturity: tested
summary: "Where every item is and how many you have: warehouses and their shelves, goods received from suppliers, picked and delivered to customers, moved between shelves and sites, and counted, with every movement recorded so the quantity on a shelf and the value of the stock always add up, and nobody sells the last unit twice."
decisions:
  - proposed: "v2: stock status is a property of the location (unrestricted, quality, blocked), not of each quant; releasing stock is a transfer between locations"
    status: superseded by v3 (below)
  - proposed: "v3: stock type is part of every stock row (product, location, lot, stock type, owner); a location's status is the default type of what is put there and the only types it accepts (a QC area takes quality only, a normal bin all three); a change of type where the stock stands is a move between types with no value change. Why: a small warehouse cannot always carry a doubtful pallet to a QC area, and SAP's 321 / 343 / 349 change the type without a movement"
    status: for sign-off (SAP full-scope pass)
  - proposed: "v3: valuation is average cost or standard cost, chosen per company by the owner from the first day of a later month; standard prices are dated rows per company and product; a change revalues stock on hand"
    status: for sign-off (SAP full-scope pass)
  - proposed: "v3: replenishment is a rule (reorder point, min / max from product's site data), so it may send purchase requests on its own when the owner sets auto; the default is suggest"
    status: for sign-off (SAP full-scope pass)
  - proposed: "v3: full EWM (warehouse tasks, RF queues, slotting, labour management, yard) is deferred: putaway rules, pick batches, packing and SSCCs cover a warehouse of an SME to mid-market firm"
    status: for sign-off (SAP full-scope pass)
  - proposed: "v2: catch weight and batch-specific units are designed with their columns reserved and stay off until M7"
    status: for sign-off (wave 2)
facets:
  domain: supply-chain
  industries:
    - any
  customer_words:
    - how many do we have in stock
    - which shelf is it on
    - we sold something we didn't have
    - stock take
    - goods in, goods out
    - what is our stock worth
    - batch numbers
    - serial numbers
    - first expiry first out
    - cycle count
    - reorder point
    - stock at the customer
    - consignment stock from the supplier
    - standard cost
    - scrap
  replaces:
    - a stock spreadsheet
    - the stock tab in the accounting package
    - Odoo Inventory
  pillars:
    - sql
  first_module_fit: medium
  depends_on:
    - module: product
      why: every stock row names a product (SKU) and counts it in the product's base unit, converted exactly by the product module
      required: true
    - module: sales-order
      why: deliveries are made against confirmed orders, reserve their lines, and record what left on the order
      required: recommended
    - module: purchasing
      why: receipts are expected from purchase orders and carry their cost
      required: recommended
    - module: gl
      why: stock value and its movements post to the ledger; without it the valuation is exported for the accountant
      required: optional
    - module: business-partner
      why: a receipt names its supplier and a delivery its customer, by bp_id
      required: recommended
  feeds:
    - sales-order
    - purchasing
    - gl
  owns_master_data: []
  references_master_data:
    - product
    - business_partner
actors:
  - id: warehouse_manager
    name: Whoever runs the warehouse (operations lead, the owner in a small firm)
    does: sets up warehouses, zones and bins, putaway rules and pick sequence, decides which products are tracked by lot or serial and how lots are picked, plans transfers, batches deliveries, starts counts (from the cycle count plan) and applies small adjustments, changes stock types and blocks lots, accepts replenishment proposals, reserves stock by hand for a priority order
    sees: every warehouse, location, document and move; quantities and the value of a count's difference
    permissions:
      - inv:stock:read
      - inv:warehouse:write
      - inv:product:write
      - inv:receipt:validate
      - inv:delivery:validate
      - inv:transfer:write
      - inv:count:write
      - inv:adjustment:apply
      - inv:reservation:write
      - inv:move:reverse
      - inv:issue:write
      - inv:stock_type:write
      - inv:replenishment:write
      - inv:settings:write
  - id: stock_operator
    name: The person on the floor (picker, packer, goods-in)
    does: receives goods and returns, inspects returns, puts away, picks, packs and ships deliveries, moves stock between bins, issues stock to a cost centre or scraps it, records what a count found
    sees: products, locations, quantities and the documents of their warehouse; never a cost or a value
    permissions:
      - inv:stock:read
      - inv:receipt:validate
      - inv:delivery:validate
      - inv:transfer:write
      - inv:count:write
      - inv:issue:write
  - id: stock_controller
    name: A second person for large differences (finance controller, the owner)
    does: approves a count adjustment, a goods issue or a scrap whose value is over the threshold, and a transit shortfall written off; never one they counted, submitted or requested
    sees: every count, issue and scrap, its difference and its value
    permissions:
      - inv:stock:read
      - inv:valuation:read
      - inv:adjustment:approve
      - inv:issue:approve
  - id: owner
    name: The owner
    does: sets the controls on the warehouse (negative stock, the approval thresholds, lots and serials, the ledger mode, the valuation method per company, whether replenishment sends on its own, whether expired stock may be picked, the AI step's mode)
    sees: everything
    permissions:
      - inv:stock:read
      - inv:valuation:read
      - inv:settings:controls
  - id: accountant
    name: Finance (bookkeeper, outside accountant)
    does: reads stock value per product and company, the average or standard cost, and the journals posted for each movement; keeps the account map and the standard prices
    sees: quantities, values and postings; changes no stock
    permissions:
      - inv:stock:read
      - inv:valuation:read
      - inv:account_map:write
      - inv:valuation:write
  - id: sales_rep
    name: Sales
    does: asks what is available before promising a date
    sees: available quantities per product and warehouse; never a cost, a value or a bin
    permissions:
      - inv:availability:read
  - id: system
    name: The system
    does: posts the stock move of each receipt line and return purchasing records, takes reservations from sales orders, expects returns from them, answers ATP, derives on hand and availability, appends average or standard cost, posts valuation to the ledger, claims document numbers, classifies ABC and proposes replenishment, suggests a cause for a count difference, imports the Odoo opening stock once
    sees: everything, through its own service account
    permissions:
      - inv:stock:read
      - inv:availability:read
      - inv:receipt:intake
      - inv:reservation:intake
      - inv:return:expect
      - inv:valuation:post
      - inv:number_series:claim
      - inv:count:suggest
      - inv:replenishment:propose
      - inv:abc:classify
      - inv:migration:import
      - inv:migration:read
      - inv:issue:intake
      - inv:standard_price:intake
stories:
  - id: INV-01
    kind: person
    actor: warehouse_manager
    story: As the warehouse manager, I want my sites, zones and bins as a tree, so that every item has an address and a count can cover one aisle.
    given: no warehouse yet; company UK1
    when: I add warehouse WH1 "Leeds" for company UK1, zone WH1/A and bins WH1/A/01 to WH1/A/40
    then: WH1 exists with its stock root WH1 (kind view) and its locations; WH1/A/01 is kind internal, its parent WH1/A; adding a second WH1/A/01 is refused ("WH1/A/01 already exists"); a location's code is fixed once a move names it; the virtual locations SUPPLIER, CUSTOMER, LOSS, TRANSIT and OPENING exist once per company, are not stock (on hand there is never shown as available) and cannot be renamed, archived or counted
    screen: Warehouses
    path:
      process: inventory.warehouse
      choices: {}
    reference: not built
    customer_varies: how many levels (warehouse, zone, bin, or just warehouse); whether bins are used at all
  - id: INV-02
    kind: person
    actor: warehouse_manager
    story: As the warehouse manager, I want to archive a bin we no longer use, so that nobody puts stock there, without losing its history.
    given: bin WH1/A/40 with 3 units of COLA-075, and bin WH1/A/39 empty
    when: I archive both
    then: 'WH1/A/39 is archived and no new move may name it; WH1/A/40 is refused ("WH1/A/40 holds 3 C62 of COLA-075: move it first"); every past move naming either still reads the same'
    screen: Warehouses
    reference: not built
  - id: INV-03
    kind: person
    actor: warehouse_manager
    story: As the warehouse manager, I want to say which products we keep in stock and which are tracked by batch or serial number, so that we only count what we hold and can trace a recall.
    given: products COLA-075 (kind goods), HOST-M (kind service) and DRILL-500 (goods); lots and serials turned on by the owner
    when: I set DRILL-500 to tracking serial and COLA-075 to tracking lot
    then: 'each is recorded from today; HOST-M is refused ("HOST-M is a service: services are not stocked"); changing the tracking of a product with stock on hand is refused, naming the quantity and where it is; with lots and serials off (the default) the tracking choice is not offered'
    screen: Stock
    reference: "not built: the product brick has kind goods | service and no tracking field, so tracking is inventory's own row per product"
    customer_varies: whether any product is tracked at all
  - id: INV-04
    kind: person
    actor: stock_operator
    story: As someone on the floor, I want to see how many of a product are where, and how many are already promised, so that I pick from the right bin and do not promise stock twice.
    given: "COLA-075, base unit LTR: WH1/A/01 holds 36 LTR, WH1/A/02 holds 9 LTR; a confirmed order reserves 18 LTR at WH1"
    when: I look COLA-075 up, or scan its pack GTIN
    then: "on hand 45 LTR at WH1 (by bin: 36 and 9), reserved 18, available 27; each shown also in the product's sales unit (60 bottles on hand) by the product's exact conversion; a sales rep asking sees only available 27 per warehouse, no bins and no value; the answer is derived from the moves at the moment it is asked"
    screen: Stock
    path:
      process: inventory.stock
      choices: {}
    reference: not built
  - id: INV-05
    kind: person
    actor: stock_operator
    story: As goods-in, I want to receive what a supplier delivered against what we expected, so that stock, the purchase order and the books agree.
    given: purchase order PO-0101 line 1 still expects 10 PK24 of COLA-075 (PK24 = 24 bottles = 18 LTR) at 21.60 a pack, as purchasing's GET /purchase-orders/PO-0101/expected answers; tolerance 0%
    when: I scan 8 PK24 into WH1/A/01 against delivery note DN-881 and submit
    then: "the scanner records the receipt through purchasing (POST /purchase-orders/PO-0101/receipts, INV-21); purchasing posts the line back (POST /receipts, move_ref pur:<receipt_id>:1, INV-20) and a done receipt numbered WH1/IN/00001 holds one move SUPPLIER -> WH1/A/01 of 144 LTR (8 PK24, numerator 18 / denominator 1, kept beside it), valued 172.80; purchasing shows 2 PK24 outstanding on line 1; scanning 11 PK24 is refused before purchasing is called (\"11 is more than the 10 expected: the tolerance is 0%\"); submitting DN-881 twice records one receipt; the receipt's posting date is today or earlier and falls in an open period, never in the future (a future date is refused 422 with the reason, as is a date in a closed period; the default is today)"
    screen: Receipts
    path:
      process: inventory.receipt
      choices: {}
    reference: not built
    customer_varies: the over-receipt tolerance; whether a receipt is one step (into a bin) or two (goods-in, then put away)
  - id: INV-06
    kind: person
    actor: stock_operator
    story: As goods-in, I want to record the batch or serial numbers as I receive tracked products, so that a recall can name the customers who got them.
    given: DRILL-500 tracked by serial; COLA-075 tracked by lot; an order still expecting 2 DRILL-500 and 1 PK24 of COLA-075
    when: I scan serials SN-1 and SN-2 and lot L-2611 and submit
    then: two moves of 1 C62 each, one per serial, and one move of 18 LTR with lot L-2611; submitting without a serial on each unit is refused (before purchasing is called) ("2 DRILL-500 need 2 serial numbers, 1 given"); a serial already in stock is refused ("SN-1 is already on hand at WH1/A/03")
    screen: Receipts
    reference: not built
  - id: INV-07
    kind: person
    actor: stock_operator
    story: As a picker, I want to pick and ship what a confirmed order needs, so that the customer gets it and the order knows it was delivered.
    given: "sales order SO-2026-0012 line 1: 48 C62 (bottles) of COLA-075 (0.75 LTR each) reserved at WH1; WH1/A/01 holds 36 LTR"
    when: I create the delivery from the order, pick 24 bottles (18 LTR) from WH1/A/01 and validate
    then: a done delivery WH1/OUT/00001 with a move WH1/A/01 -> CUSTOMER of 18 LTR (24 C62) valued at the average cost; the reservation drops by 18 LTR; the sales order records a delivery of 24 on line 1 with delivery_ref inv:WH1/OUT/00001; the remaining 24 stay on a back-order delivery for the same order; picking from a bin that does not hold it is refused naming what the bin holds
    screen: Deliveries
    path:
      process: inventory.delivery
      choices: {}
    reference: "not built: sales-order's record_delivery route exists and refuses more than ordered, a future date and a date before confirmation"
  - id: INV-08
    kind: person
    actor: stock_operator
    story: As a picker, I want the system to stop two of us shipping the last unit, so that we never deliver what we no longer have.
    given: WH1/A/03 holds one DRILL-500; two deliveries for two orders name it, neither reserved (one order came in by phone); negative stock is not allowed
    when: two pickers validate at the same moment
    then: 'exactly one succeeds; the other is refused ("WH1/A/03 holds 0 DRILL-500 now: another delivery took it") and nothing of it is written, neither the move nor the call to the sales order; on hand never shows -1'
    screen: Deliveries
    reference: not built
  - id: INV-09
    kind: person
    actor: warehouse_manager
    story: As the warehouse manager, I want to move stock between bins or between sites, so that the system says where things really are.
    given: WH1/A/01 holds 36 LTR of COLA-075; a second warehouse WH2 of the same company
    when: I move 18 LTR to WH1/B/07, and ship 9 LTR to WH2
    then: "the first is one done transfer WH1/INT/00001 (WH1/A/01 -> WH1/B/07), no value changes; the second is a transfer in two steps: shipped WH1/A/01 -> TRANSIT now, received TRANSIT -> WH2/A/01 when it arrives, the 9 LTR counted in transit until then and in neither warehouse's available; a transfer to a warehouse of another company is refused (\"WH9 belongs to company DE1: an inter-company move is a sale and a purchase\")"
    screen: Transfers
    path:
      process: inventory.transfer
      choices: {}
    reference: not built
  - id: INV-10
    kind: person
    actor: stock_operator
    story: As whoever counts, I want to record what is actually on the shelves, so that the system matches reality.
    given: a count started by the warehouse manager on WH1/A at 08:00; the moves say WH1/A/01 holds 36 LTR of COLA-075; at 09:00 a picker ships 9 LTR from WH1/A/01
    when: at 10:00 I record 24 LTR counted at WH1/A/01, and submit the count
    then: "the difference is computed against what the moves said at the moment the line was counted (27 LTR), not at the start: -3 LTR, valued at the average cost; nothing changes on hand until the count is applied; counting a product into a bin it was never moved to is allowed (a found item); a counted quantity above 10^12 or with more decimals than the unit allows is refused with the reason (422), never an error"
    screen: Counts
    path:
      process: inventory.stock_count
      choices: {}
    reference: not built
  - id: INV-11
    kind: person
    actor: warehouse_manager
    story: As the warehouse manager, I want small count differences applied at once and large ones checked by a second person, so that shrinkage is visible and nobody writes off stock alone.
    given: approval threshold 500.00 GBP (the sum of the absolute value differences across the lines) and a per-line limit 200.00 GBP; count C-14 with two lines worth -42.10 and +30.00; count C-15 worth -1,250.00; count C-16 with three lines worth -250.00, -20.00 and +20.00
    when: I apply C-14, and submit C-15 and C-16
    then: 'C-14 applies (sum 72.10, no line at 200.00); C-16 waits for approval although its sum 290.00 is under 500.00, because one line is at or above the per-line limit; one adjustment move per line, between the bin and LOSS, and the loss posted to the ledger; C-15 waits for approval; a stock controller who is neither the counter nor the submitter (compared by email AND by sign-in subject, so a second account of the same person is refused) approves it and it applies; the submitter approving is refused ("you submitted C-15: a second person approves")'
    screen: Counts
    path:
      process: inventory.stock_count
      choices:
        Gateway_count_value: over_threshold
    reference: not built
    customer_varies: the threshold, and whether every count needs a second person
  - id: INV-12
    kind: person
    actor: stock_controller
    story: As the second person, I want to see what a count found and what it is worth before I approve it, so that I approve a loss knowingly.
    given: count C-15 submitted with 6 lines, value -1,250.00, and the AI's suggested causes for two of them
    when: I open it
    then: each line shows expected (at its counted moment), counted, difference and value, and any suggestion marked as a suggestion; I approve, or reject with a reason (the count returns to the warehouse manager to recount); I cannot change a counted quantity
    screen: Counts
    reference: not built
  - id: INV-13
    kind: person
    actor: warehouse_manager
    story: As the warehouse manager, I want to hold stock for an important order, or release it, so that the right customer gets the last units.
    given: 27 LTR of COLA-075 available at WH1; order SO-2026-0014 asks for 36 LTR and is reserved 27, short 9
    when: I release 9 LTR from SO-2026-0012 and reserve them for SO-2026-0014
    then: SO-2026-0014 is fully reserved; SO-2026-0012 is short 9 and shows it; both changes are appended with who and why; reserving more than available is refused, naming what is available
    screen: Deliveries
    reference: not built
  - id: INV-14
    kind: person
    actor: stock_operator
    story: As goods-in, I want to take back what a customer returns against its RMA and inspect it, so that the stock, the return order and the credit follow what actually came back.
    given: delivery WH1/OUT/00001 of 24 bottles of COLA-075 on SO-2026-0012 line 1, valued 21.60; sales-order authorised RMA RE-2026-0001 for 6 bottles (POST /expected-returns, v3)
    when: the customer returns 6 bottles; I receive them, inspect them (4 good, 1 damaged by us, 1 damaged by the customer) and submit; another parcel arrives with no RMA
    then: a return receipt WH1/RET/00001 with a move CUSTOMER -> WH1/QC of 4.5 LTR in stock type quality, valued at the cost those bottles left at (5.40), not today's average; the returns order records 6 received (record_delivery on RE-2026-0001 with source inventory, delivery_ref inv:WH1/RET/00001); the inspection moves 3 LTR to WH1/A/01 unrestricted (no value change), scraps 0.75 LTR (INV-38) and sends 0.75 LTR back to the customer at the value it came in, and reports 5 accepted and 1 rejected to sales-order (POST /sales-orders/RE-2026-0001/return-inspections, once); the parcel with no open RMA is refused ("no open RMA of 7311 names COLA-075"); receiving more than the RMA expects, or a serial never delivered to that customer, is refused
    screen: Receipts
    reference: "not built: v3 receives against sales-order v5's returns order (RMA); the v2 negative correction on the original order stays only for a hand-recorded delivery mistake before invoicing"
  - id: INV-15
    kind: person
    actor: warehouse_manager
    story: As the warehouse manager, I want to correct a move recorded by mistake without editing it, so that the history stays true.
    given: transfer WH1/INT/00003 moved 18 LTR to WH1/B/07 instead of WH1/B/08
    when: I reverse it with reason "wrong bin" and record the right transfer
    then: "a reversing move WH1/B/07 -> WH1/A/01 of 18 LTR names the original; the original is unchanged and marked reversed; reversing it twice is refused; a delivery or receipt is never reversed this way: a delivery is undone by a return (INV-14), a receipt by a return to the supplier (known gap)"
    screen: Stock
    reference: not built
  - id: INV-16
    kind: person
    actor: accountant
    story: As finance, I want stock value per product and company on any date, so that the balance sheet and the stock agree.
    given: "COLA-075 at company UK1: received 144 LTR at 1.2000 a litre, then 72 LTR at 1.3500, then 90 LTR delivered"
    when: I ask the valuation for today and for the day before the second receipt
    then: today 126 LTR, average 1.2500, value 157.50 (216 LTR worth 270.00, less 90 LTR at 1.2500 = 112.50); the earlier day 144 LTR, 172.80; each figure lists the moves and journals behind it; the total equals the sum of the moves' values exactly, and the stock account's balance in the ledger is shown beside it with any difference named
    screen: Valuation
    path:
      process: inventory.valuation
      choices: {}
    reference: not built
  - id: INV-17
    kind: person
    actor: owner
    story: As the owner, I want to decide whether stock may go negative, so that a shipment is never blocked by a late receipt if I accept that risk, and never goes out unseen if I do not.
    given: negative stock not allowed (the default); WH1/A/02 holds 9 LTR
    when: a picker validates 12 LTR from it; then I allow negative stock for WH2 only and a picker does the same there
    then: at WH1 refused ("WH1/A/02 holds 9 LTR, 12 asked"); at WH2 allowed and the bin shows -3 LTR, flagged on the Stock screen until a receipt or a count clears it; the change is recorded from today with who set it; only inv:settings:controls changes it
    screen: Settings
    reference: not built
  - id: INV-34
    kind: person
    actor: stock_operator
    story: As whoever counts and picks, I want to work in the packs we actually handle, so that I count five cases and six loose bottles instead of working out litres.
    given: COLA-075, base LTR, warehouse unit PK24 (= 18 LTR), sales unit C62 (= 0.75 LTR); WH1/A/01 holds 94.5 LTR; an order line of 48 C62 is reserved
    when: I look the bin up, count it as 5 PK24 plus 6 C62, and open the pick list for the order
    then: "the bin shows 5 PK24 and 6 C62 (94.5 LTR): the warehouse unit first, the rest in the sales unit, and in the base unit where neither divides it exactly; the count line holds two entries (5 PK24, 6 C62), each with its unit's conversion, and counted 94.5 LTR; the pick list proposes 2 PK24 for the 48 C62; an entry in a unit the product does not have, or with more decimals than the unit allows, is refused with the reason; with no warehouse unit set the base unit is used and said so"
    screen: Counts
    path:
      process: inventory.stock_count
      choices: {}
    reference: SAP WM unit of measure (MLGN-LVSME) and counting in alternative units (MI04 entry in any unit of entry); Odoo counts in the product's unit only
    customer_varies: which unit each product is handled in (case, layer, pallet)
  - id: INV-35
    kind: person
    actor: stock_operator
    story: As whoever ships and receives, I want each delivery and receipt to show its weight and volume, so that I can book the carrier and check a delivery against the supplier's note.
    given: PK24 of COLA-075 at gross 19.2 / net 18.0 KGM and 0.027 MTQ; the bottle at gross 0.79 / net 0.75 KGM with no volume (product PRD-28)
    when: a delivery of 3 PK24 and 6 C62 is created, and a receipt of 8 PK24 is posted
    then: each line copies its unit's measures when it is written; GET /documents/{document_id}/shipping answers the delivery's gross 62.34 KGM, net 58.5 KGM and volume 0.081 MTQ with "volume unknown for 1 of 2 lines", and the receipt's gross 153.6 KGM; measures in other units are converted through unit_conversion (GRM, LBR) exactly; a measure changed on the product later (a new unit, PRD-34) never changes a document already written; with delivery_needs_weights on, validating a delivery with a line of unknown weight is refused naming the line
    screen: Deliveries
    path:
      process: inventory.delivery
      choices: {}
    reference: SAP delivery header gross / net weight and volume (LIKP-BTGEW, NTGEW, VOLUM) from MARM per item; Odoo delivery weight from product weight
    customer_varies: whether weights must be known before a delivery leaves (pallet freight, parcel carriers)
  - id: INV-36
    kind: person
    actor: warehouse_manager
    story: As the warehouse manager, I want goods in quality inspection or set aside as damaged to be counted and valued but never sold, so that nobody ships stock we have not released.
    given: location WH1/QC with stock status quality and WH1/DAMAGED with status blocked; 8 PK24 of COLA-075 are received into WH1/QC
    when: an order asks availability, a picker tries WH1/QC, and I release 6 PK24 to WH1/A/01 and move 2 PK24 to WH1/DAMAGED
    then: "on hand at WH1 counts the 144 LTR, available counts none of it until released; WH1/QC cannot be reserved or picked from (\"WH1/QC is in quality inspection: release it first\"); the release is a transfer WH1/QC -> WH1/A/01 of 108 LTR with no value change, and the 36 LTR at WH1/DAMAGED stay on hand, valued and unavailable until a count writes them off to LOSS or a return sends them to the supplier; changing a location's status while it holds stock is refused (move the stock first)"
    screen: Warehouses
    path:
      process: inventory.transfer
      choices: {}
    reference: SAP stock types unrestricted / quality inspection / blocked and transfer postings between them (movement types 321, 343, 344, 349); Odoo multi-step receipts through a quality location
    customer_varies: whether goods are inspected on arrival; whether damaged goods are kept apart
    note: "v3: the location's status is now the default type and the limit; the type is on each stock row (INV-55), so the same result is reached here by moving the goods, and where they stand by a type change"
  - id: INV-37
    kind: person
    actor: stock_operator
    story: As someone in the workshop or the office, I want to take stock out for our own use and charge it to a cost centre, so that consumables leave the shelf and their cost lands where it was spent.
    given: GLOVES (type RAW, stocked) base unit C62, issue unit BX100 (a box of 100, product PRD-29); WH1/A/05 holds 20 BX100; average cost 0.0800 a glove; cost centre MAINT; issue approval threshold 500.00
    when: I issue 3 BX100 from WH1/A/05 to cost centre MAINT, then try 2 BX100 to cost centre NOPE, then the warehouse manager reverses the first with reason "wrong cost centre"
    then: a goods issue WH1/GI/00001 with one move WH1/A/05 -> UK1:CONSUMPTION of 300 C62 (3 BX100, the issue unit proposed and its conversion kept), valued 24.00 at the average, and a journal consumption 24.00 debit with cost centre MAINT on the line / stock_valuation 24.00 credit; NOPE is refused (gate cost_centre_valid, the ledger's answer); the reversal is a move UK1:CONSUMPTION -> WH1/A/05 of 300 C62 naming the original, valued at the original's 24.00, and a reversing journal; reversing twice is refused; an issue whose value is at or above 500.00 waits for a stock controller who is not the requester (email AND sign-in subject)
    screen: Issues
    path:
      process: inventory.goods_issue
      choices: {}
    reference: SAP goods issue to cost centre (MIGO / MB1A movement type 201, reversal 202), unit of issue MARC-AUSME; Odoo has no consumption document (an inventory adjustment to a virtual location)
    customer_varies: whether stock is used internally at all (workshops, maintenance, offices)
  - id: INV-38
    kind: person
    actor: stock_operator
    story: As someone on the floor, I want to scrap damaged or expired stock with a reason, so that it leaves the books as a loss we can see, not as a count difference.
    given: WH1/DAMAGED (stock type blocked) holds 36 LTR of COLA-075 lot L-2611; scrap reasons DAMAGED, EXPIRED, QUALITY
    when: I scrap 36 LTR of L-2611 with reason DAMAGED, and then try to scrap 9 LTR more from it
    then: a goods issue WH1/GI/00002 purpose scrap with a move WH1/DAMAGED -> UK1:LOSS of 36 LTR valued at the average, and a journal inventory_scrap debit / stock_valuation credit naming the reason; the second is refused ("WH1/DAMAGED holds 0 LTR of L-2611"); a scrap at or above the threshold waits for a second person; scrapping is never a count adjustment, so the loss report separates shrinkage (counts) from scrap (reasons)
    screen: Issues
    path:
      process: inventory.goods_issue
      choices: {}
    reference: SAP scrapping (movement type 551 from unrestricted, 553 from quality, 555 from blocked; reversal 552) with reason for movement; Odoo stock.scrap
  - id: INV-39
    kind: person
    actor: stock_operator
    story: As a picker, I want the pick list to tell me which batch to take, first-expiring first, so that nothing expires on the shelf and no customer gets stock too close to its date.
    given: COLA-075 removal strategy FEFO at WH1; lots L-2611 (expires 2026-12-01, 18 LTR in WH1/A/01), L-2612 (expires 2027-02-01, 36 LTR in WH1/A/02), L-2601 (expired 2026-10-15, 9 LTR in WH1/A/03); 7311 requires 60 days of remaining shelf life; today 2026-11-02
    when: a delivery of 24 C62 (18 LTR) for 7311 is picked, and a picker scans L-2611 instead of the proposed lot
    then: "the pick list proposes L-2612 from WH1/A/02 (L-2611 has only 29 days left, under 7311's 60; L-2601 is expired and is never proposed or available); scanning L-2611 is refused (gate shelf_life, \"L-2611 expires 2026-12-01: 7311 needs 60 days\"); a warehouse manager may allow it with a reason, recorded; for a product with FIFO the oldest received lot is proposed; an expired lot is excluded from availability and ATP from its expiry date and is listed for scrapping"
    screen: Deliveries
    path:
      process: inventory.delivery
      choices: {}
    reference: SAP batch determination with sort by shelf-life expiration date (FEFO) and minimum remaining shelf life (MARA-MHDRZ, customer-specific in batch search strategies); EWM removal strategies FIFO / FEFO; Odoo removal strategies FIFO / FEFO
    customer_varies: whether stock expires; the minimum shelf life each customer accepts
  - id: INV-40
    kind: person
    actor: stock_operator
    story: As whoever handles serial-numbered goods, I want every serial followed from receipt to the customer and back, so that warranty, theft and recall questions have an answer.
    given: DRILL-500 tracked by serial; SN-1 received into WH1/A/03, SN-2 into WH1/A/04
    when: SN-1 is delivered to 7311 on WH1/OUT/00007; 7311 returns SN-2 against RE-2026-0002; a count finds SN-1 on a shelf; a transfer is scanned without a serial
    then: 'GET /serials/DRILL-500/SN-1 answers its history: received (supplier, receipt, date), moved, delivered to 7311 on WH1/OUT/00007; the return of SN-2 is refused ("SN-2 was never delivered to 7311"); the count line for SN-1 is refused as a found item ("SN-1 left on WH1/OUT/00007: record a return first"); the transfer without a serial is refused; a serial is on hand in at most one place with quantity 1, and a delivered serial is on hand nowhere'
    screen: Stock
    path:
      process: inventory.stock
      choices: {}
    reference: SAP serial number management (serial number profile, IQ09 serial history, equipment); Odoo stock.lot of serial tracking with traceability
  - id: INV-41
    kind: person
    actor: warehouse_manager
    story: As the warehouse manager, I want to find every customer who received a batch, so that a recall reaches the right people the same day.
    given: "lot L-2611 of COLA-075 received on R-7 from supplier 9100: 144 LTR; delivered 54 LTR to 7311 and 36 LTR to 8420; 36 LTR scrapped; 18 LTR in WH1/A/01"
    when: I ask where L-2611 is and where it went, and block it
    then: "GET /lots/COLA-075/L-2611/trace answers: from supplier 9100 on R-7; to 7311 (54 LTR, WH1/OUT/00003 and /00009) and 8420 (36 LTR, WH1/OUT/00005); scrapped 36; on hand 18 at WH1/A/01; nothing unaccounted; blocking it changes its stock type to blocked wherever it is (a transfer posting, no movement), so it is never reserved, picked or promised until released"
    screen: Stock
    path:
      process: inventory.stock
      choices: {}
    reference: SAP batch where-used list (MB56) and batch status restricted / unrestricted; Odoo lot traceability report
  - id: INV-43
    kind: person
    actor: warehouse_manager
    story: As the warehouse manager, I want the system to tell me what to count this week, more often for what matters, so that a cycle count replaces the annual shutdown.
    given: "ABC classes at WH1 (INV-42): COLA-075 A, SCREW-M4 B, GLOVES C; frequencies A 12 per year, B 4, C 1; COLA-075 last counted 2026-09-25, SCREW-M4 2026-08-01, GLOVES 2026-01-10"
    when: I open the cycle count plan on 2026-11-02 and start counts from it
    then: the plan lists COLA-075 (due 2026-10-25, overdue) and SCREW-M4 (due 2026-11-01), not GLOVES (due 2027-01-10); starting from the plan makes one count per product over every bin that holds it (scope product, not a subtree); each line counts as in INV-10 at its counted moment, so nothing need stop moving; applying a count sets the product's last counted date; a count of a full subtree (the annual count) is still possible
    screen: Counts
    path:
      process: inventory.stock_count
      choices: {}
    reference: "SAP cycle counting (MIBC: cycle counting indicator A / B / C with intervals per plant, MICN batch input), physical inventory without posting block; Odoo inventory frequency per location (annual inventory day, cyclic counting per location)"
    customer_varies: the classes' thresholds and frequencies; whether an annual count is still wanted
  - id: INV-44
    kind: person
    actor: warehouse_manager
    story: As whoever replenishes, I want the system to propose what to buy or move when stock runs low, rounded to how we really order, so that we reorder on time without counting shelves.
    given: "product site WH1 for COLA-075 (PRD-37): min_max, reorder point 360 LTR, max 1 440 LTR, safety stock 90, buy, purchase unit PK24 (18 LTR), rounding profile PALLET-LAYER; WH2 transfer from WH1, reorder point 72, lot size fixed 144 LTR; replenishment_mode suggest"
    when: the nightly run on 2026-11-02 finds WH1 projected 300 LTR (on hand unrestricted 360 + 0 expected - 60 reserved) and WH2 projected 54 LTR; I accept the WH1 proposal and dismiss nothing; the run is repeated
    then: "WH1: a proposal to buy up to the max, 1 140 LTR (1 440 - 300) = 63.33 PK24, 64 whole packs, rounded by GET /products/COLA-075/round-proposal to 60 PK24 (64 is 80% of a pallet, under 90%; the 4 packs over 6 layers are 40% of a layer, under 50%), so 1 080 LTR and a projected 1 380 LTR, recorded with the site row's valid_from and every figure it used; WH2: a proposal to transfer 144 LTR from WH1; accepting the first sends one purchase request to purchasing (INV-54); the WH2 proposal becomes a draft transfer; the repeat writes nothing more; in auto mode the owner's control sends them without a person (a rule, not an AI step); a proposal never sees stock in quality or blocked status or on consignment at a customer"
    screen: Replenishment
    path:
      process: inventory.replenishment
      choices: {}
    reference: SAP consumption-based planning (MRP type VB reorder point, V1 with forecast, HB replenish to maximum; MD01 / MD03; planned order or purchase requisition; stock transport requisition for special procurement 40); Odoo reordering rules min / max and the replenishment report
    customer_varies: which products are planned; whether proposals are sent automatically
  - id: INV-46
    kind: person
    actor: stock_operator
    story: As goods-in, I want stock the supplier still owns kept apart in the books but usable on the shelf, so that we pay for it only when we take it.
    given: supplier 9100 keeps consignment stock of SCREW-M4 with us; purchasing's consignment order PO-0150 expects 5 000 C62; consignment price 2.4500 per 100
    when: 5 000 C62 are received into WH1/B/01 (purchasing posts them with special_stock supplier_consignment); a delivery picks 1 200 C62 of them; then 300 C62 are moved into our own stock
    then: the receipt is a move SUPPLIER -> WH1/B/01 with owner 9100, valued 0.00 (not ours) and no journal; on hand shows 5 000 C62 of which 5 000 consignment of 9100; available counts them (we may use them); the delivery's validation withdraws 1 200 C62 from 9100's ownership first (a move from owner 9100 to owner us at WH1/B/01, valued 29.40 at purchasing's consignment price, journal stock_valuation debit / consignment_liability credit, and purchasing told once through POST /consignment-withdrawals so it settles with the supplier), then delivers them as our stock at the new average; the 300 C62 transfer to own stock is the same withdrawal with no delivery; returning unused consignment stock to 9100 moves it back to SUPPLIER with no value
    screen: Receipts
    path:
      process: inventory.receipt
      choices: {}
    reference: SAP supplier consignment (special stock K, movement types 101 K, 411 K withdrawal, consignment settlement MRKO); Odoo owner on quants (consignment)
    customer_varies: whether any supplier keeps stock with you
  - id: INV-48
    kind: person
    actor: accountant
    story: As finance, I want to value a company's stock at standard cost if the owner chooses, with the difference to what we paid shown as a variance, so that margins are stable and purchasing variances are visible.
    given: company UK1 valuation_method standard from 2026-12-01 (the owner's control, from the first day of a later month); COLA-075 standard price 1.2000 a litre from 2026-12-01; on 2026-11-30 UK1 holds 126 LTR at average 1.2500 (157.50)
    when: the method takes effect on 2026-12-01; on 2026-12-03 144 LTR are received at 1.3500 a litre (194.40 from purchasing); on 2026-12-04 90 LTR are delivered
    then: at 2026-12-01 a revaluation row brings 126 LTR to 151.20 (-6.30, journal stock_valuation credit / revaluation debit); the receipt is valued 172.80 at standard with a price difference of 21.60 (journal stock_valuation 172.80 debit, price_difference 21.60 debit, stock_received_not_billed 194.40 credit); the delivery is valued 108.00 (90 x 1.2000); value_after is always round_half_up(quantity_after x standard, 2) and each move's value is the change in value_after, so the moves sum exactly and zero quantity is zero value; a standard dated today or earlier, or a method switch not on the first of a later month, is refused; another company may stay on average cost
    screen: Valuation
    path:
      process: inventory.valuation
      choices: {}
    reference: SAP price control S (standard price) vs V (moving average) per material and valuation area (MBEW-VPRSV), price differences on goods receipt (PRD), standard price change revaluation (MR21 / CK24, UMB); IAS 2 para 21 (standard cost as a measurement technique when it approximates cost); Odoo costing methods standard / average / FIFO per category
    customer_varies: average or standard per company
  - id: INV-56
    kind: person
    actor: accountant
    story: As finance, I want to change a standard price from a date and see the stock revalued, so that next year's standard applies to what is already on the shelf.
    given: UK1 on standard; COLA-075 standard 1.2000; on hand 180 LTR on 2026-12-31
    when: on 2026-12-20 I set 1.2500 from 2027-01-01; on 2027-01-01 the change takes effect; then I try to set a price from 2026-12-20
    then: a revaluation row on 2027-01-01 of +9.00 (180 x 0.0500) and a journal stock_valuation debit / revaluation credit, journal_id derived (company, product, valid_from), posted once; moves from 2027-01-01 are valued at 1.2500; the back-dated price is refused (starts after today); the price per company is a dated row the accountant writes with inv:valuation:write, never product's cost_amount
    screen: Valuation
    path:
      process: inventory.valuation
      choices: {}
    reference: SAP standard price release (CK24 marking and release, future standard price MBEW-ZKPRS / ZKDAT)
  - id: INV-50
    kind: person
    actor: warehouse_manager
    story: As the warehouse manager, I want goods-in told which bin to put each item away in, so that stock goes where pickers will look and bins are not overfilled.
    given: "receipt steps two (goods-in to WH1/IN, then put away); putaway rules at WH1: 1 COLA-075 fixed bin WH1/A/01 (max 108 LTR), 2 category drinks to the next bin of zone WH1/A with room, 3 everything else addition to existing stock, else zone WH1/C; WH1/A/01 holds 90 LTR"
    when: 8 PK24 (144 LTR) of COLA-075 are received into WH1/IN and put away, and 10 C62 of SCREW-M4
    then: the putaway proposes 18 LTR to WH1/A/01 (its room to 108 LTR) and 126 LTR to WH1/A/02 (the next bin of WH1/A with room by volume, from the units' copied measures); SCREW-M4 goes to the bin that already holds it; each putaway is a transfer WH1/IN -> bin with no value change; the operator may choose another bin, which is recorded with who; a bin over its capacity (quantity, weight or volume) is refused naming the capacity; stock in WH1/IN is on hand but not available until put away
    screen: Receipts
    path:
      process: inventory.transfer
      choices: {}
    reference: SAP WM / stock room management putaway strategies (fixed bin F, open storage C, addition to existing stock I, next empty bin L; bin capacity check); Odoo putaway rules
    customer_varies: whether bins are assigned per product (fixed) or chosen freely; one-step or two-step receipts
  - id: INV-51
    kind: person
    actor: stock_operator
    story: As a picker, I want the morning's deliveries picked together in walking order, so that I walk each aisle once instead of once per order.
    given: deliveries WH1/OUT/00011, /00012 and /00013 ready; locations carry a pick_sequence; delivery steps pick_pack_ship
    when: the warehouse manager batches the three into pick batch WH1/PB/00001 and I pick it
    then: one pick list over all three, sorted by pick_sequence, each line naming the lot by the removal strategy (INV-39) and the delivery it is for; picked goods move bin -> WH1/OUT-STAGE (a transfer, no value change) and are sorted to their deliveries; a delivery leaves the batch only whole; validation of each delivery still claims stock per delivery (INV-08); a delivery in a batch cannot be cancelled until it is taken out
    screen: Deliveries
    path:
      process: inventory.delivery
      choices: {}
    reference: SAP WM / EWM wave picking and two-step picking (pick to staging, then allocate), picking sequence by bin; Odoo batch and wave transfers
    customer_varies: whether volume justifies batching; one-step or two-step picking
  - id: INV-52
    kind: person
    actor: stock_operator
    story: As a packer, I want to pack a delivery into boxes and pallets, each with its own label number and weight, so that the carrier and the customer can check every package.
    given: WH1/OUT/00011 of 6 PK24 COLA-075 and 2 DRILL-500; package types BOX-L (tare 0.6 KGM, 60 x 40 x 40 CMT) and PALLET-EU (tare 25 KGM); our GS1 company prefix 5012345
    when: I pack 4 PK24 on one pallet, 2 PK24 and 2 DRILL-500 in a box, and validate
    then: two packages, each with an SSCC from the series (18 digits, check digit computed, never reused) and its contents, gross weight = tare + the contents' copied weights (PALLET 101.8 KGM, BOX the sum likewise); GET /documents/WH1/OUT/00011/shipping lists the packages; validating with an item not in any package is refused under pick_pack_ship; a package's contents never exceed what was picked
    screen: Deliveries
    path:
      process: inventory.delivery
      choices: {}
    reference: SAP handling units (HU, packing in the delivery, SSCC per HU, packaging materials with tare); Odoo packages (stock.quant.package) and package types
    customer_varies: whether you pack into numbered packages; pallets or parcels
  - id: INV-53
    kind: person
    actor: warehouse_manager
    story: As the warehouse manager, I want a transfer between our sites to say when it will arrive, so that the receiving site can promise that stock and nobody loses track of a lorry.
    given: WH2 is supplied from WH1, 2 days in transit (product site PRD-37); a draft transfer of 144 LTR COLA-075 from WH1 to WH2
    when: it ships on 2026-11-02; an order at WH2 asks ATP; it arrives on 2026-11-05 with 126 LTR
    then: shipping records expected_arrival_on 2026-11-04 (ship date + the site's planned days); ATP at WH2 counts the 144 LTR from 2026-11-04 (INV-49); the transit stock is valued and in neither warehouse's available; on arrival 126 LTR are received and the 18 LTR short stay in UK1:TRANSIT on the transfer with gate transit_cleared unmet until a count of TRANSIT or a loss approved by a second person; a transfer overdue past its expected arrival is listed on the Transfers screen
    screen: Transfers
    path:
      process: inventory.transfer
      choices: {}
    reference: SAP stock transport order with stock in transit (two-step 303 / 305, or 351 / 101 with planned delivery time), in-transit stock in MMBE; Odoo two-step inter-warehouse resupply
  - id: INV-55
    kind: person
    actor: warehouse_manager
    story: As the warehouse manager, I want to put stock into quality inspection or blocked status where it stands, so that a doubtful pallet is held without anyone moving it across the warehouse.
    given: WH1/A/02 (default status unrestricted, allowing all three) holds 36 LTR of COLA-075 lot L-2612; WH1/QC allows only quality
    when: I set 18 LTR of L-2612 at WH1/A/02 to quality, then release 12 LTR and block 6, then try to put unrestricted stock into WH1/QC by a transfer
    then: each change is a move from (WH1/A/02, unrestricted) to (WH1/A/02, quality) and back, same bin, no value change, naming who and why; available at WH1 drops by 18 LTR and rises by 12; the blocked 6 LTR stay on hand and valued; the transfer into WH1/QC arrives as quality (the location's only allowed status); a reservation or a pick never takes quality or blocked stock; stock type is part of every stock row (product, location, lot, stock type, owner), and a location's status is its default and its limit (v3)
    screen: Stock
    path:
      process: inventory.stock
      choices: {}
    reference: SAP stock types per quant (unrestricted, quality inspection, blocked) and transfer postings 321 / 322, 343 / 344, 349 / 350 without a change of storage location
  - id: INV-30
    kind: system
    actor: system
    trigger: on read (derived)
    story: The system derives on hand, reserved and available from the moves and the reservations whenever they are asked, so that no stored quantity can drift from the history.
    given: moves into WH1/A/01 of 144 LTR and out of 108 LTR; reservations of 18 LTR at WH1
    when: on hand is asked for WH1/A/01, for the subtree WH1, and as of yesterday 17:00
    then: 36 LTR; the subtree is the sum over every internal location whose code starts with WH1/; as of a past moment only moves recorded by then count; asking twice gives the same answer
    reference: not built
  - id: INV-31
    kind: system
    actor: system
    trigger: in the same request as each move that changes a company's quantity of a product
    story: The system keeps the average cost per product per company by appending a valuation row per move, so that every delivery is costed at what the stock cost.
    given: "COLA-075 at UK1: 144 LTR worth 172.80 (average 1.2000)"
    when: 72 LTR are received at 1.3500, then 90 LTR delivered, then the last 126 LTR delivered
    then: "rows: +72 worth 97.20 (216 LTR, 270.00, average 1.2500); -90 worth -112.50 (126 LTR, 157.50); -126 worth -157.50 (0 LTR, 0.00): the move that empties the product takes the remaining value, never quantity x average, so no residue is left; each row is keyed (company, product, seq) and claimed with a plain INSERT, so two concurrent moves cannot both take the same seq; a transfer between warehouses of one company appends nothing"
    reference: not built
  - id: INV-32
    kind: system
    actor: system
    trigger: when a receipt, delivery, return or applied count is done, and again on retry while a posting is pending
    story: The system asks the ledger to post the value of each stock movement, so that the stock account always equals the stock.
    given: ledger mode post; the account map has stock_valuation, stock_received_not_billed, cost_of_goods_sold and inventory_loss for UK1
    when: delivery WH1/OUT/00001 worth 21.60 is done
    then: one journal (cost_of_goods_sold debit 21.60 / stock_valuation credit 21.60) with journal_id derived from (document, event), so posting again changes the ledger once; a refusal (a closed period, a missing account) leaves the posting pending with the ledger's reason, the stock move stands, and the Valuation screen lists it to fix; in export mode nothing is posted and the month's movements are a file for the accountant
    reference: not built
  - id: INV-33
    kind: system
    actor: system
    trigger: when a count is submitted and the step is on
    story: The system suggests a likely cause for each large count difference, so that the approver checks the obvious first.
    given: count C-15 shows WH1/A/01 short 18 LTR of COLA-075, and a transfer of 18 LTR to WH1/B/07 the same morning
    when: the count is submitted with ai_explain_variance on (suggest)
    then: "the line carries a suggestion (\"possibly the 18 LTR moved to WH1/B/07 at 09:12 was put in WH1/A/01: recount WH1/B/07\") marked as a suggestion; nothing is adjusted or approved by it; the approver's decision on it is logged with who"
    reference: not built
  - id: INV-42
    kind: system
    actor: system
    trigger: on the first business day of each month (the composition's clock), for every warehouse
    story: The system classifies each product A, B or C per warehouse by the value that moved out in the last twelve months, so that counting effort follows value.
    given: "WH1, last twelve months' issues and deliveries valued: COLA-075 40,000.00, SCREW-M4 8,000.00, GLOVES 900.00, nine others 1,100.00 together; thresholds A to 80%, B to 95%"
    when: the classification runs on 2026-11-02, and again the same day, and the warehouse manager overrides GLOVES to B with a reason
    then: "each product is classed by the cumulative share of the products above it: COLA-075 starts at 0% (A), SCREW-M4 at 80% (B), GLOVES at 96% and the rest after it (C); dated rows (warehouse, product, valid_from) from today; the re-run writes nothing; the override is a dated row with who and why, kept until the next run that would change the class names it as overridden; nothing about it changes stock or value"
    reference: SAP ABC analysis for cycle counting (MIBC by consumption or requirement value, thresholds per plant)
  - id: INV-20
    kind: integration
    actor: system
    trigger: when purchasing records a receipt line, from its own screen or from this module's scanner (INV-21)
    story: Purchasing posts each received line here, so that stock moves are owned by one module and a delivery is keyed once.
    given: purchasing's receipt R-1 of 8 PK24 of COLA-075 on PO-0101 line 1 into WH1/A/01, received 2026-10-21, at 21.6000 a pack
    when: purchasing calls POST /receipts twice with move_ref pur:R-1:1
    then: "one move SUPPLIER -> WH1/A/01 of 144 LTR, converted exactly through product, dated the received_on date, valued 172.80, answered {move_id, quantity_base: \"144\"}; the second call returns the same move and records nothing; a unit that does not convert exactly is refused with product's reason and nothing is moved"
    owner: inventory
    reference: not built
  - id: INV-21
    kind: integration
    actor: system
    trigger: when goods-in submits a scanned delivery on this module's Receipts screen
    story: The scanner records the receipt through purchasing, so that there is one way a receipt is recorded and purchasing owns the order and its matching.
    given: 8 PK24 scanned against PO-0101 line 1 into WH1/A/01, delivery note DN-881
    when: the scan is submitted
    then: purchasing's POST /purchase-orders/PO-0101/receipts is called once with delivery note DN-881; purchasing answers the receipt with a move_ref per line, each line already posted here (INV-20); the lots and serials scanned are attached to the moves those move_refs name; submitting DN-881 again records once; the scanner never posts a supplier move itself
    owner: purchasing
    reference: not built
  - id: INV-22
    kind: integration
    actor: system
    trigger: when a sales order is confirmed, amended or cancelled
    story: The sales order asks this module to reserve (or release) stock for its goods lines, so that what is promised is held.
    given: SO-2026-0012 confirmed, revision 1, line 1 48 C62 of COLA-075 at 0.75 LTR each; 45 LTR available at WH1
    when: sales-order calls POST /reservations/sales-orders/SO-2026-0012 with revision 1, twice
    then: 36 LTR reserved for line 1 at WH1, short 0; the second call changes nothing; revision 2 with 24 C62 reduces the reservation to 18 LTR; a release (cancellation) frees it all; a service line is ignored and said so; the answer is each line's readiness {gate, met, reason, fix}
    owner: inventory
    reference: "not built: sales-order 0.x does not call this yet (it has no outbound seam for stock); until it does, the warehouse manager reserves from the Deliveries screen (INV-13), which reads the order through GET /sales-orders/{sales_order_id}"
  - id: INV-23
    kind: integration
    actor: system
    trigger: when a delivery or a customer return is done
    story: This module records on the sales order what was delivered, through the order's own route, so that the order's fulfilment and its invoicing follow the warehouse.
    given: delivery WH1/OUT/00001 of 24 C62 on SO-2026-0012 line 1
    when: it is validated, and the call is repeated
    then: "sales-order's record_delivery is called with quantity 24 in the line's own unit, delivery_ref inv:WH1/OUT/00001 and delivered_on today; the order records it once; a refusal by the order (more than ordered, an order no longer confirmed) refuses the whole validation and nothing is written here; v3: before raising and validating it reads GET /sales-orders/{sales_order_id}/fulfilment (blocks, complete delivery, tolerances, the order type's special stock and purpose); a customer return is recorded on its returns order (INV-14), never as a negative on the original"
    owner: sales-order
    reference: the route exists (erp-brick-sales-order POST /sales-orders/{sales_order_id}/deliveries)
  - id: INV-24
    kind: integration
    actor: system
    trigger: from INV-32
    story: Stock journals are posted by the ledger, never written here.
    given: the ledger installed and post mode on
    when: a posting is due
    then: a balanced journal reaches the ledger's journal route; the ledger owns the journal, the period and the balance
    owner: gl
    reference: the route ar already calls (POST /journal-entry/journals); the gl spec (written in parallel) confirms it
  - id: INV-25
    kind: integration
    actor: system
    trigger: when a document line names a product and a unit
    story: Quantities are converted by the product module, and a unit used here is frozen there, so that a pack size cannot change under stock.
    given: COLA-075 with PK24 = 24 bottles = 18 LTR
    when: a receipt line of 8 PK24 is written
    then: the product's convert route answers exactly (144 LTR, 18/1); the move stores the quantity in LTR, the document's unit, numerator and denominator; product's unit-used route is called once for PK24; a conversion the product cannot make exactly within the base unit's decimals is refused with the product's reason
    owner: product
    reference: the routes exist (erp-brick-product GET /products/{product_id}/convert, POST /products/{product_id}/units/{unit_code}/used, GET /gtin/{gtin})
  - id: INV-26
    kind: integration
    actor: system
    trigger: on a one-off migration at cut-over
    story: The Odoo stock comes over once as opening balances, reconciled per product and location and in value, and can be re-run safely.
    given: an Odoo database with two warehouses, 300 stocked products, lots on 20 of them and an average cost per product
    when: the migration runs twice and the reconciliation is computed
    then: one opening move per (product, location, lot) from OPENING, dated the cut-over date, valued at Odoo's cost; the second run writes nothing; every check in migration.odoo.reconcile is equal or explained; once the customer signs the reconciliation, a later run refuses to rewrite it and lists a difference as an adjustment to make
    owner: inventory
    reference: not built
  - id: INV-27
    kind: integration
    actor: system
    trigger: when another module asks a product's cost or availability
    story: Sales and invoicing read availability and the average cost here, so that a promise date and a margin use the stock's own figures.
    given: COLA-075 with 27 LTR available at WH1 and an average cost of 1.2500 at UK1
    when: sales-order asks availability, and the order admin asks the cost for margin
    then: availability answers per warehouse without bins or value; the cost answers only to a caller holding inv:valuation:read; product's standard cost_amount is left untouched by this module
    owner: inventory
    reference: not built
  - id: INV-28
    kind: integration
    actor: system
    trigger: when purchasing records a return to the supplier
    story: Purchasing posts a return to the supplier here, so that the goods leave stock at the cost they came in at.
    given: receipt R-1 posted 144 LTR into WH1/A/01 (move_ref pur:R-1:1); 2 PK24 are damaged
    when: purchasing calls POST /returns-to-supplier with move_ref pur:RET-1:1 reversing pur:R-1:1, twice
    then: "one move WH1/A/01 -> SUPPLIER of 36 LTR valued at the receipt's cost (43.20), answered {move_id, quantity_base: \"36\"}; the second call records nothing; a return when the stock is no longer at WH1/A/01 is refused (409, \"WH1/A/01 holds 20 LTR, 36 asked\") and nothing moves"
    owner: inventory
    reference: not built
  - id: INV-45
    kind: integration
    actor: system
    trigger: when a consignment order (sales-order SO-45) is delivered, issued, picked up or returned
    story: Stock kept at a customer stays ours and valued, apart from what we can sell, until the customer uses it.
    given: 7311 consignment location UK1:CONSIGNMENT:7311 (kind consignment_customer, created on first use); a CONS_FILL order of 240 C62 COLA-075
    when: inventory delivers the CONS_FILL, then the CONS_ISSUE of 60, the CONS_PICKUP of 24 and the CONS_RETURN of 6, and sales-order asks GET /consignment-stock/customers/7311
    then: the fill is a move WH1/A/01 -> UK1:CONSIGNMENT:7311 of 180 LTR, no value change, no cost of sales, not recorded as a delivery on the order's invoicing (the order type says so in its fulfilment answer); the issue moves 45 LTR to UK1:CUSTOMER at the average (cost of sales) and calls record_delivery on the CONS_ISSUE order; the pick-up moves 18 LTR back to WH1; the return receives 4.5 LTR from UK1:CUSTOMER into quality; the stock answer is 162 C62 (121.5 LTR); consignment stock is on hand and valued, never available, reserved or promised to anyone else
    owner: inventory
    reference: not built
  - id: INV-47
    kind: integration
    actor: system
    trigger: when purchasing's subcontract order is sent (components provided) and when the subcontracted product is received
    story: Components we give a subcontractor stay ours at their site, and are consumed into the finished product when it comes back, so that its value is the components plus the service.
    given: purchasing's subcontract order PO-0160 with subcontractor 9200 for 100 C62 of KIT-A at 3.0000 service each, components 100 C62 BOX-S and 200 C62 SCREW-M4 (listed on the order, no bill of materials needed)
    when: the warehouse manager ships the components (a transfer to UK1:SUBCONTRACT:9200), then purchasing posts the receipt of 100 KIT-A through POST /receipts with source_kind subcontract_receipt and the components consumed, twice
    then: the components sit at UK1:SUBCONTRACT:9200 on hand and valued, never available; the receipt is one move SUPPLIER -> WH1/A/09 of 100 KIT-A and two consumption moves out of UK1:SUBCONTRACT:9200 (100 BOX-S, 200 SCREW-M4) at their average; KIT-A's receipt value = the components' value + 300.00 service, so stock value is moved, not created; a component short at the subcontractor is refused (409, naming it) and nothing is moved; the repeat records nothing
    owner: inventory
    reference: SAP subcontracting (item category L, special stock O, movement types 541 provision and 543 consumption with 101 receipt)
  - id: INV-49
    kind: integration
    actor: system
    trigger: when sales-order promises dates (SO-35) or re-promises them (SO-36)
    story: Inventory answers what can be promised by date, from stock, receipts and transfers on their way, so that a promise uses the same figures as the warehouse.
    given: "COLA-075 at WH1: unrestricted 360 LTR (of which lot L-2601 9 LTR expired), reserved 180 LTR with dates; purchasing expects 720 LTR on 2026-11-09; goods-in 1 day; a transfer of 36 LTR arriving 2026-11-04"
    when: sales-order asks GET /atp/COLA-075?warehouse_id=WH1&quantity=480&unit_code=C62&requested_on=2026-11-03&min_shelf_life_days=60
    then: available_now 171 LTR (360 - 9 expired - 180 reserved), plus 36 LTR from 2026-11-04 and 720 LTR from 2026-11-10; the 360 LTR asked are confirmed 171 now, 36 on 2026-11-04 and 153 on 2026-11-10; stock expiring within the minimum shelf life of its date is not counted; quality, blocked and customer-consignment stock never; expected receipts read from purchasing's GET /expected-receipts, never from pur_ tables; nothing is reserved by asking
    owner: inventory
    reference: not built
  - id: INV-54
    kind: integration
    actor: system
    trigger: when a replenishment proposal to buy is accepted (or sent in auto mode)
    story: An accepted proposal becomes one purchase request in purchasing, so that purchasing owns the buying and the proposal knows what became of it.
    given: the WH1 proposal for 60 PK24 of COLA-075 accepted on 2026-11-02
    when: inventory calls POST /purchase-requests/from-replenishment twice with request_ref inv:repl:WH1:COLA-075:2026-11-02
    then: purchasing answers one request_id; the proposal is marked sent with it; the second call returns the same; the next night's projection counts the request as expected until purchasing reports it ordered (then the order's expected receipt) or cancelled (then the proposal is open again)
    owner: purchasing
    reference: not built
  - id: INV-57
    kind: integration
    actor: system
    owner: inventory
    trigger: when purchasing approves a bill whose actual delivery cost differs from what the receipt was valued at
    story: Purchasing hands the delivery-cost difference here, so that stock still on hand carries its real landed cost and the rest goes to price difference.
    given: receipt R-77 of 100 PK24 of COLA-075 valued at 1,800.00 including 50.00 planned freight; 60 PK24 of it still on hand; the forwarder bills 80.00
    when: purchasing calls POST /valuation-adjustments with adjustment_ref pur:B-912:1 and amount 30.00
    then: 18.00 (60 of 100) is added to the value on hand of that receipt's stock and 12.00 posts to price difference, one journal through gl; a repeat with the same adjustment_ref changes nothing; under standard cost the whole 30.00 is price difference
  - id: INV-58
    kind: integration
    actor: system
    owner: inventory
    trigger: when a till sale closes (pos POS-27) and when a production order issues components (manufacturing MFG-20)
    story: Another module asks this one to take stock out for what it sold or used, so that the move, its lot and its value are inventory's and the cost is posted once.
    given: LON-SOHO's consumption location LON-SOHO/USE holds 3.200 KGM of BEANS-ETH at an average cost of 18.0000 a KGM; receipt R-5521 sold two lattes whose recipe uses 0.018 KGM each; production order UK01-MO-2026-00118 issues 84.000 KGM of GREEN-ETH, lot GE-0412
    when: pos calls POST /goods-issues/from-source with source_kind pos_sale and move_refs pos:R-5521:1:1 and pos:R-5521:2:1; manufacturing calls it with source_kind production_issue and account_purpose wip; each call is repeated
    then: "one move per line keyed move_ref (the repeat answers the same moves and changes nothing); pos's two moves of 0.018 KGM at 18.0000 are valued 0.32 and 0.33 (each rounded once, the remainder on the last so the issue totals round(0.036 x 18.0000) = 0.65), journal cost_of_sales / stock_valuation; the production issue is valued at its lot's cost and posts wip / stock_valuation; each answer lists {move_ref, move_id, quantity_base, value}; a pos_sale is never refused for stock (the sale has happened: a short location goes negative and is listed for the stock controller), a production_issue short of stock is refused (gate on_hand) unless the location allows negative stock; the lot is the one named, else FEFO. v7: an output or by-product received in error comes back out the same way, source_kind production_output_reversal naming reverses_move_ref \"mfg:UK01-MO-2026-00118:output:1\": the move leaves at the value it came in (the reversed move's), debits wip and credits stock_valuation, from the same lot; it is refused 409 {gate: on_hand} when that lot no longer holds the quantity (it was sold or used: correct it there first) and once per reversed move"
  - id: INV-59
    kind: integration
    actor: system
    owner: inventory
    trigger: when a production order reports output or a by-product (MFG-20), and when a till refund puts goods back on the shelf (pos POS-11)
    story: Another module hands this one what it produced or took back, so that the stock is received at the right cost and a lot can be traced back to what it was made of.
    given: UK01-MO-2026-00118 reports 82.500 KGM of ROAST-ETH as lot RE-1180 at standard 9.3899, from input lot GE-0412 (84.000 KGM), and 2.000 KGM of CHAFF at its net realisable value 0.5000; refund R-5530 restocks one BAG-ETH-250 sold on R-5521
    when: manufacturing calls POST /receipts with source_kind production_receipt and by_product_receipt; pos calls it with source_kind pos_refund_restock naming reverses_move_ref pos:R-5521:3:1
    then: RE-1180 is received at 774.67 (82.500 x 9.3899 = 774.66675, rounded once) and credits wip, the chaff at 1.00 and credits wip; a lot link RE-1180 <- GE-0412 (84.000 KGM) is recorded, so GET /lots/ROAST-ETH/RE-1180/trace walks back to the green beans and GET /lots/GREEN-ETH/GE-0412/trace forward to every bag; the restocked bag is received at the cost it left at (the reversed move's value) and credits cost_of_sales; each is idempotent on move_ref; purchasing's source kinds are unchanged
  - id: INV-60
    kind: integration
    actor: system
    owner: inventory
    trigger: when manufacturing releases a cost roll-up (MFG-07)
    story: A released roll-up becomes this module's dated standard prices, so that the standard is the one a second person approved and the stock is revalued on the day it starts.
    given: UK01 values at standard; roll-up CR-2026-12 released by cost accountant B with ROAST-ETH 9.6100 a KGM from 2026-12-01
    when: manufacturing calls POST /standard-prices with source_ref mfg:CR-2026-12, twice; the accountant had already scheduled 9.5000 for 2026-12-01 by hand
    then: "without the accountant's row: a scheduled standard price (UK01, ROAST-ETH, 2026-12-01, 9.6100) with set_by B and source_ref, the repeat answers the same; revalued on 2026-12-01 by apply_standard_price (INV-48); with the accountant's different row for the same date the call is refused 409 (gate standard_price_taken: \"a standard price of 9.5000 is already set for 2026-12-01 by <who>\"), never overwritten; a valid_from of today or earlier is refused (gate starts_after_today); a company valued at average cost is refused (gate values_at_standard)"
  - id: INV-61
    kind: integration
    actor: system
    owner: inventory
    trigger: when the nightly replenishment runs and manufacturing is installed
    story: Replenishment counts what production will consume, so that components are bought in time for planned production, and leaves made products to production's planning.
    given: "GREEN-ETH at ROASTERY (buy, reorder point 500 KGM): 900 KGM on hand, 1,200 KGM needed by planned orders within the horizon; ROAST-ETH at ROASTERY (make, mrp)"
    when: the proposal runs
    then: "GREEN-ETH's projected available is 900 - 1,200 = -300 KGM, at or below its reorder point, so a buy proposal is made as for any product (rounded by product, sent through purchasing); the requirements are read from manufacturing's GET /dependent-requirements for the site and the horizon, never from mfg_ tables; ROAST-ETH is not proposed (procurement make or planning mrp: manufacturing's MRP-lite plans it)"
processes:
  - key: warehouse
    pcf_id: null
    pcf_name: Operate warehousing (set up the storage locations)
    reference_names:
      - Warehouse management
      - Locations
    brick: inventory
  - key: stock
    pcf_id: null
    pcf_name: Manage inventory (on hand, availability, corrections)
    reference_names:
      - Plan to Inventory
      - Stock overview
    brick: inventory
  - key: receipt
    pcf_id: null
    pcf_name: Receive, inspect and store inbound deliveries
    reference_names:
      - Procure to Pay (goods receipt)
      - Receipts
    brick: inventory
  - key: delivery
    pcf_id: null
    pcf_name: Fulfil customer orders (pick, pack, ship)
    reference_names:
      - Order to Cash (delivery)
      - Deliveries
    brick: inventory
  - key: transfer
    pcf_id: null
    pcf_name: Track inventory (internal moves)
    reference_names:
      - Internal transfers
    brick: inventory
  - key: stock_count
    pcf_id: null
    pcf_name: Perform physical inventory counts and reconcile
    reference_names:
      - Physical inventory
      - Cycle count
    brick: inventory
  - key: valuation
    pcf_id: null
    pcf_name: Account for inventory (valuation)
    reference_names:
      - Inventory valuation
      - Record to Report (stock)
    brick: inventory
  - key: goods_issue
    pcf_id: null
    pcf_name: Issue stock for internal use and scrap it (v3)
    reference_names:
      - Goods issue to cost centre
      - Scrapping
    brick: inventory
  - key: replenishment
    pcf_id: null
    pcf_name: Plan and replenish inventory (v3)
    reference_names:
      - Consumption-based planning
      - Reordering rules
    brick: inventory
  - key: standard_price
    pcf_id: null
    pcf_name: Set standard costs and revalue stock (v3)
    reference_names:
      - Standard price release
      - Revaluation
    brick: inventory
workflows:
  - entity: receipt
    states:
      - scanned
      - done
    terminal:
      - done
    transitions:
      - key: scan_delivery
        name: Scan what arrived
        from: none
        to: scanned
        by: stock_operator
        gate: "readiness: on_order (purchasing's GET /purchase-orders/{purchase_order_id}/expected), units_exact, tracking_complete, within_tolerance; the bin is internal and not archived"
        effect: "purchasing's POST /purchase-orders/{purchase_order_id}/receipts called once, keyed by the delivery note: the ONE way a receipt is recorded; nothing in stock until purchasing posts each line back"
      - key: receive_customer_return
        name: Receive a customer return against its RMA
        from: none
        to: done
        by: stock_operator
        gate: "readiness: rma_open (sales-order's expected return for that customer and product), within_rma, serial_was_delivered (a serial delivered to that customer)"
        effect: numbered {warehouse}/RET/{seq:5}; a move CUSTOMER -> the return location in stock type quality where the reason inspects, valued at the cost it left at; record_delivery on the returns order (v3)
      - key: inspect_return
        name: Inspect the returned goods
        from: done
        to: done
        by: stock_operator
        gate: the return is in quality stock; every unit decided
        effect: restock (a type change to unrestricted, or a putaway), scrap (a goods issue, purpose scrap) or back to the customer at the value it came in; accepted and rejected reported to sales-order once (POST /sales-orders/{sales_order_id}/return-inspections)
      - key: receive_from_source
        name: Receive what another module produced or took back (v6, INV-59)
        from: none
        to: done
        by: system
        gate: "readiness: source_kind production_receipt | by_product_receipt | pos_refund_restock; move_ref unique (a known one answers its move); units convert exactly; the location is internal; a pos_refund_restock names the move it reverses"
        effect: "numbered {warehouse}/IN/{seq:5}; a move PRODUCTION (or CUSTOMER) -> location; valued at unit_cost (production: standard or the order's cost; by-product: its net realisable value) or, for a restock, at the reversed move's cost; credits wip (production) or cost_of_sales (restock); a lot link per input lot named"
      - key: post_receipt
        name: Post the received stock
        from: scanned
        to: done
        by: system
        gate: purchasing calls POST /receipts per line, keyed move_ref pur:<receipt_id>:<line_no> (a receipt recorded on purchasing's own screen starts here)
        effect: "numbered {warehouse}/IN/{seq:5}; a move SUPPLIER -> location per line, converted exactly, valued at quantity_priced x unit_cost / pricing_quantity rounded once (v2: purchasing's pricing unit and quantity); the unit's weights and volume copied onto the line (v2); average cost appended; scanned lots and serials attached; the valuation posted; {move_id, quantity_base} answered"
    note: "v3: a receipt lands in WH1/IN when receipt_steps is two and a putaway transfer follows (put_away_stock); a supplier-consignment line carries the owner and no value; a subcontract receipt consumes the components at the subcontractor (INV-47). What is still to arrive is purchasing's (its outstanding quantities), never an inventory document; a return to the supplier is purchasing's return row posted through POST /returns-to-supplier (INV-28), valued at the receipt's cost; a return from a customer is a receipt from CUSTOMER naming the delivery it reverses (INV-14), valued at the cost it left at"
  - entity: delivery
    states:
      - waiting
      - ready
      - done
      - cancelled
    terminal:
      - done
      - cancelled
    transitions:
      - key: reserve_order
        name: Reserve stock for the confirmed order
        from: none
        to: waiting
        by: system
        gate: a confirmed sales order with goods lines
        effect: reservation rows per line at the warehouse, as much as is available (never from a quality or blocked location, v2); the shortfall stated
      - key: reserve_by_hand
        name: Reserve or release by hand
        from: waiting
        to: waiting
        by: warehouse_manager
        requires: reason
        gate: no more than is available
        effect: a reservation row appended, with who and why
      - key: stock_arrives
        name: Stock becomes available
        from: waiting
        to: ready
        by: system
        gate: every line reserved in full, or the order accepts part shipments
        effect: the delivery appears on the pick list
      - key: batch_deliveries
        name: Batch deliveries into one pick
        from: ready
        to: ready
        by: warehouse_manager
        gate: deliveries of one warehouse, ready, not in another batch
        effect: a pick batch {warehouse}/PB/{seq:5} with one pick list in pick_sequence order (v3)
      - key: pick_goods
        name: Pick from the bins
        from: ready
        to: ready
        by: stock_operator
        gate: "each bin holds what is picked from it (unless negative stock is allowed there) and the stock picked is unrestricted (v3: by stock row); a lot or serial per tracked unit; readiness: shelf_life (the lot proposed by the removal strategy, FEFO or FIFO, with the customer's minimum remaining shelf life; another lot only by a warehouse manager with a reason; never an expired lot unless the owner allows it); the line's unit converts exactly to the order line's unit"
        effect: picked quantities recorded on the delivery, proposed in the warehouse unit (v2) and by lot (v3); with two-step picking, a transfer bin -> staging
      - key: pack_delivery
        name: Pack into packages
        from: ready
        to: ready
        by: stock_operator
        gate: contents never more than picked; a package type
        effect: packages with an SSCC each (claimed, never reused), contents and gross weight (v3)
      - key: validate_delivery
        name: Validate the delivery
        from: ready
        to: done
        by: stock_operator
        gate: "readiness: something_picked, stock_claimed (the claim rows on every bin and the warehouse were won), order_accepts (the sales order's record_delivery answered ok), weights_known (v2, only with delivery_needs_weights), not_blocked (v3: the order's fulfilment answer has no delivery block or incomplete delivery field), all_packed (v3, only with pick_pack_ship)"
        effect: numbered {warehouse}/OUT/{seq:5}; gross and net weight and volume answered for shipping (v2); supplier-consignment stock picked is withdrawn first (purchasing told, v3); moves bin -> CUSTOMER at average or standard cost, or to the customer's consignment location for a CONS_FILL order (v3); the reservation consumed; the order records the delivery; the cost of goods posted to the purpose's account (sale, free_of_charge, consignment issue); what is left goes to a back-order delivery unless the order asks for complete delivery or the line closed within tolerance
      - key: cancel_delivery
        name: Cancel the delivery
        from: ready
        to: cancelled
        by: warehouse_manager
        requires: reason
        gate: nothing on it validated
        effect: its reservations released
    note: "a delivery is undone only by a return receipt (INV-14). Two validations for the last unit: one wins the claim row, the other is refused and writes nothing (INV-08)"
  - entity: transfer
    states:
      - draft
      - in_transit
      - done
      - cancelled
    terminal:
      - done
      - cancelled
    transitions:
      - key: plan_transfer
        name: Plan the move
        from: none
        to: draft
        by: warehouse_manager
        gate: both locations internal, of one company (a subcontractor's or a customer's consignment location of the company counts as one, v3)
        effect: a draft transfer; between an unrestricted and a quality or blocked location it is a release or a block (v2); a transfer to a subcontractor provides components (v3); from a replenishment proposal, the supplying site's stock (v3)
      - key: put_away_stock
        name: Put away from goods-in
        from: draft
        to: done
        by: stock_operator
        gate: "readiness: bin_capacity (quantity, weight and volume within the bin's capacity, from the copied measures)"
        effect: the bin proposed by the putaway rules (fixed bin, addition to stock, next bin with room), or the one chosen with who; no value change (v3)
      - key: provide_to_subcontractor
        name: Send components to a subcontractor (v3)
        from: none
        to: done
        by: system
        gate: purchasing's subcontract order line names them (POST /subcontract-provisions, idempotent on move_ref); the source location holds them
        effect: a transfer to the subcontractor's location as stock still ours (special stock O), consumed later by the subcontract receipt
      - key: change_stock_type
        name: Change the stock type where it stands
        from: none
        to: done
        by: warehouse_manager
        requires: reason
        gate: the location accepts the new type; the stock is there
        effect: a move between types at the same location, no value change; blocking a lot changes it everywhere it is (v3)
      - key: move_within_site
        name: Move between bins
        from: draft
        to: done
        by: stock_operator
        gate: both bins in one warehouse; the source holds it; a lot or serial per tracked unit
        effect: numbered {warehouse}/INT/{seq:5}; one move bin -> bin; no value change
      - key: ship_to_site
        name: Ship to the other warehouse
        from: draft
        to: in_transit
        by: stock_operator
        gate: the source holds it
        effect: a move bin -> TRANSIT; counted in transit, available nowhere
      - key: receive_at_site
        name: Receive at the other warehouse
        from: in_transit
        to: done
        by: stock_operator
        gate: no more received than was shipped
        effect: a move TRANSIT -> bin; a shortfall is left in transit until a count of TRANSIT or a loss approved by a second person is applied (gate transit_cleared, v3); expected_arrival_on was set when shipped, from the site's planned days
      - key: cancel_transfer
        name: Cancel the planned move
        from: draft
        to: cancelled
        by: warehouse_manager
    note: a move recorded by mistake is reversed by a new move naming it (INV-15), never edited
  - entity: stock_count
    states:
      - counting
      - submitted
      - approved
      - applied
      - rejected
    terminal:
      - applied
    transitions:
      - key: start_count
        name: Start a count
        from: none
        to: counting
        by: warehouse_manager
        gate: an internal location subtree, or a list of products over every bin that holds them (v3); no other open count on it
        effect: every product (and stock type) with stock in scope listed, with no expected quantity shown to the counter
      - key: record_counted
        name: Record what is on the shelf
        from: counting
        to: counting
        by: stock_operator
        gate: a quantity within bounds and the unit's decimals, in any unit of the product (v2); a lot or serial for a tracked product
        effect: one or more entries per line (5 PK24, 6 C62) summed exactly into counted_base; counted_at per line; expected is what the moves said at counted_at
      - key: submit_count
        name: Submit the count
        from: counting
        to: submitted
        by: warehouse_manager
        effect: differences and their value at average cost fixed on the count
      - key: ai_explain_variance
        name: AI suggests likely causes (suggest)
        from: submitted
        to: submitted
        by: system
        gate: the step is on and a line's difference is over the threshold
        effect: a suggestion per line; nothing adjusted
      - key: apply_small
        name: Apply a count under the threshold
        from: submitted
        to: applied
        by: warehouse_manager
        gate: the sum of the absolute VALUE differences across the lines is under count_approval_threshold, and no single line's absolute value difference is at or above count_line_value_limit
        effect: an adjustment move per line between the bin and LOSS; the loss or gain posted
      - key: approve_count
        name: A second person approves the count
        from: submitted
        to: approved
        by: stock_controller
        approval: true
        gate: "readiness: approver_not_counter (neither a counter nor the submitter, by email and by sign-in subject)"
        effect: the decision recorded
      - key: apply_approved
        name: Apply the approved count
        from: approved
        to: applied
        by: system
        effect: adjustment moves; the loss or gain posted
      - key: reject_count
        name: Reject and recount
        from: submitted
        to: rejected
        by: stock_controller
        requires: reason
        effect: nothing applied
      - key: recount
        name: Recount
        from: rejected
        to: counting
        by: warehouse_manager
        effect: the lines are recorded again
    note: "a count never sets a quantity: it appends the difference as moves to or from LOSS. Moves recorded after a line was counted are kept, because the difference is taken at counted_at"
  - entity: goods_issue
    states:
      - draft
      - awaiting_approval
      - posted
      - cancelled
    terminal:
      - posted
      - cancelled
    transitions:
      - key: plan_goods_issue
        name: Plan an issue or a scrap
        from: none
        to: draft
        by: stock_operator
        gate: "readiness: cost_centre_valid (the ledger's cost centre, for purpose cost_centre), scrap_reason (for purpose scrap); the product's issue unit proposed (product PRD-29)"
        effect: a draft goods issue with its purpose (cost_centre | scrap | internal_use), lines in any unit of the product
      - key: post_goods_issue
        name: Post the issue
        from: draft
        to: posted
        by: stock_operator
        gate: "readiness: stock_claimed (bin and warehouse claim rows won), under_issue_threshold (the value is under issue_approval_threshold)"
        effect: numbered {warehouse}/GI/{seq:5}; moves bin -> {company}:CONSUMPTION or :LOSS at average or standard cost; a journal per purpose (consumption with the cost centre on the line, scrap) posted
      - key: submit_goods_issue
        name: Submit an issue over the threshold
        from: draft
        to: awaiting_approval
        by: stock_operator
        gate: the value is at or above issue_approval_threshold
        effect: waits for a stock controller; nothing moves
      - key: approve_goods_issue
        name: A second person approves the issue
        from: awaiting_approval
        to: posted
        by: stock_controller
        approval: true
        gate: "readiness: approver_not_requester (by email AND sign-in subject), stock_claimed"
        effect: posted as post_goods_issue
      - key: reject_goods_issue
        name: Reject the issue
        from: awaiting_approval
        to: cancelled
        by: stock_controller
        requires: reason
      - key: cancel_goods_issue
        name: Cancel the draft issue
        from: draft
        to: cancelled
        by: stock_operator
      - key: issue_from_source
        name: Take out what another module consumed (v6, INV-58)
        from: none
        to: posted
        by: system
        gate: "readiness: source_kind pos_sale | production_issue | production_output_reversal (v7: an output or by-product received in error taken back out, naming reverses_move_ref); each move_ref unique (a known one answers its move); units convert exactly; stock_claimed; on_hand for production_issue (a pos_sale posts and may go negative, listed for the stock controller)"
        effect: "numbered {warehouse}/GI/{seq:5}; moves location -> {company}:CONSUMPTION per line at average or standard cost (the lot named, else FEFO); a journal per call: cost_of_sales (pos_sale) or wip (production_issue) / stock_valuation; {move_ref, move_id, quantity_base, value} answered"
      - key: reverse_goods_issue
        name: Reverse a posted issue
        from: posted
        to: posted
        by: warehouse_manager
        requires: reason
        gate: not reversed before; the issue's period open in the ledger
        effect: reversing moves naming the original, valued as it was, and a reversing journal (SAP 202 / 552)
    readiness:
      - transition: issue_from_source
        gate: on_hand
        reason: "{location} holds {on_hand} of {product}; the production issue needs {quantity}"
        fix: move stock there first, or the owner allows negative stock at the location
      - transition: plan_goods_issue
        gate: cost_centre_valid
        reason: the ledger has no open cost centre with that code
        fix: pick a cost centre (gl)
      - transition: post_goods_issue
        gate: under_issue_threshold
        reason: the issue's value is at or above the approval threshold
        fix: submit it for a stock controller
      - transition: approve_goods_issue
        gate: approver_not_requester
        reason: you planned or submitted this issue (same email or sign-in subject)
        fix: ask another stock controller
  - entity: replenishment_proposal
    states:
      - proposed
      - sent
      - dismissed
    terminal:
      - sent
      - dismissed
    transitions:
      - key: propose_replenishment
        name: Propose what to buy or move (nightly)
        from: none
        to: proposed
        by: system
        gate: "a product planned at the site (product's GET /product-sites) with procurement buy or transfer (v6: make or mrp is manufacturing's, skipped); projected available (v6: less manufacturing's dependent requirements in the horizon, GET /dependent-requirements, when manufacturing is installed) at or below its reorder point; once per (site, product, business date)"
        effect: "a proposal: projected figures, the site row's valid_from, quantity to the max (min_max) or the lot size, rounded by product's round-proposal; buy or transfer from the supplying site"
      - key: accept_replenishment
        name: Accept the proposal
        from: proposed
        to: sent
        by: warehouse_manager
        gate: the quantity may be changed; it still meets the purchase rule
        effect: "buy: one purchase request in purchasing (POST /purchase-requests/from-replenishment); transfer: a draft transfer from the supplying site"
      - key: auto_send_replenishment
        name: Send the proposal automatically (auto mode)
        from: proposed
        to: sent
        by: system
        gate: the owner's replenishment_mode is auto from a date on or before today
        effect: as accept_replenishment, by the system's client
      - key: dismiss_replenishment
        name: Dismiss the proposal
        from: proposed
        to: dismissed
        by: warehouse_manager
        requires: reason
  - entity: standard_price
    states:
      - scheduled
      - effective
    terminal:
      - effective
    transitions:
      - key: schedule_standard_price
        name: Set a standard price from a date
        from: none
        to: scheduled
        by: accountant
        gate: "readiness: starts_after_today; the company values at standard on that date, or switches to it that day"
        effect: a dated standard price per company and product (NUMERIC(19,4) per base unit)
      - key: intake_standard_price
        name: Take a released roll-up's standard price (v6, INV-60)
        from: none
        to: scheduled
        by: system
        gate: "readiness: starts_after_today; values_at_standard (the company values at standard on valid_from); standard_price_taken (no other price for that company, product and date)"
        effect: as schedule_standard_price, with set_by the releaser and source_ref; idempotent on (company_code, product_id, valid_from, source_ref)
      - key: apply_standard_price
        name: The standard price takes effect
        from: scheduled
        to: effective
        by: system
        gate: valid_from is today (business_timezone)
        effect: a revaluation row of the quantity on hand at the old and new price, and its journal (stock_valuation against revaluation), journal_id derived (company, product, valid_from), posted once
    readiness:
      - transition: schedule_standard_price
        gate: starts_after_today
        reason: a standard price starts tomorrow at the earliest
        fix: pick a later date
      - transition: intake_standard_price
        gate: standard_price_taken
        reason: a standard price of {price} is already set for {valid_from} by {who}
        fix: the accountant withdraws theirs, or manufacturing releases for a later date
      - transition: intake_standard_price
        gate: values_at_standard
        reason: "{company} values at average cost on {valid_from}"
        fix: the owner switches the company to standard from a later month (INV-48), or release for average cost (no standard price)
entities:
  - id: warehouse
    meaning: a site where stock is kept, belonging to one company
    natural_key: "warehouse_id: the customer's own short code (WH1), fixed once set"
    key_attributes:
      - name
      - company_code
      - address
      - allow_negative_stock_from (dated; the owner's control)
      - status (active | archived)
    relationships:
      - 1..n location
    master_data: module-owned
    reference_table: inv_warehouse
  - id: location
    meaning: a place stock can be in, real (a zone, a bin) or virtual (supplier, customer, loss, transit, opening)
    natural_key: "location_id: the full path code (WH1/A/01), VARCHAR, fixed once a move names it; virtual ones are {company_code}:SUPPLIER, :CUSTOMER, :LOSS, :TRANSIT, :OPENING"
    key_attributes:
      - warehouse_id
      - parent_location_id
      - "kind (view | internal | supplier | customer | loss | transit | opening | consumption (v3) | consignment_customer (v3, per customer: {company}:CONSIGNMENT:{bp_id}) | subcontractor (v3, per subcontractor: {company}:SUBCONTRACT:{bp_id}))"
      - "stock_status (v2, internal only: unrestricted | quality | blocked; v3: the DEFAULT type of stock put here)"
      - "allowed_stock_types (v3: default all three; a QC area quality only)"
      - "pick_sequence (v3: the walking order)"
      - "max_quantity_base, max_weight, max_volume (v3: capacity; null = unlimited)"
      - barcode
      - status (active | archived)
    relationships:
      - -> warehouse
      - -> location (parent)
    master_data: module-owned
    reference_table: inv_location
    note: a subtree is every location whose code starts with the parent's code and a slash, so on hand per zone is one prefix query, no graph walk
  - id: stocked_product
    meaning: how this module treats a product it stocks (its tracking), from a date
    natural_key:
      - product_id
      - valid_from
    key_attributes:
      - tracking (none | lot | serial)
      - "removal_strategy (v3: fifo | fefo | manual; default fifo)"
      - "shelf_life_days (v3: sets a lot's expires_on at receipt when the supplier gives none)"
      - set_by
    relationships:
      - -> product (product module)
    master_data: module-owned (append-only); the product itself references product
    reference_table: inv_stocked_product
    note: a product of kind goods with no row is tracking none; the product module has no stock fields and this module never writes them
  - id: lot_link
    meaning: "an output lot made from an input lot (v6, INV-59): the step production adds to the trace"
    natural_key:
      - product_id
      - lot_code
      - input_product_id
      - input_lot_code
      - move_ref
    key_attributes:
      - input_quantity (in the input's base unit)
      - source_kind
      - source_id
    master_data: module-owned (append-only)
    reference_table: inv_lot_link
  - id: lot
    meaning: a batch or a serial number of one product
    natural_key:
      - product_id
      - lot_code
    key_attributes:
      - kind (lot | serial)
      - expires_on
      - received_on
      - "lot_unit_code, lot_numerator, lot_denominator (RESERVED until M7: the lot's own conversion, deferred.batch_uom; NULL)"
      - "catch_unit_code (RESERVED until M7: deferred.catch_weight; NULL)"
    master_data: module-owned
    reference_table: inv_lot
  - id: stock_document
    meaning: "a receipt, a delivery, a return, a transfer or an adjustment: the paper a move is recorded on"
    natural_key: "document_id: derived from its source (rcpt:pur:{receipt_id}, rts:pur:{return_id}, dlv:so:{sales_order_id}:{n}, ret:{delivery document_id}:{n}, int:{warehouse_id}:{client request id}, adj:{count_id}, odoo:{db}:stock.picking:{id}); the number ({warehouse}/IN/00001) is stamped when it is done"
    key_attributes:
      - kind (receipt | delivery | return | transfer | adjustment | opening | issue (v3) | putaway (v3) | type_change (v3) | revaluation (v3))
      - warehouse_id
      - company_code
      - bp_id
      - source_kind
      - source_ref
      - "purpose (v3: sale | free_of_charge | consignment_fill | consignment_issue | cost_centre | scrap | internal_use | subcontract)"
      - cost_centre (v3, issues)
      - rma_ref (v3, returns)
      - expected_arrival_on (v3, transfers between sites)
      - pick_batch_id (v3)
      - number
      - lifecycle
      - done_on
      - done_by
      - requested_by_email
      - requested_by_sub
      - approved_by_email
      - approved_by_sub
      - back_order_of
    relationships:
      - 1..n document_line
      - 0..n stock_move
    master_data: module-owned
    reference_table: inv_document
  - id: document_line
    meaning: what a document expects, picks or receives for one product, in the unit it was written in
    natural_key:
      - document_id
      - line_no
    key_attributes:
      - product_id
      - unit_code
      - unit_numerator
      - unit_denominator
      - quantity_expected
      - source_line_ref (purchase order line or so_line_no)
      - unit_cost (NUMERIC(19,4) per pricing_quantity of pricing_unit_code; receipts only)
      - "pricing_unit_code, pricing_numerator, pricing_denominator, pricing_quantity (v2: purchasing's, receipts only)"
      - "gross_weight, net_weight, weight_unit_code, volume, volume_unit_code (v2: per one of unit_code, copied from product when the line is written; null = unknown)"
      - catch_quantity_expected (RESERVED until M7; NULL)
    master_data: module-owned
    reference_table: inv_document_line
  - id: stock_move
    meaning: a quantity of one product (and lot) that went from one location to another at a moment; the ledger
    natural_key: "move_id: {document_id}:{line_no}:{n}"
    key_attributes:
      - product_id
      - lot_code
      - "stock_type_from, stock_type_to (v3: unrestricted | quality | blocked; equal unless a type change)"
      - "owner_from, owner_to (v3: null = ours, else the supplier's bp_id for consignment stock; a withdrawal changes it)"
      - quantity_base (NUMERIC(19,4) in the product's base unit; always positive)
      - unit_code
      - quantity (in that unit)
      - unit_numerator
      - unit_denominator
      - from_location_id
      - to_location_id
      - company_code
      - moved_on (business date)
      - moved_at
      - value_amount (NUMERIC(18,2))
      - reverses_move_id
      - by
      - "catch_quantity, catch_unit_code (RESERVED until M7: the actual parallel-unit quantity of this move, deferred.catch_weight; NULL)"
      - "conversion_source (RESERVED until M7: product | lot; product)"
    relationships:
      - -> stock_document
      - -> location (from, to)
      - -> lot
    master_data: "module-owned (append-only: never updated or deleted)"
    reference_table: inv_move
  - id: stock_claim
    meaning: the row two writers race for, so only one takes stock out of a place at a time
    natural_key:
      - product_id
      - location_id
      - lot_code
      - stock_type
      - owner
      - claim_no
    key_attributes:
      - move_id or reservation_id
      - quantity_base
      - on_hand_after
    master_data: module-owned (append-only; a plain INSERT, the loser gets 23505, re-reads and is refused or retries)
    reference_table: inv_claim
    note: claim_no is the last claim_no on the key + 1. Every move out of an internal location claims its bin AND its warehouse root (location_id = {warehouse_id}), and every reservation claims the warehouse root, so a reservation and an unreserved delivery collide too
  - id: reservation
    meaning: stock at a warehouse held for a sales order line
    natural_key:
      - sales_order_id
      - so_line_no
      - seq
    key_attributes:
      - warehouse_id
      - product_id
      - quantity_base (signed: a release is negative)
      - revision
      - "schedule_version, confirmed_on, priority (v3: from sales-order's promise)"
      - reason
      - by
      - at
    relationships:
      - -> sales order line (sales-order)
    master_data: module-owned (append-only); reserved per line is the sum of its rows less what its deliveries consumed
    reference_table: inv_reservation
  - id: stock_count
    meaning: one counting of a location subtree, its lines and its decision
    natural_key: "count_id: {warehouse_id}:C-{n}, from the count series"
    key_attributes:
      - location_id (root)
      - "scope (v3: subtree | products), product_ids (v3)"
      - "source (v3: manual | cycle_plan)"
      - lifecycle
      - started_by
      - submitted_by
      - decided_by
      - decided_sub
      - reason
      - value_amount
    relationships:
      - 1..n count_line
    master_data: module-owned
    reference_table: inv_count
  - id: count_line
    meaning: what was found for one product (and lot) in one bin
    natural_key:
      - count_id
      - location_id
      - product_id
      - lot_code
    key_attributes:
      - "counted_base (v2: the exact sum of its entries)"
      - counted_at
      - counted_by
      - counted_sub
      - expected_base (at counted_at)
      - difference_base
      - value_amount
      - suggestion
    master_data: module-owned
    reference_table: inv_count_line
  - id: count_entry
    meaning: one thing the counter wrote for a count line, in the unit they counted in (5 PK24; 6 C62) (v2)
    natural_key:
      - count_id
      - location_id
      - product_id
      - lot_code
      - entry_no
    key_attributes:
      - quantity
      - unit_code
      - unit_numerator
      - unit_denominator
      - quantity_base
      - catch_quantity (RESERVED until M7; NULL)
      - counted_by
      - counted_at
    master_data: module-owned (append-only while counting; a wrong entry is a negative entry)
    reference_table: inv_count_entry
  - id: valuation_row
    meaning: the average cost and value of one product in one company after one move
    natural_key:
      - company_code
      - product_id
      - seq
    key_attributes:
      - "kind (v3: move | revaluation | method_switch)"
      - "method (v3: average | standard)"
      - move_id
      - quantity_base_change
      - value_change (NUMERIC(18,2))
      - quantity_after
      - value_after (NUMERIC(18,2))
      - average_cost_after (NUMERIC(19,4); under standard, the standard price)
      - "price_difference (v3: NUMERIC(18,2), receipts at standard)"
      - moved_on
      - "catch_quantity_change, catch_quantity_after (RESERVED until M7: valuation in the parallel unit; NULL)"
    master_data: module-owned (append-only; seq claimed with a plain INSERT)
    reference_table: inv_valuation
  - id: posting
    meaning: what was asked of the ledger for one document event, and its answer
    natural_key:
      - document_id
      - event
    key_attributes:
      - journal_id (BIGINT derived from document_id and event)
      - status (posted | pending | exported)
      - reason
      - attempts
      - posted_at
    master_data: module-owned
    reference_table: inv_posting
  - id: account_map
    meaning: which ledger account each stock purpose uses, per company, from a date
    natural_key:
      - company_code
      - purpose
      - valuation_class
      - valid_from
    key_attributes:
      - account_id (BIGINT; gl)
    note: "v3 purposes: stock_valuation, stock_received_not_billed, cost_of_goods_sold, inventory_loss, consumption, inventory_scrap, free_of_charge, price_difference, revaluation, consignment_liability, subcontracting; valuation_class (product type's, optional: '*' = every class) lets raw materials and trading goods post to different stock accounts (SAP OBYC by valuation class)"
    master_data: module-owned (configuration; references gl's accounts)
    reference_table: inv_account_map
  - id: number_series
    meaning: the next number of a warehouse's receipts, deliveries, returns, transfers and counts
    natural_key:
      - series_id ({warehouse_id}/IN, /OUT, /RET, /INT, /C, /GI (v3), /PB (v3), SSCC:{company prefix} (v3))
      - number
    key_attributes:
      - document_id
      - claimed_at
    master_data: module-owned (a claim row per number, plain INSERT)
    reference_table: inv_number_series
  - id: migration_map
    meaning: the Odoo record each migrated row came from
    natural_key:
      - odoo_db
      - odoo_model
      - odoo_id
    key_attributes:
      - our_key
      - run_id
    master_data: module-owned
    reference_table: inv_migration_map
  - id: odoo_move_history
    meaning: Odoo's stock moves before the cut-over, kept to read, never part of the ledger
    natural_key:
      - odoo_db
      - odoo_move_line_id
    key_attributes:
      - reference
      - product_id
      - lot_code
      - quantity_base
      - from_location_id
      - to_location_id
      - done_at
      - origin
    master_data: module-owned (read-only after the run)
    reference_table: inv_odoo_history
  - id: expected_return
    meaning: a customer return sales-order authorised (an RMA), what it expects back and what has come (v3)
    natural_key:
      - rma_ref
      - line_no
    key_attributes:
      - sales_order_id
      - bp_id
      - warehouse_id
      - product_id
      - unit_code
      - quantity_base
      - original_delivery_ref
      - serials
      - inspect
      - received_base
      - status (open | received | cancelled)
    master_data: module-owned; written by sales-order's client through POST /expected-returns
    reference_table: inv_expected_return
  - id: inspection
    meaning: what an inspector decided for each unit of a returned line (v3)
    natural_key:
      - document_id
      - line_no
      - decision_no
    key_attributes:
      - decision (restock | scrap | back_to_customer | to_supplier)
      - quantity_base
      - reason
      - inspected_by_email
      - inspected_by_sub
      - reported_to_order (bool)
    master_data: module-owned (append-only)
    reference_table: inv_inspection
  - id: abc_class
    meaning: a product's A, B or C class at a warehouse, from a date (v3)
    natural_key:
      - warehouse_id
      - product_id
      - valid_from
    key_attributes:
      - abc_class
      - consumption_value (NUMERIC(18,2), the last twelve months)
      - cumulative_share
      - source (computed | override)
      - reason
      - set_by
    master_data: module-owned (append-only; computed monthly, overridable with a reason)
    reference_table: inv_abc_class
  - id: putaway_rule
    meaning: where goods of a product or category go when put away at a warehouse (v3)
    natural_key:
      - warehouse_id
      - seq
      - valid_from
    key_attributes:
      - applies_to (product | category | all), target
      - strategy (fixed_bin | addition_to_stock | next_bin_with_room | zone)
      - target_location_id
    master_data: module-owned (configuration, dated)
    reference_table: inv_putaway_rule
  - id: pick_batch
    meaning: deliveries picked together in walking order (v3)
    natural_key: pick_batch_id ({warehouse}/PB/{seq:5}, from the series)
    key_attributes:
      - warehouse_id
      - delivery_document_ids
      - status (open | picked | done)
      - created_by
    master_data: module-owned
    reference_table: inv_pick_batch
  - id: package_type
    meaning: a box, a crate or a pallet we pack into (v3)
    natural_key: package_type_code
    key_attributes:
      - tare_weight, weight_unit_code
      - length, width, height, dimension_unit_code
      - max_weight
    master_data: module-owned (configuration)
    reference_table: inv_package_type
  - id: package
    meaning: one packed box or pallet of a delivery, with its SSCC (v3)
    natural_key: "sscc (18 digits: extension digit, the GS1 company prefix, a serial reference from the series, check digit)"
    key_attributes:
      - document_id
      - package_type_code
      - "contents: [{product_id, lot_code, quantity_base}]"
      - gross_weight
      - weight_unit_code
      - packed_by
      - packed_at
    master_data: "module-owned (the serial reference claimed with a plain INSERT on (company prefix, reference): never reused)"
    reference_table: inv_package
  - id: replenishment_proposal
    meaning: what the nightly run proposed to buy or move for a product at a site, and what became of it (v3)
    natural_key:
      - warehouse_id
      - product_id
      - business_date
    key_attributes:
      - site_row_valid_from
      - on_hand_base, reserved_base, expected_base, projected_base
      - reorder_point, max_stock (as read)
      - proposed_base, rounded (in the purchase unit), unit_code
      - procurement (buy | transfer), supplying_site_id
      - lifecycle
      - request_ref
      - purchase_request_id
      - transfer_document_id
      - decided_by
      - reason
    master_data: module-owned
    reference_table: inv_replenishment_proposal
  - id: standard_price
    meaning: a product's standard cost in one company, from a date (v3)
    natural_key:
      - company_code
      - product_id
      - valid_from
    key_attributes:
      - standard_price (NUMERIC(19,4) per base unit)
      - set_by
      - lifecycle (scheduled | effective)
      - "source_ref (v6: mfg:<rollup_id> for a released roll-up, else null)"
      - set_sub (v6)
    master_data: module-owned (append-only; valid_from after today)
    reference_table: inv_standard_price
  - id: settings
    meaning: how this business keeps stock
    natural_key:
      - key
      - valid_from
    key_attributes:
      - value
      - set_by
    master_data: module-owned (configuration, dated)
    reference_table: inv_settings
  - id: suggestion
    meaning: what an AI step proposed and what a person decided
    natural_key:
      - count_id
      - location_id
      - product_id
      - lot_code
      - step
    key_attributes:
      - text
      - decided (accepted | dismissed)
      - decided_by
      - decided_at
    master_data: module-owned
    reference_table: inv_suggestion
master_data:
  owns:
    - inv_warehouse
    - inv_location
    - inv_stocked_product
    - inv_lot
    - inv_document
    - inv_document_line
    - inv_move
    - inv_claim
    - inv_reservation
    - inv_count
    - inv_count_line
    - inv_count_entry
    - inv_valuation
    - inv_posting
    - inv_account_map
    - inv_number_series
    - inv_migration_map
    - inv_odoo_history
    - inv_settings
    - inv_suggestion
    - inv_expected_return
    - inv_inspection
    - inv_abc_class
    - inv_putaway_rule
    - inv_pick_batch
    - inv_package_type
    - inv_package
    - inv_replenishment_proposal
    - inv_standard_price
  references:
    - entity: product
      owner: product
      how: inv_move.product_id = product.product_id; units and conversions through product's convert route, never prod_ tables
      if_absent: "nothing can be stocked: the module refuses to start without the product module"
    - entity: business_partner
      owner: business-partner
      how: inv_document.bp_id = business_partner.bp_id
      if_absent: receipts and deliveries carry no supplier or customer beyond the order's reference
    - entity: sales_order
      owner: sales-order
      how: inv_reservation.(sales_order_id, so_line_no) and inv_document.source_ref; read through GET /sales-orders/{sales_order_id}
      if_absent: deliveries are raised by hand and nothing is reserved
    - entity: account
      owner: gl
      how: inv_account_map.account_id = the ledger's account_id
      if_absent: "ledger mode export: the month's stock movements and their values are a file for the accountant"
    - entity: product site data (v3)
      owner: product
      how: replenishment and transit days read GET /product-sites and GET /products/{product_id}/sites/{site_id}; never prod_ tables
      if_absent: no replenishment proposals; transfers carry no expected arrival
    - entity: purchase orders and requests (v3)
      owner: purchasing
      how: expected receipts for ATP (GET /expected-receipts), purchase requests from proposals, consignment withdrawals, subcontract receipts
      if_absent: ATP counts stock only; proposals are a list for the buyer
    - entity: cost_centre (v3)
      owner: gl
      how: inv_document.cost_centre validated through gl's cost centre route
      if_absent: a cost centre is a code validated against nothing (shared.yaml keys.cost_centre)
  warning: A quantity kept on the product AND in the warehouse, or a delivery recorded on the order by hand AND shipped from stock, is how stock is counted twice. One ledger of moves; the order hears about a delivery only from it.
jobs:
  - story: INV-30
    trigger: on read
    runs: on hand, reserved and available from inv_move and inv_reservation
    where_options:
      - derived on read
    idempotent: nothing is stored
  - story: INV-31
    trigger: in the same request as the move
    runs: the next valuation row for (company, product)
    where_options:
      - in the same request
    idempotent: "keyed (company_code, product_id, seq) and by move_id: a retried move finds its row and appends nothing"
  - story: INV-32
    trigger: when a document is done, and a retry of pending postings
    runs: post the document event's journal through the ledger's route
    where_options:
      - in the same request
      - the composition's clock worker retrying pending postings (--reserved 1 --max-replicas 1)
      - external scheduler
    idempotent: "journal_id derived from (document_id, event): the ledger lands it once; inv_posting keyed (document_id, event)"
  - story: INV-42
    trigger: first business day of each month
    runs: ABC classification per warehouse
    where_options:
      - the composition's clock worker
      - external scheduler
    idempotent: "rows keyed (warehouse, product, valid_from): a re-run the same day writes nothing"
  - story: INV-44
    trigger: nightly
    runs: replenishment proposals from product's site data
    where_options:
      - the composition's clock worker
      - external scheduler
    idempotent: "keyed (warehouse, product, business date); requests keyed inv:repl:...: a re-run sends nothing more"
  - story: INV-56
    trigger: start of each business day
    runs: standard prices taking effect today, their revaluation rows and journals
    where_options:
      - the composition's clock worker
      - external scheduler
    idempotent: revaluation keyed (company, product, valid_from); journal_id derived from it
  - story: INV-33
    trigger: when a count is submitted
    runs: the variance suggestion
    where_options:
      - in the same request
    idempotent: "keyed per count line and step: re-running replaces nothing a person decided"
seams:
  - story: INV-20
    with: purchasing
    owner: inventory
    direction: inbound
    route: POST /receipts
    request: "{move_ref: \"pur:<receipt_id>:<line_no>\", source_kind: purchase_receipt | consignment_receipt | subcontract_receipt, source_id: receipt_id, purchase_order_id, bp_id (supplier), product_id, quantity (string), unit_code, location_id, received_on (YYYY-MM-DD), unit_cost (string, NUMERIC 19,4, per pricing_quantity of pricing_unit_code; omitted for a consignment receipt; includes planned delivery costs), pricing_unit_code, pricing_numerator, pricing_denominator, pricing_quantity (the order line's, fixed), currency, stock_owner_bp_id (v3, optional: the consigning supplier; the stock is booked supplier-owned, special stock K, with no value to us), consume_provided (v3, optional, a subcontract receipt: [{product_id, quantity (string), unit_code}], the components held at the subcontractor consumed into the finished product), service_fee (v3, with consume_provided: the line's net per pricing unit), delivery_costs (v3, optional: [{kind, amount (string)}], the valuation detail of the landed cost)}"
    response: "201 {move_id, quantity_base, consumed (a subcontract receipt): [{move_id, product_id, quantity_base}]}; 200 the same for a repeated move_ref; 409/422 {gate, reason, fix} when the unit does not convert exactly, the location is not an internal one, the product is not stocked, or a provided component is short at the subcontractor (components_at_subcontractor)"
    permission: inv:receipt:intake
    status: aligned 2026-10-22 with purchasing PUR-25, PUR-53, PUR-58, PUR-62
    rule: called only by purchasing, once per receipt line, after it has recorded the receipt (POST /purchase-orders/{purchase_order_id}/receipts is the one way a receipt is recorded); idempotent on move_ref; inventory converts through product, owns the move and its valuation; purchasing keeps move_id on its receipt line and never writes inv_ tables
  - story: INV-28
    with: purchasing
    owner: inventory
    direction: inbound
    route: POST /returns-to-supplier
    request: '{move_ref: "pur:<return_id>:<line_no>", reverses_move_ref: "pur:<receipt_id>:<line_no>", source_kind: "purchase_return", source_id: return_id, bp_id, product_id, quantity (string, positive, what leaves), unit_code, location_id, returned_on (YYYY-MM-DD)}'
    response: "{move_id, quantity_base}; 409 {gate: on_hand, reason, fix} when the stock is no longer at the location"
    permission: inv:receipt:intake
    status: "aligned 2026-10-22 with purchasing PUR-26; agreed with purchasing (wave 2): purchasing's PUR-26 calls exactly this"
    rule: idempotent on move_ref; valued at the cost of the move it reverses; the return row stands in purchasing whatever the answer, and its hand-over shows the reason
  - story: INV-21
    with: purchasing
    owner: purchasing
    direction: outbound
    route: POST /purchase-orders/{purchase_order_id}/receipts
    request: "{delivery_note, received_on, location_id, lines: [{line_no, quantity, unit_code}]}"
    response: "{receipt_id, lines: [{line_no, quantity, quantity_base, move_ref, stock_move_id}], readiness: [{gate, met, reason, fix}]}"
    permission: purchasing:receipt:write
    status: aligned 2026-10-22 with purchasing PUR-07
    rule: "the ONE way a receipt is recorded; the scanner calls it and never posts a supplier move itself; purchasing posts each line back through POST /receipts (INV-20) before it answers; a repeat with the same delivery note records once; this call: {delivery_note, received_on, location_id, lines: [{line_no, quantity (string), unit_code}]}"
  - story: INV-21
    with: purchasing
    owner: purchasing
    direction: outbound
    route: GET /purchase-orders/{purchase_order_id}/expected
    request: path purchase_order_id
    response: "{purchase_order_id, order_no, bp_id, lines: [{line_no, product_id, unit_code, ordered, received, outstanding, quantity_base_outstanding, expected_on}]}"
    permission: purchasing:order:read_expected
    status: aligned 2026-10-22 with purchasing PUR-25
    rule: the scanner's on_order and within_tolerance gates read what is still to arrive here; inventory keeps no expected-receipt copy
  - story: INV-22
    with: sales-order
    owner: inventory
    direction: inbound
    route: POST /reservations/sales-orders/{sales_order_id}
    request: "{revision: int, warehouse_id (optional, else the company's default warehouse), lines: [{line_no, product_id, unit_code, quantity (string), unit_numerator, unit_denominator}]}"
    response: "{sales_order_id, revision, lines: [{line_no, reserved_base, short_base, base_unit_code, readiness: [{gate: stock_reserved, met, reason, fix}]}]}; v3: the request may carry schedule_version, priority and per line schedule [{confirmed_on, quantity_base}] (sales-order v5 SO-36), keyed (sales_order_id, revision, schedule_version)"
    permission: inv:reservation:intake
    status: "aligned 2026-10-22 with sales-order SO-25; agreed with sales-order v3 (its SO-25 seam): called on confirm and every amendment; erp-brick-sales-order builds it"
    rule: "keyed (sales_order_id, revision): a repeat changes nothing; a later revision sets each line's reservation to its new quantity; lines for services are ignored and named"
  - story: INV-22
    with: sales-order
    owner: inventory
    direction: inbound
    route: POST /reservations/sales-orders/{sales_order_id}/release
    request: "{reason}"
    response: "{sales_order_id, released_base_by_line: [{line_no, quantity_base}]}"
    permission: inv:reservation:intake
    status: "aligned 2026-10-22 with sales-order SO-25; agreed with sales-order v3 (its SO-25 seam): called on cancel"
    rule: releases what is reserved and not yet delivered; a repeat releases nothing more
  - story: INV-22
    with: sales-order
    owner: sales-order
    direction: outbound
    route: GET /sales-orders/{sales_order_id}
    request: "path sales_order_id (the fulfiller view: confirmed orders, no prices)"
    response: "the order as erp-brick-sales-order returns it: lifecycle, revision, lines [{line_no, product_id, unit_code, quantity, unit_numerator, unit_denominator}], deliveries"
    permission: so:order:read
    status: built; aligned 2026-10-22 with sales-order SO-23
    rule: used when a delivery is raised from the order on the Deliveries screen; inventory never reads so_ tables
  - story: INV-23
    with: sales-order
    owner: sales-order
    direction: outbound
    route: POST /sales-orders/{sales_order_id}/deliveries
    request: "{line_no, quantity (string, exact, in the line's unit_code), source: \"inventory\", delivery_ref: \"inv:<delivery number>\", delivered_on (today), corrects_ref (a customer return: the delivery's inv: ref)}"
    response: "the order view (lines with delivered quantities and quantity_base, fulfilment status derived); 409 {gate: stocked_from_inventory | within_ordered | exact_base, reason, fix}"
    permission: so:order:deliver
    status: built; aligned 2026-10-22 with sales-order SO-23
    rule: "called inside the delivery's validation before the moves commit; a refusal refuses the validation; a repeat with the same delivery_ref records once on the order's side, so a retry after a lost answer is safe; this call: {line_no, quantity (string, exact, in the order line's unit_code, up to 4 places; negative for a return), source: \"inventory\", delivery_ref: \"inv:{delivery number}\", delivered_on (today), corrects_ref (for a return: the delivery's inv: ref)}; no version (if_match is optional)"
  - story: INV-24
    with: gl
    owner: gl
    direction: outbound
    route: POST /journal-entry/journals
    request: "{journal_id (BIGINT as string, derived_id(document_id, event)), source_module: \"inventory\", source_document: document_id, event (receipt | delivery | return | adjustment | reversal | issue | revaluation), company_code, journal_date (the move's business date), currency (the company's), memo, lines: [{account_id | purpose (qualified by valuation_class), debit | credit (string, 2 places), cost_centre (a goods issue), memo}]}"
    response: "201 {journal_id, entry_no, period_id, status: posted, replay: false, lines: n}; 200 the same with replay: true; 409 {gate: period_open | journal_conflict, reason, fix}; 422 {gate: balanced | purposes_mapped | ledger_assigned | bounds, reason, fix}"
    permission: gl:journal:post
    status: aligned 2026-10-22 with gl GL-30
    rule: the ledger owns journals; inventory records the answer in inv_posting and retries pending ones; never writes gl_ tables
  - story: INV-24
    with: gl
    owner: gl
    direction: outbound
    route: GET /periods/open
    request: query date=YYYY-MM-DD, company_code (optional; the default company), ledger_id (optional; the leading ledger)
    response: "200 {date, company_code, period_id, open: bool, status: open | closed | none, reason, fix}"
    permission: gl:period:read
    status: aligned 2026-10-22 with gl GL-32
    rule: read before a posting so a closed period is a readiness reason, not a surprise
  - story: INV-25
    with: product
    owner: product
    direction: outbound
    route: GET /products/{product_id}/convert?quantity=&from_unit=&to_unit=
    request: query quantity (string), from_unit, to_unit
    response: "{product_id, from_unit, to_unit, quantity, exact: \"n/d\", converted, in_base_unit, base_unit_code}; 422 when the exact fraction does not fit the target unit's decimals (refused, never rounded)"
    permission: product:product:read
    status: built; aligned 2026-10-22 with product PRD-21
    rule: a conversion whose exact fraction does not fit the target unit's decimals is refused here (not rounded)
  - story: INV-25
    with: product
    owner: product
    direction: outbound
    route: POST /products/{product_id}/units/{unit_code}/used
    request: "{document_ref}"
    response: "{product_id, unit_code, used: true, fixed_by}; 200 the same when already used; 409 {gate: einvoice_unit_code, reason, fix}"
    permission: product:unit:mark_used
    status: built; aligned 2026-10-22 with product PRD-21
    rule: "called once a document line uses a non-base unit; a 409 (no e-invoice unit code) refuses the line with product's reason; this call: {document_ref: document_id}"
  - story: INV-25
    with: product
    owner: product
    direction: outbound
    route: GET /products/{product_id}?on=
    request: "path product_id; query on (default today: the date the measures and roles are read for)"
    response: "{product_id, name, description, kind, product_type_code, stocked_default, valuation_class, tax_category, commodity_code (v3), country_of_origin (v3), base_unit_code, roles {sales, purchase, issue, production, warehouse, delivery}, units: [{unit_code, numerator, denominator, quantity_decimals, gtins: [{gtin, kind}], measures: {gross_weight, net_weight, weight_unit_code, volume, volume_unit_code, length, width, height, dimension_unit_code, valid_from} | null}], lifecycle, version}"
    permission: product:product:read
    status: built (v1 shape); aligned 2026-10-22 with product PRD-28
    rule: a service is never stocked; an archived product may still be received back or counted, never newly reserved
  - story: INV-27
    with: sales-order
    owner: inventory
    direction: inbound
    route: GET /availability/{product_id}?warehouse_id=
    request: product_id, optional warehouse_id
    response: "{product_id, base_unit_code, warehouses: [{warehouse_id, on_hand, reserved, available, in_transit_in}]}"
    permission: inv:availability:read
    status: proposed
    rule: no bins, no lots, no value in this answer
  - story: INV-27
    with: manufacturing
    owner: inventory
    direction: inbound
    route: GET /availability/{product_id}?warehouse_id=
    request: product_id, optional warehouse_id
    response: "{product_id, base_unit_code, warehouses: [{warehouse_id, on_hand, reserved, available, in_transit_in}]}"
    permission: inv:availability:read
    rule: no bins, no lots, no value in this answer
    status: "inventory v7 2026-10-26 (spec gaps wave 4): listed for manufacturing MFG-06, MFG-10"
  - story: INV-27
    with: sales-order
    owner: inventory
    direction: inbound
    route: GET /valuation/products/{product_id}?company_code=&as_of=
    request: product_id, company_code, optional as_of date
    response: "{product_id, company_code, quantity_base, value_amount, average_cost (NUMERIC 19,4 as a string), as_of}"
    permission: inv:valuation:read
    status: proposed
    rule: the margin a sales or invoicing screen shows reads this, not product.cost_amount, once inventory is installed
  - story: INV-27
    with: manufacturing
    owner: inventory
    direction: inbound
    route: GET /valuation/products/{product_id}?company_code=&as_of=
    request: product_id, company_code, optional as_of date
    response: "{product_id, company_code, quantity_base, value_amount, average_cost (NUMERIC 19,4 as a string), as_of}"
    permission: inv:valuation:read
    rule: the margin a sales or invoicing screen shows reads this, not product.cost_amount, once inventory is installed
    status: "inventory v7 2026-10-26 (spec gaps wave 4): listed for manufacturing MFG-06, MFG-10"
  - story: INV-26
    with: business-partner
    owner: business-partner
    direction: outbound
    route: GET /migration-map/{db}/{model}?ids=
    request: path db, model (res.partner); query ids=<comma-separated Odoo ids>
    response: "[{odoo_model, odoo_id, ours}]; an id not migrated is omitted"
    permission: bp:migration:read
    status: the one map route (shared.yaml conventions.odoo_migration.map_route)
    rule: Odoo ids resolve through the earlier brick's map, never by matching names; the same route on product (product.product, uom.uom), sales-order (sale.order, sale.order.line) and purchasing (purchase.order.line, for a receipt line's cost)
  - story: INV-26
    with: gl
    owner: inventory
    direction: inbound
    route: GET /migration-map/{db}/{model}?ids=
    request: path db, model (stock.warehouse, stock.location, stock.lot, stock.picking); query ids=<comma-separated Odoo ids>
    response: "[{odoo_model, odoo_id, ours}]; an id not migrated is omitted"
    permission: inv:migration:read
    status: the one map route (shared.yaml conventions.odoo_migration.map_route)
    rule: read from inv_migration_map; later bricks resolve Odoo stock ids through it, never by names
  - story: INV-49
    with: sales-order
    owner: inventory
    direction: inbound
    route: GET /atp/{product_id}?warehouse_id=&quantity=&unit_code=&requested_on=&min_shelf_life_days=&exclude_sales_order_id=
    permission: inv:availability:read
    request: "query: warehouse_id, quantity (string, in unit_code), unit_code, requested_on (material availability date wanted), min_shelf_life_days, exclude_sales_order_id (its own reservation, on a re-promise)"
    response: "{product_id, base_unit_code, available_now, confirmations: [{available_on, quantity_base}], shortfall_base, sources: [{kind (on_hand | purchase | transit), ref, on, quantity_base}], pick_pack_days}"
    status: aligned 2026-10-22 with sales-order SO-35; agreed with sales-order v5 (SO-35)
    rule: derived on read, nothing reserved; unrestricted stock (ours and supplier consignment) less dated reservations, plus purchasing's expected receipts after the site's goods-in days and transfers by expected arrival; never quality, blocked, customer-consignment or subcontractor stock, nor a lot expiring within the minimum shelf life of its date
  - story: INV-49
    with: purchasing
    owner: purchasing
    direction: outbound
    route: GET /expected-receipts?product_id=&warehouse_id=
    permission: purchasing:order:read_expected
    request: query product_id, warehouse_id
    response: 200 [{purchase_order_id, line_no, expected_on, quantity_base_outstanding, special_stock}]
    status: aligned 2026-10-22 with purchasing PUR-25
    rule: ATP and replenishment read what is still to arrive here; inventory keeps no copy
  - story: INV-14
    with: sales-order
    owner: inventory
    direction: inbound
    route: POST /expected-returns
    permission: inv:return:expect
    request: "{rma_ref: so:{sales_order_id}, bp_id, warehouse_id, lines: [{line_no, product_id, unit_code, quantity, unit_numerator, unit_denominator, original_delivery_ref, serials, inspect}]}; serials (optional, v5) = [serial], the serial numbers the customer says are coming back, copied by sales-order from the delivery it is reversing (GET /serials/{product_id}/{serial} lists what inventory delivered); empty or absent when the product is not serial-managed; each is checked against that customer's deliveries at receipt (serial_was_delivered), not at registration"
    request_schema:
      - field: rma_ref
        type: rma_ref
        required: true
      - field: bp_id
        type: bp_id
        required: true
      - field: warehouse_id
        type: warehouse_id
        required: true
      - field: lines
        type: array
        required: true
        items:
          - field: line_no
            type: integer
            required: true
          - field: product_id
            type: product_id
            required: true
          - field: unit_code
            type: unit_code
            required: true
          - field: quantity
            type: decimal
            required: true
          - field: unit_numerator
            type: integer
            required: false
          - field: unit_denominator
            type: integer
            required: false
          - field: original_delivery_ref
            type: string
            required: false
          - field: serials
            type: array
            required: false
            items:
              - serial
          - field: inspect
            type: boolean
            required: false
    response: "{rma_ref, expected: [{line_no, quantity_base}]}"
    status: aligned 2026-10-22 with sales-order SO-41
    rule: idempotent on rma_ref; POST /expected-returns/{rma_ref}/cancel withdraws it while nothing is received; a customer return is received only against an open RMA
  - story: INV-14
    with: sales-order
    owner: sales-order
    direction: outbound
    route: POST /sales-orders/{sales_order_id}/return-inspections
    permission: so:return:inspect
    request: "{line_no, inspection_ref (inv:<return number>:<line>), received_quantity, accepted_quantity, rejected_quantity, decision (restock | scrap | to_supplier), reason, inspected_on}"
    response: the returns line {received, accepted, rejected, credited} and the order's readiness
    status: aligned 2026-10-22 with sales-order SO-49; agreed with sales-order v5 (SO-49)
    rule: "called once per inspected return line after the receipt was recorded on the returns order (POST /sales-orders/{sales_order_id}/deliveries, source inventory); a repeat records once; this call: {line_no, inspection_ref: inv:<return number>:<line>, received_quantity, accepted_quantity, rejected_quantity, decision, reason, inspected_on}"
  - story: INV-23
    with: sales-order
    owner: sales-order
    direction: outbound
    route: GET /sales-orders/{sales_order_id}/fulfilment
    permission: so:order:read
    request: "path sales_order_id (the fulfiller view: no prices)"
    response: "{sales_order_id, order_type_code, item categories per line, priority, ship_to_bp_id, ship_to_address, warehouse_id per line, partial_delivery, max_partials, under_tolerance_pct, over_tolerance_pct, combine_allowed, special_stock (none | to_consignment | from_consignment), purpose (sale | free_of_charge | consignment), schedule (latest version per line), delivery_blocked {met, reasons: [{gate, reason, fix}]}, min_remaining_shelf_life_days}"
    status: aligned 2026-10-22 with sales-order SO-37; agreed with sales-order v5 (SO-37)
    rule: "read when a delivery is raised and again at validation; a delivery block keeps it off the pick list; the purpose and special stock decide the target location and the account; this call: path sales_order_id"
  - story: INV-45
    with: sales-order
    owner: inventory
    direction: inbound
    route: GET /consignment-stock/customers/{bp_id}?product_id=
    permission: inv:availability:read
    request: path bp_id; query product_id
    response: "{bp_id, products: [{product_id, base_unit_code, on_hand_base, location_id}]}"
    status: aligned 2026-10-22 with sales-order SO-45; agreed with sales-order v5 (SO-45)
    rule: consignment stock at a customer is ours, valued, never available; sales-order gates its CONS_ISSUE, CONS_PICKUP and CONS_RETURN on it
  - story: INV-44
    with: product
    owner: product
    direction: outbound
    route: GET /product-sites?site_id=&planning=&on=
    permission: product:product:read
    request: "query: site_id (warehouse_id), planning (active = planning_method not none), on (default today)"
    response: "[{product_id, site_id, valid_from, site_status, procurement_type, supplying_site_id, planned_delivery_days, gr_processing_days, planning_method, reorder_point, safety_stock, max_stock, lot_size_method, fixed_lot_size, rounding_profile_code, base_unit_code, purchase_unit_code}] paged by product_id"
    status: aligned 2026-10-22 with product PRD-39; agreed with product v3
    rule: "the parameters stay product's; a proposal records the row's valid_from and the figures it used; this call: GET /product-sites?site_id=&planning=active&on=; this call: query site_id (warehouse_id), planning active, on (the business date)"
  - story: INV-44
    with: product
    owner: product
    direction: outbound
    route: GET /products/{product_id}/round-proposal?site_id=&quantity=&unit_code=&on=
    permission: product:product:read
    request: "query: site_id (its rounding profile), quantity (string, the proposal), unit_code, on"
    response: "{product_id, proposed, rounded, unit_code, steps_applied: [{multiple, round_up_pct, result}], purchase_rule {met, reason}}"
    status: aligned 2026-10-22 with product PRD-38; agreed with product v3 (PRD-38)
    rule: "a proposal is always rounded here; a person's changed quantity is checked against the purchase rule only; this call: the proposed quantity in the purchase unit"
  - story: INV-54
    with: purchasing
    owner: purchasing
    direction: outbound
    route: POST /purchase-requests/from-replenishment
    permission: purchasing:request:intake
    request: "{request_ref: inv:repl:{warehouse_id}:{product_id}:{business_date}, product_id, quantity, unit_code (the purchase unit), warehouse_id, location_id (its goods-in), needed_by, reason}"
    response: "201 {request_ref, request_id, status: awaiting_approval}; 200 the same for the same request_ref; 422 {gate: purchasable, reason, fix}"
    status: aligned 2026-10-22 with purchasing PUR-65
    rule: idempotent on request_ref; purchasing approves and orders by its own rules; the proposal keeps request_id and counts it as expected until purchasing reports it ordered or cancelled
  - story: INV-46
    with: purchasing
    owner: purchasing
    direction: outbound
    route: POST /consignment-withdrawals
    permission: purchasing:consignment:intake
    request: "{move_ref: \"inv:{document_id}:{line_no}\", bp_id (the consigning supplier), product_id, quantity (string), unit_code, withdrawn_on (YYYY-MM-DD, the move's date)}"
    response: "201 {withdrawal_id, move_ref, unit_price (NUMERIC 19,4), pricing_unit_code, pricing_numerator, pricing_denominator, pricing_quantity, amount, currency}; 200 the same with replay: true; 409 {gate: consignment_price, reason, fix}"
    status: aligned 2026-10-22 with purchasing PUR-54
    rule: called inside the validation that takes consignment stock into our ownership; the answer values the withdrawal move; a refusal refuses the validation and nothing moves; idempotent on withdrawal_ref
  - story: INV-47
    with: purchasing
    owner: inventory
    direction: inbound
    route: POST /receipts
    permission: inv:receipt:intake
    request: "{move_ref: \"pur:<receipt_id>:<line_no>\", source_kind: purchase_receipt | consignment_receipt | subcontract_receipt, source_id: receipt_id, purchase_order_id, bp_id (supplier), product_id, quantity (string), unit_code, location_id, received_on (YYYY-MM-DD), unit_cost (string, NUMERIC 19,4, per pricing_quantity of pricing_unit_code; omitted for a consignment receipt; includes planned delivery costs), pricing_unit_code, pricing_numerator, pricing_denominator, pricing_quantity (the order line's, fixed), currency, stock_owner_bp_id (v3, optional: the consigning supplier; the stock is booked supplier-owned, special stock K, with no value to us), consume_provided (v3, optional, a subcontract receipt: [{product_id, quantity (string), unit_code}], the components held at the subcontractor consumed into the finished product), service_fee (v3, with consume_provided: the line's net per pricing unit), delivery_costs (v3, optional: [{kind, amount (string)}], the valuation detail of the landed cost)}"
    response: "201 {move_id, quantity_base, consumed (a subcontract receipt): [{move_id, product_id, quantity_base}]}; 200 the same for a repeated move_ref; 409/422 {gate, reason, fix} when the unit does not convert exactly, the location is not an internal one, the product is not stocked, or a provided component is short at the subcontractor (components_at_subcontractor)"
    status: aligned 2026-10-22 with purchasing PUR-25, PUR-53, PUR-58, PUR-62
    rule: a supplier-consignment line is received with its owner and no value; a subcontract receipt consumes the named components from the subcontractor's location and values the product at their value plus the service; idempotent on move_ref
  - story: INV-37
    with: gl
    owner: gl
    direction: outbound
    route: GET /cost-centres/{cost_centre}
    permission: gl:cost_centre:read
    request: path cost_centre
    response: "200 {cost_centre, name, status: open | closed, company_code}; 404 when unknown"
    status: aligned 2026-10-22 with gl GL-61
    rule: the cost_centre_valid gate reads it; the journal line carries the cost centre
  - story: INV-01
    with: product
    owner: inventory
    direction: inbound
    route: GET /warehouses/{warehouse_id}
    permission: inv:stock:read
    request: path warehouse_id
    response: "{warehouse_id, company_code, status}"
    status: aligned 2026-10-22 with product PRD-39; agreed with product v3 (its set_site_data check)
    rule: product validates a site row's site and supplying site here
  - story: INV-01
    with: pos
    owner: inventory
    direction: inbound
    route: GET /warehouses/{warehouse_id}
    permission: inv:stock:read
    request: path warehouse_id
    response: "{warehouse_id, company_code, status}"
    rule: product validates a site row's site and supplying site here
    status: "inventory v7 2026-10-26 (spec gaps wave 4): listed for pos (a shop's warehouse is validated here)"
  - story: INV-40
    with: crm
    owner: inventory
    direction: inbound
    route: GET /serials/{product_id}/{serial}
    permission: inv:stock:read
    request: path product_id, serial
    response: "{product_id, code, kind, history: [{moved_at, document_id, from_location_id, to_location_id, bp_id, quantity_base}], on_hand: [{location_id, stock_type, quantity_base}], delivered_to: [{bp_id, document_id, quantity_base}]}"
    status: "proposed (v7, 2026-10-26: the combined serials-and-lots row split in two, one route per row, so the contract check can read each)"
    rule: derived from moves; service and warranty screens read serials here, never inv_ tables
  - story: INV-40
    with: crm
    owner: inventory
    direction: inbound
    route: GET /lots/{product_id}/{lot_code}/trace
    permission: inv:stock:read
    request: path product_id, lot_code
    response: "{product_id, code, kind, history: [{moved_at, document_id, from_location_id, to_location_id, bp_id, quantity_base}], on_hand: [{location_id, stock_type, quantity_base}], delivered_to: [{bp_id, document_id, quantity_base}]}"
    status: "proposed (v7, 2026-10-26: split from the serials row)"
    rule: derived from moves; a recall reads the lot here, never inv_ tables
  - story: INV-40
    with: manufacturing
    owner: inventory
    direction: inbound
    route: GET /lots/{product_id}/{lot_code}/trace
    permission: inv:stock:read
    request: path product_id, lot_code
    response: "{product_id, code, kind, history: [{moved_at, document_id, from_location_id, to_location_id, bp_id, quantity_base}], on_hand: [{location_id, stock_type, quantity_base}], delivered_to: [{bp_id, document_id, quantity_base}]}"
    status: "v7 2026-10-26 (spec gaps wave 4): listed for manufacturing MFG-16 (genealogy: where an output lot went; the input lots' suppliers are the bp_ids in each input lot's history)"
    rule: derived from moves; manufacturing keeps the genealogy (which input lots went into which output lot) and reads where each lot went here
  - story: INV-25
    with: product
    owner: product
    direction: outbound
    route: GET /gtin/{gtin}
    permission: product:product:read
    request: path gtin (8, 12, 13 or 14 digits; left-padded to 14)
    response: "{gtin, product_id, unit_code, kind (main | additional), status, quantity_base, base_unit_code}; 404 for a GTIN never issued; a retired GTIN answers status retired and is refused for a new line by the caller"
    rule: the scanner resolves every barcode here; it never keeps its own barcode table
    status: built; aligned 2026-10-22 with product PRD-27
  - story: INV-47
    with: purchasing
    owner: inventory
    direction: inbound
    route: POST /subcontract-provisions
    permission: inv:receipt:intake
    request: '{move_ref: "pur:<purchase_order_id>:<line_no>:prov:<seq>", purchase_order_id, line_no, bp_id (the subcontractor), from_location_id, components: [{product_id, quantity (string), unit_code}], provided_on (YYYY-MM-DD)}'
    response: "201 {move_id, components: [{product_id, quantity_base}]}; 200 the same for a repeated move_ref; 409 {gate: on_hand, reason, fix} when a component is short"
    rule: "transition provide_to_subcontractor: the components move from our location to stock held at the supplier (still ours, special stock O, valued as before); idempotent on move_ref; purchasing never writes inv_ tables"
    status: aligned 2026-10-22 with purchasing PUR-57
  - story: INV-57
    with: purchasing
    owner: inventory
    direction: inbound
    route: POST /valuation-adjustments
    permission: inv:valuation:post
    request: "{adjustment_ref: \"pur:<bill_id>:<line_no>\", source_kind: purchase_delivery_cost, purchase_order_id, receipt_id, product_id, amount (string, signed), currency, on (the bill's date)}"
    response: 201 {adjustment_ref, on_hand_amount, price_difference_amount}; 200 the same for a repeated adjustment_ref
    rule: the difference is spread over what is still on hand from that receipt and the rest posts to price difference; idempotent on adjustment_ref; inv:valuation:post is a machine grant on purchasing's client
    status: aligned 2026-10-22 with purchasing PUR-63
  - story: INV-01
    with: purchasing
    owner: inventory
    direction: inbound
    route: GET /locations
    permission: inv:stock:read
    request: query usage (internal | receiving), warehouse_id (optional)
    response: "{locations: [{location_id, warehouse_id, name, usage, default: bool}]}"
    rule: the receipt screen's location picker (usage receiving)
    status: aligned 2026-10-22 with purchasing PUR-07
  - story: INV-01
    with: pos
    owner: inventory
    direction: inbound
    route: GET /locations
    permission: inv:stock:read
    request: query usage (internal | receiving), warehouse_id (optional)
    response: "{locations: [{location_id, warehouse_id, name, usage, default: bool}]}"
    rule: the receipt screen's location picker (usage receiving)
    status: "inventory v7 2026-10-26 (spec gaps wave 4): listed for pos (a shop's stock location)"
  - story: INV-01
    with: fixed-assets
    owner: inventory
    direction: inbound
    route: GET /locations
    permission: inv:stock:read
    request: query usage (internal | receiving), warehouse_id (optional)
    response: "{locations: [{location_id, warehouse_id, name, usage, default: bool}]}"
    rule: the location picker on the asset master and the count (usage internal); without inventory a site code is free text
    status: aligned 2026-10-22 with fixed-assets FA-25
  - story: INV-14
    with: sales-order
    owner: inventory
    direction: inbound
    route: POST /expected-returns/{rma_ref}/cancel
    permission: inv:return:expect
    request: path rma_ref (so:{sales_order_id}); no body
    request_schema:
      - field: rma_ref
        type: rma_ref
        required: true
        in: path
    response: '200 {rma_ref, status: cancelled}; a repeat answers the same; 422 {gate: rma_received, reason: "<rma_ref> is partly received: it can no longer be cancelled"}; 422 when no such RMA'
    rule: withdraws every line of the RMA while nothing of it is received; a cancelled RMA no longer lets a return be received against it (rma_open)
    status: added 2026-10-24, seam-gap PR 2
  - story: INV-58
    with: pos
    owner: inventory
    direction: inbound
    route: POST /goods-issues/from-source
    permission: inv:issue:intake
    request: "{source_kind: pos_sale, source_id: receipt_id, company_code, location_id (the shop's consumption location), issued_on (the business date), lines: [{move_ref: \"pos:<receipt_id>:<line_no>:<component_no>\", product_id, quantity (string), unit_code, lot_code (optional)}]}"
    request_schema:
      - field: source_kind
        type: string
        required: true
        values:
          - pos_sale
      - field: source_id
        type: string
        required: true
      - field: company_code
        type: company_code
        required: true
      - field: location_id
        type: location_id
        required: true
      - field: issued_on
        type: date
        required: true
      - field: lines
        type: array
        required: true
        items:
          - field: move_ref
            type: string
            required: true
          - field: product_id
            type: product_id
            required: true
          - field: quantity
            type: decimal
            required: true
          - field: unit_code
            type: unit_code
            required: true
          - field: lot_code
            type: lot_code
            required: false
    response: "201 {issue_id, moves: [{move_ref, move_id, quantity_base, value (string, NUMERIC 18,2)}]}; 200 the same for known move_refs; 422 {gate: units_exact | bounds, reason, fix}"
    rule: "transition issue_from_source (INV-58): never refused for stock (the sale happened; a negative location is listed for the stock controller); inventory posts cost_of_sales / stock_valuation itself and answers each move's value, which pos keeps for its margin; idempotent on move_ref; pos never writes inv_ tables"
    status: added 2026-10-25 (v6) for pos v1 POS-27
  - story: INV-58
    with: manufacturing
    owner: inventory
    direction: inbound
    route: POST /goods-issues/from-source
    permission: inv:issue:intake
    request: '{source_kind: production_issue, source_id: production_order_id, company_code, location_id, issued_on, account_purpose: wip, lines: [{move_ref: "mfg:<production_order_id>:issue:<line_no>:<seq>", product_id, quantity (string), unit_code, lot_code (optional)}]}'
    request_schema:
      - field: source_kind
        type: string
        required: true
        values:
          - production_issue
      - field: source_id
        type: production_order_id
        required: true
      - field: company_code
        type: company_code
        required: true
      - field: location_id
        type: location_id
        required: true
      - field: issued_on
        type: date
        required: true
      - field: account_purpose
        type: string
        required: true
        values:
          - wip
      - field: lines
        type: array
        required: true
        items:
          - field: move_ref
            type: string
            required: true
          - field: product_id
            type: product_id
            required: true
          - field: quantity
            type: decimal
            required: true
          - field: unit_code
            type: unit_code
            required: true
          - field: lot_code
            type: lot_code
            required: false
    response: "201 {issue_id, moves: [{move_ref, move_id, quantity_base, lot_code, value (string, NUMERIC 18,2)}]}; 200 the same for known move_refs; 409 {gate: on_hand, reason, fix}; 422 {gate: units_exact | bounds, reason, fix}"
    rule: transition issue_from_source (INV-58); posts wip / stock_valuation (the account map's purpose wip, qualified by valuation class); answers each move's value and lot so manufacturing's WIP and genealogy need no read of inv_ tables; a reversal is a pos_refund_restock-like receipt with source_kind production_receipt naming reverses_move_ref
    status: added 2026-10-25 (v6) for manufacturing v1 MFG-20
  - story: INV-58
    with: manufacturing
    owner: inventory
    direction: inbound
    route: POST /goods-issues/from-source
    permission: inv:issue:intake
    request: '{source_kind: production_output_reversal, source_id: production_order_id, company_code, location_id, issued_on, account_purpose: wip, lines: [{move_ref: "<the output or by-product move_ref>:reverse", reverses_move_ref, product_id, quantity (string), unit_code, lot_code (the output lot)}]}'
    request_schema:
      - field: source_kind
        type: string
        required: true
        values:
          - production_output_reversal
      - field: source_id
        type: production_order_id
        required: true
      - field: company_code
        type: company_code
        required: true
      - field: location_id
        type: location_id
        required: true
      - field: issued_on
        type: date
        required: true
      - field: account_purpose
        type: string
        required: true
        values:
          - wip
      - field: lines
        type: array
        required: true
        items:
          - field: move_ref
            type: string
            required: true
          - field: reverses_move_ref
            type: string
            required: true
          - field: product_id
            type: product_id
            required: true
          - field: quantity
            type: decimal
            required: true
          - field: unit_code
            type: unit_code
            required: true
          - field: lot_code
            type: lot_code
            required: false
    response: "201 {issue_id, moves: [{move_ref, move_id, quantity_base, lot_code, value (string, NUMERIC 18,2)}]}; 200 the same for known move_refs; 409 {gate: on_hand | already_reversed, reason, fix}; 422 {gate: units_exact | reverses_known | bounds, reason, fix}"
    rule: "v7 (2026-10-26, spec gaps wave 4): the reversal of an output or by-product receipt (no route took output back out; erp-brick-manufacturing refused it with output_not_reversible). Valued at the reversed move's own value, never today's cost; debit wip / credit stock_valuation; the lot link of the reversed receipt is kept and marked reversed, so the trace shows both"
    status: added 2026-10-26 (inventory v7) for manufacturing v2 MFG-20 reverse_entry
  - story: INV-59
    with: manufacturing
    owner: inventory
    direction: inbound
    route: POST /receipts
    permission: inv:receipt:intake
    request: "{move_ref: \"mfg:<production_order_id>:output:<seq>\" | \"mfg:<production_order_id>:byproduct:<line_no>:<seq>\", source_kind: production_receipt | by_product_receipt, source_id: production_order_id, company_code, product_id, quantity (string), unit_code, location_id, received_on (YYYY-MM-DD), lot_code (the new output lot), unit_cost (string, NUMERIC 19,4 per base unit: standard, the order's actual cost on an average-cost company, or net realisable value for a by-product), currency, reverses_move_ref (optional: a correction of an earlier output), input_lots: [{product_id, lot_code, quantity (string, base unit)}]}"
    request_schema:
      - field: move_ref
        type: string
        required: true
      - field: source_kind
        type: string
        required: true
        values:
          - production_receipt
          - by_product_receipt
      - field: source_id
        type: production_order_id
        required: true
      - field: company_code
        type: company_code
        required: true
      - field: product_id
        type: product_id
        required: true
      - field: quantity
        type: decimal
        required: true
      - field: unit_code
        type: unit_code
        required: true
      - field: location_id
        type: location_id
        required: true
      - field: received_on
        type: date
        required: true
      - field: lot_code
        type: lot_code
        required: false
      - field: unit_cost
        type: decimal
        required: true
      - field: currency
        type: currency
        required: true
      - field: reverses_move_ref
        type: string
        required: false
      - field: input_lots
        type: array
        required: false
        items:
          - field: product_id
            type: product_id
            required: true
          - field: lot_code
            type: lot_code
            required: true
          - field: quantity
            type: decimal
            required: true
    response: "201 {move_id, quantity_base, value (string, NUMERIC 18,2)}; 200 the same for a repeated move_ref; 422 {gate: units_exact | location_internal | lot_required, reason, fix}"
    rule: "transition receive_from_source (INV-59): stock_valuation / wip; a lot link per input lot (lot_link), so the trace (INV-40) walks through production; purchasing's source kinds and rules are unchanged"
    status: added 2026-10-25 (v6) for manufacturing v1 MFG-20
  - story: INV-59
    with: pos
    owner: inventory
    direction: inbound
    route: POST /receipts
    permission: inv:receipt:intake
    request: "{move_ref: \"pos:<refund_receipt_id>:<line_no>:<component_no>\", source_kind: pos_refund_restock, source_id: refund receipt_id, company_code, product_id, quantity (string), unit_code, location_id (the shop's), received_on (the business date), reverses_move_ref: \"pos:<original receipt_id>:<line_no>:<component_no>\", lot_code (optional)}"
    request_schema:
      - field: move_ref
        type: string
        required: true
      - field: source_kind
        type: string
        required: true
        values:
          - pos_refund_restock
      - field: source_id
        type: string
        required: true
      - field: company_code
        type: company_code
        required: true
      - field: product_id
        type: product_id
        required: true
      - field: quantity
        type: decimal
        required: true
      - field: unit_code
        type: unit_code
        required: true
      - field: location_id
        type: location_id
        required: true
      - field: received_on
        type: date
        required: true
      - field: reverses_move_ref
        type: string
        required: true
      - field: lot_code
        type: lot_code
        required: false
    response: "201 {move_id, quantity_base, value}; 200 the same for a repeated move_ref; 422 {gate: reverses_known | within_issued, reason, fix}"
    rule: "transition receive_from_source (INV-59): valued at the cost the reversed move left at (no unit_cost is sent), credits cost_of_sales; never more than that move issued; a refund that is not restocked sends nothing"
    status: added 2026-10-25 (v6) for pos v1 POS-11
  - story: INV-57
    with: manufacturing
    owner: inventory
    direction: inbound
    route: POST /valuation-adjustments
    permission: inv:valuation:post
    request: '{adjustment_ref: "mfg:<production_order_id>:settle:<n>", source_kind: production_settlement, production_order_id, company_code, product_id (the output), amount (string, NUMERIC 18,2, signed: positive when the order cost more), currency, on (the close date)}'
    request_schema:
      - field: adjustment_ref
        type: string
        required: true
      - field: source_kind
        type: string
        required: true
        values:
          - production_settlement
      - field: production_order_id
        type: production_order_id
        required: true
      - field: company_code
        type: company_code
        required: true
      - field: product_id
        type: product_id
        required: true
      - field: amount
        type: decimal
        required: true
      - field: currency
        type: currency
        required: true
      - field: on
        type: date
        required: true
    response: "201 {adjustment_ref, on_hand_amount, cost_of_sales_amount}; 200 the same for a repeated adjustment_ref; 422 {gate: values_at_average, reason, fix}"
    rule: "v6: on an average-cost company the order's variance is spread over what is still on hand from the order's output receipts (on_hand_amount, into stock value) and the rest to cost_of_sales (the output already sold), journal against wip; a standard-cost company is refused (gate values_at_average): manufacturing posts its variances to gl itself (MFG-15); idempotent on adjustment_ref"
    status: added 2026-10-25 (v6) for manufacturing v1 MFG-15
  - story: INV-60
    with: manufacturing
    owner: inventory
    direction: inbound
    route: POST /standard-prices
    permission: inv:standard_price:intake
    request: '{company_code, product_id, valid_from (after today), standard_price (string, NUMERIC 19,4 per base unit), source_ref: "mfg:<rollup_id>", released_by (email), released_sub}'
    request_schema:
      - field: company_code
        type: company_code
        required: true
      - field: product_id
        type: product_id
        required: true
      - field: valid_from
        type: date
        required: true
      - field: standard_price
        type: decimal
        required: true
      - field: source_ref
        type: string
        required: true
      - field: released_by
        type: string
        required: true
      - field: released_sub
        type: string
        required: true
    response: "201 {company_code, product_id, valid_from, standard_price, lifecycle: scheduled}; 200 the same for the same (company_code, product_id, valid_from, source_ref); 409 {gate: standard_price_taken, reason, fix}; 422 {gate: starts_after_today | values_at_standard, reason, fix}"
    rule: transition intake_standard_price (INV-60); revalued on valid_from by apply_standard_price (INV-48); manufacturing's second-person release is the approval, inventory does not ask again
    status: added 2026-10-25 (v6) for manufacturing v1 MFG-07
  - story: INV-61
    with: manufacturing
    owner: manufacturing
    direction: outbound
    route: GET /dependent-requirements?product_id=&warehouse_id=&from=&to=
    permission: mfg:plan:read_requirements
    request: "query product_id, warehouse_id, from, to (YYYY-MM-DD: the business date and the end of the replenishment horizon)"
    request_schema:
      - field: product_id
        type: product_id
        required: true
        in: query
      - field: warehouse_id
        type: warehouse_id
        required: true
        in: query
      - field: from
        type: date
        required: true
        in: query
      - field: to
        type: date
        required: true
        in: query
    response: "200 {product_id, warehouse_id, requirements: [{required_on, quantity (string, base unit), source: planned | released, production_order_id (released only)}]}"
    rule: propose_replenishment subtracts the requirements in the horizon from projected available (INV-61); a make or mrp product is not proposed; inventory never reads mfg_ tables
    status: "added 2026-10-25 (v6): the caller side of manufacturing v1 MFG-27"
tool_names:
  - tool: set_inventory_account_map
    route: POST /account-map
    was: set_account_map
  - tool: get_inventory_account_map
    route: GET /account-map
    was: get_account_map
  - tool: sign_inventory_migration
    route: POST /migration/odoo/sign
    was: sign_odoo_run
  - tool: list_inventory_migration_runs
    route: GET /migration/odoo/history
    was: list_odoo_history
  - tool: reconcile_inventory_migration
    route: GET /migration/odoo/reconcile
    was: reconcile_odoo_stock
screens:
  - id: stock
    name: Stock
    stories:
      - INV-03
      - INV-04
      - INV-15
      - INV-40
      - INV-41
      - INV-55
    actors:
      - warehouse_manager
      - stock_operator
      - sales_rep
    note: "v3: on hand by stock type and owner (ours, a supplier's consignment); serial history and lot trace; type changes and lot blocks"
  - id: receipts
    name: Receipts
    stories:
      - INV-05
      - INV-06
      - INV-14
      - INV-46
      - INV-50
    actors:
      - stock_operator
      - warehouse_manager
    note: "v3: returns against RMAs with their inspection; putaway proposals from goods-in"
  - id: deliveries
    name: Deliveries
    stories:
      - INV-07
      - INV-08
      - INV-13
      - INV-35
      - INV-39
      - INV-51
      - INV-52
    actors:
      - stock_operator
      - warehouse_manager
    note: "v3: the pick list by lot (FEFO / FIFO) and pick sequence, pick batches, packing into SSCC packages"
  - id: transfers
    name: Transfers
    stories:
      - INV-09
      - INV-53
    actors:
      - warehouse_manager
      - stock_operator
  - id: counts
    name: Counts
    stories:
      - INV-10
      - INV-11
      - INV-12
      - INV-34
      - INV-43
    actors:
      - warehouse_manager
      - stock_operator
      - stock_controller
    note: "v3: the cycle count plan by ABC class"
  - id: issues
    name: Issues
    stories:
      - INV-37
      - INV-38
    actors:
      - stock_operator
      - warehouse_manager
      - stock_controller
    note: "v3: goods issues to cost centres and scrap, those waiting for a second person, reversals"
  - id: replenishment
    name: Replenishment
    stories:
      - INV-44
    actors:
      - warehouse_manager
    note: "v3: tonight's proposals with every figure behind them; accept, change or dismiss; what was sent and what purchasing did with it"
  - id: warehouses
    name: Warehouses
    stories:
      - INV-01
      - INV-02
      - INV-36
    actors:
      - warehouse_manager
  - id: valuation
    name: Valuation
    stories:
      - INV-16
      - INV-48
      - INV-56
    actors:
      - accountant
      - stock_controller
      - owner
    note: stock value per product and company on a date, the moves and journals behind it, pending postings and their reasons, the account map
  - id: settings
    name: Settings
    stories:
      - INV-17
    actors:
      - warehouse_manager
      - owner
    note: every config_row below; the controls only to inv:settings:controls
permissions:
  namespace: inv
  catalog:
    - inv:stock:read
    - inv:availability:read
    - inv:warehouse:write
    - inv:product:write
    - inv:receipt:validate
    - inv:delivery:validate
    - inv:transfer:write
    - inv:count:write
    - inv:adjustment:apply
    - inv:adjustment:approve
    - inv:reservation:write
    - inv:move:reverse
    - inv:valuation:read
    - inv:account_map:write
    - inv:settings:write
    - inv:settings:controls
    - inv:receipt:intake
    - inv:reservation:intake
    - inv:valuation:post
    - inv:number_series:claim
    - inv:count:suggest
    - inv:migration:import
    - inv:migration:read
    - inv:issue:write
    - inv:issue:approve
    - inv:stock_type:write
    - inv:replenishment:write
    - inv:valuation:write
    - inv:return:expect
    - inv:replenishment:propose
    - inv:abc:classify
    - inv:issue:intake
    - inv:standard_price:intake
  machine:
    - inv:receipt:intake
    - inv:issue:intake
    - inv:standard_price:intake
    - inv:reservation:intake
    - inv:valuation:post
    - inv:number_series:claim
    - inv:count:suggest
    - inv:migration:import
    - inv:migration:read
    - inv:return:expect
    - inv:replenishment:propose
    - inv:abc:classify
  decided_by: "permissions only, never a role's name: the brick is generic; a composition maps its own roles to these"
  row_visibility:
    rule: everyone with inv:stock:read sees every warehouse (a small firm's floor staff move between sites); cost and value only to inv:valuation:read; sales sees availability only
    enforced: "in the use case: value_amount, unit_cost and average cost are projected out for callers without inv:valuation:read; the availability route is a different route with a narrow shape, not a filter"
    not_found_not_forbidden: true
config_rows:
  - table: inv_warehouse
    changes: the sites, their company and address
  - table: inv_location
    changes: zones and bins, their barcodes, which are archived, and each internal location's stock status (unrestricted, quality, blocked; v2)
  - table: inv_stocked_product
    changes: which products are tracked by lot or serial (only with lots_enabled)
  - table: inv_account_map
    changes: the ledger account per company (and valuation class, v3) for stock_valuation, stock_received_not_billed, cost_of_goods_sold, inventory_loss, consumption, inventory_scrap, free_of_charge, price_difference, revaluation, consignment_liability, subcontracting
  - table: inv_putaway_rule
    changes: where goods are put away per product or category (v3)
  - table: inv_package_type
    changes: boxes and pallets with their tare and size (v3)
  - table: inv_standard_price
    changes: standard prices per company and product from a date (v3; inv:valuation:write)
  - table: inv_settings
    changes: how this business keeps stock; every row dated from today or later, never back-dated
    settings:
      - key: allow_negative_stock
        type: str
        default: none
        changes: none | a list of warehouse ids where a move may take a bin below zero (INV-17); inv:settings:controls
      - key: count_approval_threshold
        type: str
        default: "500.00"
        changes: the SUM of the absolute VALUE differences across the count's lines (each difference valued at the average or standard cost; never a quantity), in the company's currency, at or above which a second person approves (INV-11); 0 means every count; inv:settings:controls
      - key: count_line_value_limit
        type: str
        default: "200.00"
        changes: the absolute value difference of ONE line, in the company's currency, at or above which the whole count needs a second person even when the sum is under count_approval_threshold (INV-11); 0 means no per-line limit; inv:settings:controls
      - key: lots_enabled
        type: bool
        default: false
        changes: whether products may be tracked by lot or serial (INV-03, INV-06); inv:settings:controls
      - key: ledger_mode
        type: str
        default: null
        changes: post | export | off; unset = post when the ledger (gl) is installed, else export monthly; a switch takes effect from the first day of a later month; inv:settings:controls
      - key: over_receipt_tolerance_pct
        type: int
        default: 0
        changes: percent a receipt line may exceed what was expected (INV-05)
      - key: delivery_needs_weights
        type: bool
        default: false
        changes: whether a delivery with a line of unknown weight can be validated (INV-35)
      - key: part_shipments
        type: bool
        default: true
        changes: whether a delivery may leave before every line is reserved (a back-order follows)
      - key: default_warehouse
        type: str
        default: null
        changes: "per company: where a sales order reserves when it names none"
      - key: number_format
        type: str
        default: "{warehouse}/{kind}/{seq:5}"
        changes: the number stamped on a done document
      - key: valuation_method
        type: str
        default: average
        changes: "per company: average | standard, from the first day of a later month (INV-48); inv:settings:controls"
      - key: issue_approval_threshold
        type: str
        default: "500.00"
        changes: the value of a goods issue or scrap at or above which a second person approves (INV-37); inv:settings:controls
      - key: replenishment_mode
        type: str
        default: suggest
        changes: "suggest | auto: whether accepted proposals wait for a person (INV-44); inv:settings:controls"
      - key: allow_expired_pick
        type: bool
        default: false
        changes: whether a warehouse manager may pick an expired lot with a reason (INV-39); inv:settings:controls
      - key: receipt_steps
        type: str
        default: one
        changes: one | two (goods-in, then putaway, INV-50)
      - key: delivery_steps
        type: str
        default: one_step
        changes: one_step | pick_ship | pick_pack_ship (INV-51, INV-52)
      - key: pick_pack_days
        type: int
        default: 1
        changes: "per warehouse: days from availability to goods leaving, for ATP (INV-49)"
      - key: abc_thresholds
        type: str
        default: 80,95
        changes: cumulative value shares that end class A and B (INV-42)
      - key: count_frequency
        type: str
        default: A:12,B:4,C:1
        changes: cycle counts per year per class (INV-43)
      - key: gs1_company_prefix
        type: str
        default: null
        changes: the prefix SSCCs are numbered under (INV-52)
  - table: inv_settings
    changes: "the AI step's mode (ai_steps: off | suggest); inv:settings:controls, and turning it on is recorded as the owner's consent"
in_code_not_rows:
  - that on hand is the sum of moves, derived on read, and no quantity is ever stored or edited
  - that a move is never updated or deleted; a mistake is a reversing move naming it
  - that a ledger quantity is in the product's base unit, converted exactly; a conversion that is not exact is refused, never rounded
  - that a move out of an internal location claims its bin and its warehouse with a plain INSERT; the loser re-reads and is refused or retries
  - that the move emptying a product's company stock takes its remaining value (zero quantity is zero value)
  - that the approver of a count is neither its counter nor its submitter, by email and by sign-in subject
  - that a service is never stocked and a virtual location is never counted or available
  - that stock in a quality or blocked location is on hand and valued but never available, reserved or picked (v2)
  - that a document line copies its unit's measures when written and a later product change never rewrites them (v2)
  - "that catch weight and lot conversions are refused until M7: their columns stay NULL"
  - that inventory asks the ledger and the sales order through their routes and never writes their tables
  - "that an AI step only suggests: its output lands in inv_suggestion and changes no quantity"
  - that stock type and owner are part of every stock row; quality, blocked, customer-consignment and subcontractor stock is never available (v3)
  - that supplier-consignment stock is valued at zero until withdrawn, and a withdrawal is valued at purchasing's consignment price (v3)
  - that a lot within the customer's minimum shelf life, or expired, is never proposed, promised or picked without the owner's allowance (v3)
  - that under standard cost a product's value is quantity x standard rounded once, and a receipt's difference to its purchase cost is a price difference (v3)
  - that an issue or scrap over the threshold waits for a second person, by email and sign-in subject (v3)
  - that replenishment reads product's site data and never stores it; a proposal is sent once (v3)
ai_steps:
  - key: ai_explain_variance
    benefit: an approver checks the likely cause first (a mis-put transfer, a unit confusion) instead of writing off stock that is on the next shelf
    mode: suggest
    modes_allowed:
      - off
      - suggest
    safe_for_auto: false
    inputs:
      - the count line
      - the moves on that product in that warehouse since the last count
      - pack conversions of the product
    output: per line over the threshold, a short likely cause and the location or move to check, with a confidence
    fallback: no suggestion; the approver sees the moves list
    eval: counts with seeded causes (a transfer to the wrong bin, a pack counted as a unit); share of lines whose suggestion names the seeded cause
tests:
  acceptance: one per story id above, named for it
  access:
    - a stock operator never sees unit_cost, value_amount or an average cost in any answer
    - a sales rep reads availability per warehouse only; a bin, a lot or a move is a 404 to them
    - only inv:adjustment:approve approves a count; its counter or submitter is refused, matched by email AND by sign-in subject (a second account of the same person is refused)
    - only inv:settings:controls changes allow_negative_stock, count_approval_threshold, count_line_value_limit, lots_enabled, ledger_mode or the AI step's mode; inv:settings:write is refused on them
    - a wildcard grant (inv:*:*) does not reach inv:receipt:intake, :reservation:intake, :valuation:post, :number_series:claim, :count:suggest, :migration:import, :return:expect, :replenishment:propose or :abc:classify
    - "v3: only inv:issue:approve approves an issue over the threshold, never its planner or submitter (email AND sign-in subject); only inv:valuation:write sets a standard price; only inv:settings:controls changes valuation_method, issue_approval_threshold, replenishment_mode or allow_expired_pick"
    - "v3: a stock operator never sees a standard price, a price difference or a consignment price"
  invariants:
    - on hand at any location and moment = SUM(quantity_base of moves into it) - SUM(moves out of it) recorded by then; nothing stores it
    - a move is never updated or deleted; a reversal names its original and a move is reversed at most once
    - "two concurrent validations needing the last unit: exactly one succeeds; the other gets the claim row's 23505, re-reads and is refused; neither writes a partial move nor calls the sales order twice"
    - "two concurrent reservations for the last available unit: one is reserved, the other short; reserved never exceeds on hand at a warehouse (unless negative stock is allowed there)"
    - with allow_negative_stock none, no internal location is ever below zero
    - SUM(value_amount) of a company's moves of a product = that product's last value_after; at quantity 0 the value is exactly 0.00
    - a transfer between warehouses of one company changes no value; a transfer between companies is refused
    - every ledger quantity converts exactly from its document quantity (quantity x numerator / denominator, no float); a conversion that is not exact in the base unit's decimals is refused
    - a quantity, a unit cost or a count above its bound (10^12, NUMERIC 19,4 / 18,2) or with too many decimals is a 422 with the reason, never a 500
    - a supplier move enters stock only through POST /receipts or POST /returns-to-supplier called by purchasing; the scanner has no route that posts one; the same move_ref yields one move; the same delivery_ref is recorded once on the order; the same (document_id, event) posts one journal
    - "'today' is the date in business_timezone, not the UTC date; a move is dated today, never back-dated or in the future (the migration's opening moves are the one exception: facts dated by the cut-over); and today never goes backwards (a zone change that would make today earlier keeps the later date until the clocks agree)"
    - "a document number is claimed only when the document is done, with a plain INSERT on (series_id, number): never reused, no gap from a cancelled document (it never had one), and a migrated series continues after Odoo's highest"
    - a count's difference is taken against on hand at the line's counted_at; moves after it are kept
    - a serial number is on hand in at most one location, with quantity 1
    - "a later migration run never rewrites a signed run: it writes nothing that exists and lists every difference as an adjustment to make"
    - a receipt scanned here is recorded by purchasing's POST /purchase-orders/{purchase_order_id}/receipts exactly once per delivery note, and the moves it posts back carry move_ref pur:<receipt_id>:<line_no>
    - a return to the supplier is valued at the cost of the move it reverses, and is refused with nothing moved when the stock is no longer at the location
    - GET /migration-map/{db}/{model}?ids= answers [{odoo_model, odoo_id, ours}] and omits an id not migrated
    - a transition refused for a gate names the gate, its reason and its fix, the same as the readiness answer
    - "v2: a count line's counted_base equals the exact sum of its entries (quantity x numerator / denominator each); an entry in a unit the product lacks is refused"
    - "v2: available at a warehouse never includes stock at a quality or blocked location; a reservation or a pick naming one is refused; a release is a transfer with no value change; a location's status changes only while it is empty"
    - "v2: a receipt move's value = round_half_up(quantity_base x pricing_denominator / pricing_numerator x unit_cost / pricing_quantity, 2), the same number purchasing netted for the line received in full"
    - "v2: a document's gross, net weight and volume = the sum over its lines of quantity x the copied per-unit measure, converted exactly; a line with an unknown measure is named, never counted as 0"
    - "v3: on hand per (product, location, lot, stock type, owner) = moves in less moves out; a type change or a withdrawal moves between rows at the same location; available counts only unrestricted rows owned by us or a consignment supplier"
    - "v3: two concurrent picks or issues on the last unit of a stock row: one wins the claim row (key includes stock type and owner), the other is refused and writes nothing"
    - "v3: a goods issue or scrap is valued at the cost in force, reversed at most once at the value it was posted at, and its journal carries the cost centre; the issue's number is claimed only when posted"
    - "v3: a FEFO pick proposes the earliest-expiring lot with at least the customer's minimum shelf life left; an expired lot is excluded from availability, ATP and picking from its expiry date ('today' in business_timezone)"
    - "v3: a serial is on hand in at most one row with quantity 1; a delivered serial is on hand nowhere; a return accepts only a serial delivered to that customer"
    - "v3: ABC classes and replenishment proposals are written once per (warehouse, product, date); a proposal's purchase request is keyed and sent once"
    - "v3: ATP never confirms more than unrestricted stock less reservations plus expected supply by date; nothing is reserved by asking"
    - "v3: under standard cost value_after = round_half_up(quantity_after x standard, 2) and each move's value is its change, so a company's moves sum to the value exactly and zero quantity is 0.00; receipt value + price difference = purchasing's line value"
    - "v3: a supplier-consignment move into stock carries no value; the withdrawal is valued once at purchasing's answer and purchasing is told once per withdrawal_ref"
    - "v3: a subcontract receipt's value = the consumed components' value + the service cost; a component missing at the subcontractor refuses the receipt with nothing moved"
    - "v3: a package's contents never exceed what was picked; an SSCC is never reused and its check digit is right"
    - "v3: a return receipt needs an open RMA, never exceeds it, and reports its inspection to sales-order once"
    - 'v2 (deferred to M7): catch_quantity, catch_unit_code, lot_numerator, lot_denominator, lot_unit_code and catch_quantity_change are NULL on every row; any route given one answers 422 ("catch weight and batch-specific units arrive in M7")'
    - "INV-57: a valuation adjustment is keyed adjustment_ref; it splits by what is still on hand from the named receipt, never revalues stock from another receipt, and posts once"
  scenarios:
    - id: SC-INV-01
      name: buy in packs, sell by the bottle, count in litres
      stories:
        - INV-05
        - INV-07
        - INV-10
        - INV-11
        - INV-25
      given: COLA-075 base LTR, bottle 0.75 LTR, PK24 = 18 LTR; PO-0101 expecting 10 PK24 at 21.60; an order of 48 bottles
      when: 8 PK24 are received, 24 bottles delivered, the bin counted at 117 LTR and the count applied
      then: on hand 144, 126, then 117 LTR; the order shows 24 delivered; a count worth -10.80 applies without approval and posts a loss of 10.80
    - id: SC-INV-02
      name: the last unit, twice
      stories:
        - INV-08
        - INV-13
        - INV-22
      given: one DRILL-500 at WH1/A/03; two orders, one reserved, one not
      when: both deliveries are validated concurrently, then two reservations race for a newly received unit
      then: the reserved order ships; the unreserved delivery is refused and writes nothing; of the reservations one is met and one is short
    - id: SC-INV-03
      name: average cost to zero
      stories:
        - INV-16
        - INV-31
        - INV-32
      given: COLA-075 at UK1, no stock
      when: 144 LTR received at 1.2000, 72 LTR at 1.3500, 90 LTR then 126 LTR delivered
      then: averages 1.2000, 1.2500, 1.2500; values 172.80, 270.00, 157.50, 0.00; four journals, each once; the stock account in the ledger nets to 0 (exact, no residue)
    - id: SC-INV-04
      name: a large count needs a second person
      stories:
        - INV-10
        - INV-11
        - INV-12
        - INV-33
      given: threshold 500.00; count C-15 worth -1,250.00 submitted by the warehouse manager, who also holds inv:adjustment:approve under a second account
      when: the manager approves with the second account; then a stock controller approves
      then: the first is refused (same email or same subject); the second applies the adjustment and posts it; the AI suggestion is shown, never applied
    - id: SC-INV-05
      name: a return reverses the delivery's cost
      stories:
        - INV-14
        - INV-23
      given: WH1/OUT/00001 delivered 24 bottles valued 21.60; the average cost has since moved to 1.3000 a litre
      when: 6 bottles come back
      then: the return is valued 5.40 (the cost they left at); the order records -6 with corrects_ref inv:WH1/OUT/00001; returning 30 is refused
    - id: SC-INV-06
      name: Odoo opening stock reconciles and stays signed
      stories:
        - INV-26
      given: an Odoo test database with two warehouses, a lot-tracked product, a negative quant and AVCO costs
      when: the migration runs twice, the reconciliation is signed, Odoo is changed and the migration runs again
      then: every reconcile check equal or explained (the negative quant listed); the second run writes nothing; the third writes nothing and lists the change as an adjustment to make
    - id: SC-INV-08
      name: received into inspection, counted in cases, shipped by weight
      stories:
        - INV-36
        - INV-34
        - INV-35
        - INV-20
      given: WH1/QC (quality), WH1/A/01; COLA-075 warehouse unit PK24 with measures; a purchase line priced 21.6000 per PK24; an order of 48 C62
      when: 8 PK24 are received into WH1/QC, the order asks availability, 6 PK24 are released to WH1/A/01, WH1/A/01 is counted as 5 PK24 and 6 C62, and 2 PK24 are delivered
      then: the receipt is valued 172.80 and shows 153.6 KGM; available is 0 until the release, then 108 LTR; the count line is 94.5 LTR from two entries; the delivery shows gross 38.4 KGM
    - id: SC-INV-09
      name: issue, scrap and FEFO
      stories:
        - INV-37
        - INV-38
        - INV-39
      given: GLOVES at 0.0800; COLA-075 lots L-2611 (29 days left), L-2612, L-2601 (expired); threshold 500.00
      when: 3 BX100 GLOVES are issued to MAINT and reversed, 36 LTR scrapped, a 7311 delivery picked, and an issue worth 600.00 approved by its submitter's second account
      then: 24.00 issued and reversed once; scrap posted with its reason; L-2612 proposed; the second account refused
    - id: SC-INV-10
      name: plan, promise and replenish
      stories:
        - INV-42
        - INV-43
        - INV-44
        - INV-49
        - INV-54
      given: twelve months of moves at WH1; site rows for WH1 and WH2
      when: ABC runs, the cycle plan is opened, ATP asked for 480 C62, the nightly proposal runs twice and is accepted
      then: COLA-075 class A and due for counting; 171 LTR now and the rest by date; one proposal of 60 PK24 and one purchase request
    - id: SC-INV-11
      name: special stocks
      stories:
        - INV-45
        - INV-46
        - INV-47
      given: consignment at 7311; supplier 9100's consignment SCREW-M4; subcontractor 9200 with components
      when: a fill, an issue and a pick-up; a delivery from 9100's stock; KIT-A received from 9200
      then: customer consignment on hand and never available; one withdrawal valued at purchasing's price; KIT-A valued at components + service
    - id: SC-INV-12
      name: standard cost to zero
      stories:
        - INV-48
        - INV-56
      given: UK1 switches to standard on 2026-12-01 at 1.2000; COLA-075 126 LTR at average 1.2500
      when: the switch, a receipt at 1.3500, a delivery, a new standard from 2027-01-01, and the last litre delivered
      then: revaluation -6.30; price difference 21.60; revaluation +9.00 once; value 0.00 at zero quantity
    - id: SC-INV-13
      name: receipt posting date and count value limits
      stories:
        - INV-05
        - INV-11
      given: today 2026-11-02, period 2026-10 closed and 2026-11 open; threshold 500.00, line limit 200.00; count C-16 lines worth -250.00, -20.00, +20.00; count C-14 lines worth -42.10, +30.00
      when: receipts are submitted with posting date 2026-11-03, 2026-10-15 and 2026-11-01; C-14 and C-16 are submitted
      then: the future date and the closed-period date are refused 422 with the reason, 2026-11-01 posts; C-14 applies at once; C-16 waits for a second person though its sum 290.00 is under 500.00
    - id: SC-INV-07
      name: today at midnight
      stories:
        - INV-07
        - INV-30
      given: business_timezone Europe/London, 00:30 on 2026-11-01 local (23:30 on 2026-10-31 UTC)
      when: a delivery is validated
      then: its moves and the sales order's delivered_on are 2026-11-01, not the UTC date
scale:
  reads: "the tables reader serves 16 concurrent reads; on hand is a SUM over inv_move per (product, location prefix): one query, indexed by product_id; availability adds one SUM over inv_reservation"
  hot_paths:
    - availability on every order line and confirmation
    - the pick list
    - the claim on validation (a short serial section per bin)
  workers: none required; a clock worker (--reserved 1 --max-replicas 1) only to retry pending postings, or run it from an external scheduler
  volumes: a few thousand moves a day and tens of thousands of products is comfortable; above that, add a dated on-hand snapshot per month as a derived cache (rebuildable from moves, never edited) so on hand reads the snapshot plus later moves
platform_constraints:
  - constraint: A bare INSERT of an already-committed key is rejected (23505); it is not an upsert.
    today: "the claim rows, the valuation seq and the number series use exactly that as the lock: the loser re-reads and decides"
  - constraint: A SELECT does not see the same open transaction's writes.
    today: the move, its claim and its valuation row are computed from reads taken before the write; the derived on hand is re-read after commit
  - constraint: the tables reader serves 16 concurrent reads
    today: validation storms (a wave of picks) go through an admission semaphore below 16 with the retry on the documented markers
customer_varies:
  - question: "v6: When a till sells what the system thinks is not on the shelf, do we still take it out of stock?"
    changes: INV-58 (issue_from_source for pos_sale)
    default: "yes: a sale that happened is never refused; the location goes negative and is listed for the stock controller to count (the standard default for retail, chosen 2026-10-25). A production issue short of stock is refused unless the location allows negative stock"
  - question: How many sites do you keep stock in, and do you need shelf or bin locations, or just "in the warehouse"?
    changes: inv_warehouse and inv_location depth; with no bins a warehouse has one internal location
    typical:
      shop_or_small_office: one site, no bins
      wholesale: one or two sites, zones and bins
  - question: Do you ever ship something the system says you do not have (and fix it after)?
    changes: allow_negative_stock
    typical:
      most_firms: never, and the system should stop it
      fast_moving_retail: allowed in the shop, never in the warehouse
      warning: negative stock is valued at the last average and leaves a cost difference to correct when the receipt comes in
  - question: Do you need batch or serial numbers (recalls, warranties, expiry)?
    changes: lots_enabled; inv_stocked_product per product
    typical:
      food_and_cosmetics: lots with expiry dates
      tools_and_electronics: serial numbers on the expensive items
      most_others: neither
  - question: How do you value stock?
    changes: "valuation_method per company: average (the reference) or standard (v3); FIFO layers are not offered (see sap_parity)"
    standard: IAS 2 Inventories paras 25-27 permit FIFO or weighted average cost for interchangeable items (FRS 102 section 13 likewise in the UK)
    typical:
      most_smes: weighted average, as here
      manufacturers_and_distributors_with_stable_costs: standard cost, with purchase price variances shown
  - question: When a stock count finds a difference, who approves the write-off, and above what amount?
    changes: count_approval_threshold, count_line_value_limit
    typical:
      small_firms: the owner, above a few hundred pounds
      firms_with_a_controller: every count over a small amount, by finance
  - question: Does a delivery leave when part of the order is ready, or only when all of it is?
    changes: part_shipments
  - question: Do you use stock internally or scrap it, and who approves above what value?
    changes: issue_approval_threshold; inv_account_map consumption and inventory_scrap
  - question: Does stock expire, and do customers require a minimum shelf life?
    changes: inv_stocked_product removal_strategy fefo and shelf_life_days; sales-order's customer policy minimum shelf life
  - question: Should the system propose (or send) reorders when stock runs low?
    changes: product's site rows (reorder point, min / max); replenishment_mode
  - question: Do suppliers keep consignment stock with you, do you keep stock at customers, or send components to subcontractors?
    changes: special stocks (owner on the row; consignment and subcontractor locations)
  - question: Do you put away to fixed bins, pick several orders together, and pack into numbered pallets or boxes?
    changes: receipt_steps, delivery_steps, inv_putaway_rule, pick_sequence, inv_package_type, gs1_company_prefix
variation_points:
  - node: Task_approve_count
    op: row_value
    default: a second person at or above 500.00
    depth: 1
    guideline: "warn - a write-off with no second person is the commonest way stock losses go unseen (typical: segregation of duties for adjustments)"
  - node: Task_pick_goods
    op: narrow
    default: no bin below zero
    depth: 1
    guideline: warn - negative stock costs the shipment at a stale average and needs a correction when the receipt lands
  - node: Task_ai_explain_variance
    op: on_off
    default: off until the owner turns it on (suggest)
    depth: 1
    guideline: warn - with it off the approver reads the moves list unaided
  - node: Task_validate_delivery
    op: narrow
    default: the order records every delivery from here
    depth: 1
    requirement: refuse - a delivery recorded on the order by hand while inventory is installed counts the stock twice; the sales order must take deliveries of goods lines from inventory only
  - node: Task_ship_to_site
    op: on_off
    default: two steps through transit between warehouses
    depth: 2
    guideline: warn - one step hides stock on a lorry; keep two steps when sites are more than a day apart
reference:
  repos:
    - name: erp-brick-inventory
      role: brick
      https: https://git.dodil.io/dodil/erp-brick-inventory.git
      ssh: git@git.dodil.io:dodil/erp-brick-inventory.git
      tag: v0.1.2
      read_first:
        - README.md
        - AGENTS.md
      clone: git clone --depth 1 --branch v0.1.2 https://git.dodil.io/dodil/erp-brick-inventory.git
    - name: erp-brick-product
      role: brick
      https: https://git.dodil.io/dodil/erp-brick-product.git
      ssh: git@git.dodil.io:dodil/erp-brick-product.git
      tag: v0.2.2
      read_first:
        - README.md
        - AGENTS.md
      clone: git clone --depth 1 --branch v0.2.2 https://git.dodil.io/dodil/erp-brick-product.git
    - name: erp-platform
      role: platform
      https: https://git.dodil.io/dodil/erp-platform.git
      ssh: git@git.dodil.io:dodil/erp-platform.git
      tag: v0.9.13
      read_first:
        - README.md
        - AGENTS.md
      clone: git clone --depth 1 --branch v0.9.13 https://git.dodil.io/dodil/erp-platform.git
  packages: []
  contracts: []
  build_guide: null
  known_gaps:
    - "average or standard cost per company (v3); no FIFO layers; no landed costs (freight and duty added to a receipt's cost: purchasing's to send as part of unit_cost)"
    - no inter-company moves (a sale and a purchase); drop-shipping never touches stock (sales-order v5 THIRD_PARTY with purchasing)
    - v3 (issues, scrap, FEFO, serials end to end, ABC and cycle counts, stock types per row, special stocks, ATP, putaway, pick batches, packing, transit dates, replenishment, standard cost) is specified, not built
    - "cross-module, assumed by v3: purchasing's GET /expected-receipts, POST /purchase-requests/from-replenishment, POST /consignment-withdrawals, consignment and subcontract orders posting through POST /receipts; gl's GET /cost-centres/{cost_centre}; sales-order v5's returns order, fulfilment route and inspection route"
    - "full EWM is deferred (sap_parity): no warehouse tasks or orders, RF queues, slotting, labour management, yard or cross-docking; carrier booking and shipping labels are not modelled"
    - a return to a supplier starts only in purchasing (its return row, posted here through POST /returns-to-supplier); none is started from this module's screens
    - replenishment is consumption-based (reorder point, min / max, fixed lot) from product's site data (v3); MRP with dependent demand waits for production (M7)
    - no manufacturing consumption or production locations (M7 Make & sell; the product's production unit is kept for it)
    - goods issue to a cost centre and scrap are in v3 (INV-37, INV-38); issues to projects (a WBS element) wait for projects' cost objects (M5)
    - "catch weight and batch-specific units of measure: designed, columns reserved, off until M7 (`deferred:`)"
    - pick batches and packing are in v3; carriers and shipping labels are not
    - sales-order v3 (spec) reserves through INV-22 and refuses hand-recorded deliveries of stocked lines; until erp-brick-sales-order builds it, the composition must not give fulfillers so:order:deliver on stocked goods
    - "processes have no APQC PCF ids yet (pcf_id null): erp-bench/standards carries only the category ids (4.0 = 20022), not the warehousing elements; to be verified against PCF v8.0 before sign-off"
    - company_code is a code validated against nothing until a shared company key exists (shared.yaml has none)
migration:
  odoo:
    runs_after:
      - business-partner
      - product
      - sales-order
      - purchasing
    reads:
      - model: stock.warehouse
        fields:
          - id
          - name
          - code
          - company_id
          - view_location_id
          - lot_stock_id
          - partner_id
          - active
        filter: every warehouse of the companies being migrated
        why: inv_warehouse; its code becomes warehouse_id
      - model: stock.location
        fields:
          - id
          - name
          - complete_name
          - location_id
          - usage
          - company_id
          - warehouse_id
          - barcode
          - active
        filter: usage in (internal, view, transit) under the warehouses read, plus every location named by a quant or an open picking
        why: the tree; supplier, customer, inventory (loss) and production usages map onto our virtual locations
      - model: stock.quant
        fields:
          - id
          - product_id
          - location_id
          - lot_id
          - quantity
          - reserved_quantity
          - company_id
          - in_date
        filter: location usage internal or transit; quantity != 0; read at the cut-over
        why: the opening balance by product, location and lot
      - model: stock.lot
        fields:
          - id
          - name
          - product_id
          - company_id
          - expiration_date (where product_expiry is installed)
        filter: lots named by a quant read
        why: inv_lot; product.template.tracking says lot or serial
      - model: product.product
        fields:
          - id
          - default_code
          - standard_price
          - product_tmpl_id
        filter: "products with a quant read; standard_price read per company (company-dependent field: read with each company in context)"
        why: the opening average cost per product per company
      - model: product.template
        fields:
          - id
          - is_storable (17+; type = 'product' on 16 and older)
          - tracking
          - categ_id
        filter: templates of the products read
        why: which products are stocked and their tracking; the cost method per category (property_cost_method) decides the door below
      - model: stock.valuation.layer
        fields:
          - product_id
          - company_id
          - quantity
          - value
          - create_date
        filter: all layers to the cut-over (Odoo 13 to 18; on 19 read the stock valuation report instead, as the reconcile names)
        why: Odoo's stock value per product and company, for the reconciliation only; never re-computed
      - model: stock.move
        fields:
          - id
          - reference
          - product_id
          - product_uom_qty
          - quantity
          - product_uom
          - location_id
          - location_dest_id
          - state
          - date
          - picking_id
          - origin
          - sale_line_id
          - purchase_line_id
          - price_unit
          - company_id
        filter: state = done, to the cut-over (history, read-only); plus state in (confirmed, waiting, assigned, partially_available) for open pickings
        why: history kept read-only in inv_odoo_history; open moves become open documents
      - model: stock.move.line
        fields:
          - id
          - move_id
          - product_id
          - lot_id
          - quantity
          - product_uom_id
          - location_id
          - location_dest_id
          - date
        filter: move_id in the moves read
        why: the bin and lot level of history
      - model: stock.picking
        fields:
          - id
          - name
          - picking_type_id
          - state
          - partner_id
          - origin
          - scheduled_date
          - location_id
          - location_dest_id
          - sale_id
          - backorder_id
          - company_id
        filter: state not in (draft, cancel) for history names; state in (confirmed, waiting, assigned) for open ones
        why: numbers already used per series; open receipts and deliveries
    maps:
      - from: stock.warehouse.code
        to: warehouse.warehouse_id
        rule: copied (WH); company_id -> company_code through the door's company list
      - from: stock.location.complete_name
        to: location.location_id
        rule: "WH/Stock/Shelf 1 -> WH/STOCK/SHELF-1: path segments kept, normalised to upper case and hyphens, collisions listed and stopped; usage internal -> internal, view -> view, transit -> {company}:TRANSIT or kept as a transit location; supplier, customer, inventory -> the company's virtual SUPPLIER, CUSTOMER, LOSS"
      - from: stock.quant (product, location, lot) quantity
        to: stock_move (opening)
        rule: "one move OPENING -> location per (product, location, lot), quantity converted from the product's Odoo uom to its base unit through product's unit map, dated the cut-over date (a fact dated by the cut-over: the one back-dated write), move_id opening:{db}:{location}:{product_id}:{lot}"
      - from: stock.quant.reserved_quantity
        to: (not stored)
        rule: re-reserved after cut-over from the migrated open sales orders (INV-22), so reservations name our order lines
      - from: stock.lot
        to: lot
        rule: (product_id, name) as lot_code; tracking from product.template.tracking (lot | serial | none)
      - from: stock.location used as an inspection or scrap-pending step (multi-step reception 'Quality Control', a location the door names)
        to: location.stock_status quality | blocked
        rule: per the door; every other internal location unrestricted; Odoo scrap locations (scrap_location) map to LOSS
      - from: product.product.standard_price (per company)
        to: valuation_row (opening)
        rule: unit cost of the opening moves; value_amount = round(quantity x cost, 2) per move; one opening valuation row per (company, product); never posted to the ledger (gl migrates balances)
      - from: product.template.is_storable / type
        to: (product kind goods)
        rule: product's migration owns kind; non-storable consumables are not stocked here
      - from: stock.move (done) + stock.move.line
        to: odoo_move_history
        rule: copied read-only with Odoo's reference, quantities in base unit; never part of on hand
      - from: stock.picking (open, incoming)
        to: (not an inventory document)
        rule: what is still to arrive is purchasing's open order lines (its migration carries them as outstanding); after cut-over goods-in scans against them like any order (INV-21)
      - from: stock.picking (open, outgoing)
        to: delivery (waiting)
        rule: document_id odoo:{db}:stock.picking:{id}; linked to the order through sales-order's map (sale_id)
      - from: stock.picking.name per picking type
        to: number_series
        rule: the highest number per series, so ours continues after it (or a new prefix, per the door)
      - from: stock.quant.owner_id (consignment, v3)
        to: the opening move's owner_to
        rule: a quant owned by a supplier comes over as that supplier's consignment stock (bp_id through business-partner's map), valued 0.00; a quant owned by anyone else stops the run with the quant named
      - from: product.category.removal_strategy_id / product removal (fifo | fefo | lifo)
        to: inv_stocked_product.removal_strategy
        rule: fifo and fefo copied; lifo or closest location -> fifo, listed for the door
      - from: product.template.expiration_time / use_time (product_expiry)
        to: inv_stocked_product.shelf_life_days
        rule: copied in days
      - from: stock.putaway.rule
        to: inv_putaway_rule (v3)
        rule: product or category -> target location through the location map; sublocation strategies become next_bin_with_room
      - from: product.category.property_cost_method (standard | average | fifo)
        to: valuation_method per company (v3)
        rule: standard -> standard with standard_price as the first inv_standard_price dated the cut-over; average -> average; fifo -> average at Odoo's standard_price with the difference explained (the door decides); mixed methods in one company -> the door picks one per company
    door:
      - "the cut-over date and time: Odoo stops moving stock then; the quant snapshot is read at it"
      - which companies and warehouses come over
      - "which Odoo internal locations are inspection (quality) or set-aside (blocked) stock: their quants come over on hand but unavailable"
      - "the valuation method per company (v3): standard where Odoo's categories are standard, average otherwise; a FIFO category carried at Odoo's standard_price as the opening average, the difference to Odoo's layers explained"
      - which suppliers' consignment quants (owner_id) come over as consignment stock
      - "negative quants: carried as negative opening moves (allowed for the migration only, listed, cleared by a count) or corrected in Odoo first (recommended)"
      - "open pickings: carried as open documents, or validated or cancelled in Odoo before the cut-over (recommended: fewer of them)"
      - "how much history: every done move, or the open years only (older kept as the Odoo export)"
      - "numbering after cut-over: continue Odoo's sequences or start new prefixes"
    reconcile:
      - check: on hand per product per internal location (and lot)
        odoo: read_group stock.quant SUM(quantity) by product_id, location_id, lot_id, usage internal, at the cut-over
        ours: on hand derived from inv_move per (product_id, location_id, lot_code) at the cut-over, in the Odoo uom
        must: equal
      - check: on hand per product per warehouse
        odoo: SUM(quantity) of internal quants by product_id, warehouse_id
        ours: on hand per warehouse subtree
        must: equal
      - check: stock in transit
        odoo: SUM(quantity) of quants with location usage transit
        ours: on hand at TRANSIT locations
        must: equal
      - check: stock value per product per company
        odoo: SUM(value) of stock.valuation.layer by product_id, company_id (Odoo 13-18; the Inventory Valuation report on 19)
        ours: value_after of the opening valuation row
        must: equal | explained (rounding per move, at most 0.01 per opening move; a FIFO or standard-cost category per the door)
      - check: average cost per product per company
        odoo: product.product.standard_price with company_id in context (AVCO categories)
        ours: average_cost_after of the opening row
        must: equal
      - check: stock value per company against the ledger
        odoo: the balance of each category's stock valuation account at the cut-over
        ours: SUM(value_after) per company
        must: explained
      - check: lots and serials
        odoo: count stock.lot named by a quant; serial quants with quantity != 1
        ours: count inv_lot; serials on hand more than once
        must: equal; the serial anomalies listed
      - check: negative quants
        odoo: quants with quantity < 0
        ours: opening moves with a negative result
        must: explained
      - check: consignment quants (v3)
        odoo: SUM(quantity) of internal quants with owner_id by product, owner
        ours: on hand of the opening rows with that owner
        must: equal
      - check: open pickings
        odoo: count stock.picking by picking_type_id, state open
        ours: open deliveries with source_kind odoo; open incoming pickings against purchasing's outstanding lines
        must: equal | explained (closed in Odoo per the door)
      - check: history carried
        odoo: count stock.move.line of done moves in the years carried
        ours: count inv_odoo_history
        must: equal
    not_carried:
      - "reserved quantities: re-made from the migrated open sales orders"
      - "Odoo's valuation layers and stock journal entries: read to reconcile, never re-posted (the ledger migrates its balances)"
      - routes, push and pull rules; reordering rules (stock.warehouse.orderpoint) are product's migration (its prod_site rows, v3)
      - "packages (stock.quant.package) and package types: the contents are carried, the packaging is not"
      - "putaway rules (stock.putaway.rule): carried as inv_putaway_rule where the target is a carried location (v3), else listed for the door"
      - "manufacturing and production locations (mrp): M7"
      - "catch weight: Odoo has none (no per-move actual weight), and no batch-specific unit conversion; nothing to carry"
      - "open scrap orders and packages in progress: validated or cancelled in Odoo before cut-over (door)"
      - the chatter and activities on pickings (mail.message)
    idempotent_on: opening moves on move_id "opening:{db}:{location_id}:{product_id}:{lot_code}"; open documents on document_id "odoo:{db}:stock.picking:{id}"; history on (odoo_db, odoo_move_line_id); the run on run_id "odoo:{db}:{cutover}", and a signed run is frozen
deferred:
  - id: catch_weight
    milestone: M7
    sap: "catch weight management (S/4HANA CWM): a parallel unit of measure managed and valuated beside the base unit"
    design: "A product whose parallel_unit_code is set (product, reserved) is counted in its base unit (C62, a piece) AND in a parallel unit (KGM) whose quantity is not a fixed conversion: the product's KGM row is only the nominal one. The parallel quantity is managed PER LOT: a catch-weight product must be lot-tracked (inv_stocked_product tracking lot or serial), and every move records the ACTUAL parallel quantity beside the base one (inv_move.catch_quantity in catch_unit_code). At goods-in the receiver records the weighed quantity per lot (purchasing pur_receipt_line.catch_quantity; the bill is matched on it, purchasing deferred.catch_weight); at delivery the picker records the weighed quantity, or, where the owner allows, takes it pro rata from the lot's remaining catch quantity (lot on hand in KGM / lot on hand in C62); the sales order keeps it on the delivery row and invoices it in the pricing unit (sales-order deferred.catch_weight). On hand in the parallel unit is the sum of catch_quantity per (product, location, lot), derived like on hand; a count records both (inv_count_entry. catch_quantity). The average cost is kept PER PARALLEL UNIT (value per KGM) for such a product, so a delivery is costed at catch_quantity x average; inv_valuation carries catch_quantity_change and catch_quantity_after. An actual quantity outside catch_tolerance_pct of the nominal one is a gate {gate: catch_tolerance} a second person may accept. The move that empties a lot takes its remaining catch quantity, so no residue is left."
    reserved_columns:
      - table: inv_move
        columns:
          - catch_quantity NUMERIC(19,6) NULL
          - catch_unit_code VARCHAR NULL
      - table: inv_document_line
        columns:
          - catch_quantity_expected NUMERIC(19,6) NULL
      - table: inv_count_entry
        columns:
          - catch_quantity NUMERIC(19,6) NULL
      - table: inv_valuation
        columns:
          - catch_quantity_change NUMERIC(19,6) NULL
          - catch_quantity_after NUMERIC(19,6) NULL
      - table: inv_lot
        columns:
          - catch_unit_code VARCHAR NULL
      - table: inv_settings
        rows:
          - catch_tolerance_pct
          - catch_pro_rata_allowed (not seeded until M7)
      - table: product, pur_receipt_line, so_delivery
        columns:
          - product.parallel_unit_code
          - pur_receipt_line.catch_quantity / catch_unit_code
          - so_delivery.catch_quantity / catch_unit_code
        note: reserved in those specs' deferred blocks
    stories_when_built:
      - receive a lot of 10 bars weighing 24.8 KGM and match the supplier's bill by weight
      - deliver 4 bars of a lot weighed at 9.9 KGM and invoice 9.9 KGM
      - count a lot in pieces and kilograms
      - value a catch-weight product per KGM to zero
  - id: batch_uom
    milestone: M7
    sap: batch-specific units of measure (a proportion or product unit whose conversion is set per batch)
    design: "For a product with lot_conversion_allowed (product, reserved), one unit marked variable_per_lot (e.g. KGM of active ingredient per LTR, or MTR per coil) converts per LOT, not per product: the lot carries its own lot_numerator / lot_denominator of lot_unit_code to the base unit, recorded at goods-in when the lot is created (from the supplier's certificate or a measurement) and FROZEN once any move uses the lot. A move of that lot in the variable unit converts with the lot's fraction (inv_move.conversion_source = lot) and copies it, exactly as a document copies a product conversion today; every other unit still converts with the product's. Availability and reservations in the variable unit are per lot; FEFO and lot selection then decide which lot's conversion a delivery uses."
    reserved_columns:
      - table: inv_lot
        columns:
          - lot_unit_code VARCHAR NULL
          - lot_numerator BIGINT NULL
          - lot_denominator BIGINT NULL
      - table: inv_move
        columns:
          - conversion_source VARCHAR NOT NULL DEFAULT 'product'
      - table: product, prod_product_unit
        columns:
          - product.lot_conversion_allowed (false)
          - prod_product_unit.variable_per_lot (false)
        note: reserved in product's deferred block
    stories_when_built:
      - receive a lot of 200 LTR at 0.62 KGM active per LTR and sell 31 KGM active from it
      - a lot's conversion is frozen once moved
sap_parity:
  - sap: Movement types (101, 122, 201, 301, 311, 321, 541, 551, 601, 651, 701...) as configuration
    ours: different
    where: stock_document.kind and purpose, stock_move from / to location, stock type and owner
    why: each document kind moves between real and virtual locations, types and owners; no movement-type table to configure
  - sap: Goods receipt for a purchase order (101)
    ours: covered
    where: INV-05, INV-20, INV-21
  - sap: Return delivery to the supplier (122 / 161)
    ours: covered
    where: INV-28
  - sap: Goods issue for an outbound delivery (601) and customer returns (651) with inspection
    ours: covered
    where: INV-07, INV-23, INV-14 (against sales-order's RMA)
  - sap: Goods issue to a cost centre and scrapping (201 / 202, 551 / 552 / 553 / 555)
    ours: covered
    where: INV-37, INV-38, goods_issue workflow
  - sap: "Transfer postings: storage location to storage location (311), plant to plant in one or two steps (301 / 303-305) with stock in transit"
    ours: covered
    where: INV-09, INV-53, transfer
  - sap: "Stock types: unrestricted, quality inspection, blocked, per quant"
    ours: covered
    where: "INV-55, INV-36, stock_move stock types (v3: per stock row, the location's status its default and limit)"
  - sap: Transfer postings between stock types (321, 343, 349) without moving
    ours: covered
    where: INV-55, change_stock_type
  - sap: "Special stocks: supplier consignment (K), customer consignment (W), subcontracting (O)"
    ours: covered
    where: INV-45, INV-46, INV-47
  - sap: "Special stocks: sales order stock (E) and project stock (Q)"
    ours: deferred
    where: "-"
    milestone: M7
    why: "stock assigned to one order or project is only needed where it is produced or procured for it: make-to-order production (M7) and project procurement (M5, with projects' cost objects)"
  - sap: Reservations (MB21) and sales order requirements
    ours: covered
    where: INV-13, INV-22, reservation
  - sap: Availability check (ATP) with receipts and transit by date
    ours: covered
    where: INV-49
  - sap: Negative stock allowed per plant / storage location
    ours: covered
    where: INV-17
  - sap: "Physical inventory: documents, count entry, difference posting (MI01 / MI04 / MI07)"
    ours: covered
    where: INV-10, INV-11, INV-12
  - sap: Counting in any unit of entry
    ours: covered
    where: INV-34, count_entry
  - sap: Cycle counting with ABC indicators (MIBC)
    ours: covered
    where: INV-42, INV-43
  - sap: Physical inventory posting block during the count
    ours: different
    where: INV-10
    why: a line's difference is taken at its counted moment, so stock keeps moving during a count; no block is needed
  - sap: Batch management with shelf-life expiry date (MSC1N)
    ours: covered
    where: INV-03, INV-06, lot
  - sap: Batch determination and FEFO / FIFO stock removal with minimum remaining shelf life
    ours: covered
    where: INV-39
  - sap: Batch where-used and recall (MB56)
    ours: covered
    where: INV-41
  - sap: Serial numbers on goods movements and serial history (IQ09)
    ours: covered
    where: INV-06, INV-08, INV-40
  - sap: Moving average price valuation per valuation area (price control V)
    ours: covered
    where: INV-16, INV-31, valuation_row (per company)
  - sap: Standard price valuation (price control S), price differences and standard price release / revaluation
    ours: covered
    where: INV-48, INV-56, standard_price
  - sap: FIFO / LIFO layer valuation
    ours: different
    where: INV-48
    why: SAP's price controls are S and V too (FIFO is a balance-sheet valuation run, not a price control); IAS 2 accepts weighted average, and standard where it approximates cost
  - sap: "Automatic account determination by valuation class (OBYC: BSX, WRX, GBB, PRD, UMB)"
    ours: covered
    where: INV-32, account_map (valuation_class, v3)
  - sap: Stock overview and stock on a posting date (MMBE, MB5B)
    ours: covered
    where: INV-04, INV-30, INV-16
  - sap: "Warehouse structure: storage bins (and storage types / sections) with capacity"
    ours: covered
    where: INV-01, INV-50, location
  - sap: Warehouse unit of measure (LVSME) for handling
    ours: covered
    where: INV-34, product PRD-29
  - sap: Weights and volumes on inbound and outbound deliveries (LIKP BTGEW / NTGEW / VOLUM)
    ours: covered
    where: INV-35
  - sap: WM-level putaway and stock removal strategies (fixed bin, addition to stock, next bin; FIFO / FEFO; pick sequence)
    ours: covered
    where: INV-50, INV-39, INV-51
  - sap: Wave and two-step picking, packing and handling units with SSCC
    ours: covered
    where: INV-51, INV-52, pick_batch, package
  - sap: "EWM: warehouse tasks and orders, RF queues and resources, slotting, labour management, yard, cross-docking"
    ours: deferred
    where: known_gaps
    milestone: post-M8 (on a customer's demand)
    why: these pay off in large, high-volume warehouses with dedicated staff and scanners on every move; an SME to mid-market warehouse is covered by putaway rules, pick batches and packing, and SAP itself sells EWM separately from inventory management
  - sap: Inter-company stock transport order with billing
    ours: different
    where: INV-09
    why: "a move to another company is refused: it is a sale and a purchase (sales-order and purchasing)"
  - sap: "Replenishment: reorder point planning (MRP type VB / VM), min / max, stock transport requisitions"
    ours: covered
    where: INV-44, INV-54, product PRD-37, PRD-38
  - sap: Goods issue to production orders and production storage (261)
    ours: deferred
    where: known_gaps
    milestone: M7
    why: there are no production orders before M7 Make & sell
  - sap: Catch weight management (CWM parallel unit)
    ours: deferred
    where: "deferred: catch_weight"
    milestone: M7
    why: designed, columns reserved; it changes purchasing, sales-order and invoicing at once for weighed goods (an industry need SAP first shipped as IS-CWM), with no reference customer before M7
  - sap: Batch-specific units of measure
    ours: deferred
    where: "deferred: batch_uom"
    milestone: M7
    why: designed, columns reserved; buildable in inventory alone, but nothing orders in a lot's variable unit until process production (M7), so it would ship unused
lifecycle: https://blog.dodil.io/modules/lifecycle.md
module_pattern: https://blog.dodil.io/modules/pattern.md
design_template: https://blog.dodil.io/modules/template.md
