# Sales orders — module spec (generated from modules/sales-order/module.yaml)
# A starting vocabulary for phase 2: correct it with the customer, then write ERP_SALES_ORDER.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 sales-order): 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 sales-order; (2) SHOW the customer the diagram — `erp-compose process --module sales-order --playbook <playbook>` for a brick with playbooks (hr), else `erp-compose bpmn --from ERP_SALES_ORDER.md --out processes/sales-order.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 sales-order  (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 sales-order
  repos:
    - name: erp-brick-sales-order
      role: brick
      tag: v0.2.0
      clone: git clone --depth 1 --branch v0.2.0 https://git.dodil.io/dodil/erp-brick-sales-order.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: brick-business-partner
      role: brick
      tag: v0.4.0
      clone: git clone --depth 1 --branch v0.4.0 https://git.dodil.io/dodil/erp-brick-business-partner.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 sales-order` 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>-sales-order
    version: 0.1.0
    tier: 1
    bricks:
      - { name: sales-order, brick: "brick_sales_order.application.use_cases:SO", version: 0.2.0 }
      - { name: product, brick: "brick_product.application.use_cases:PRODUCT", version: 0.2.2 }
      - { name: business-partner, brick: "brick_bp.application.use_cases:BP", version: 0.4.0 }
    # 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: sales-order
name: Sales orders
short: Orders
version: 12
maturity: tested
summary: Turn an accepted quote into a confirmed order in one step, track what has been delivered, and invoice exactly what is due (on order or on delivery, with deposits up front) without anyone re-typing a line.
decisions:
  - decided: an accepted quote creates a DRAFT order that a person confirms (SO-01, SO-03); the setting confirm_on_acceptance confirms it at once
    by: Seemo, DODIL (reference customer)
    date: 2026-10-18
  - decided: the order's key is sales_order_id (shared.yaml keys.sales_order_id), never purchasing's order_id
    by: Seemo, DODIL (reference customer)
    date: 2026-10-18
  - decided: deliveries are recorded by hand (record_delivery) until the M4 delivery bricks call the same route (SO-23)
    by: Seemo, DODIL (reference customer)
    date: 2026-10-18
  - decided: where contracts are signed, an active contract BILLS DIRECTLY through invoicing's contract adapter (ar plan_billing / raise_draft, source_kind contract) by default, with no order; the setting contract_creates_order raises a draft order instead
    by: Seemo, DODIL (reference customer)
    date: 2026-10-18
  - proposed: a line is priced by product's find_price(product_id, quantity, unit_code, bp_id, currency, priced_on) with priced_on = today, and stores the answer's source as priced_from; an order from a quote copies the accepted prices and is never re-priced
    status: for sign-off
  - proposed: "v3: with inventory installed, a stocked goods line is delivered only by inventory (source inventory); a hand delivery on it is refused, service lines stay by hand; confirm, amend and cancel reserve and release through inventory (SO-23, SO-25)"
    status: for sign-off (wave 2)
  - proposed: Odoo quotations (draft, sent) migrate to brick-quote as open quotes, not as orders; confirmed Odoo orders migrate here, open ones live and the rest as read-only history
    status: for sign-off
  - proposed: "v4: a line copies find_price's pricing_quantity and pricing unit with the price and nets from them exactly; a line from an accepted quote with no pricing quantity is per 1 of its unit"
    status: for sign-off (wave 2)
  - proposed: "v4: a line off the product's delivery multiple WARNS at confirm and amend by default; the owner may set block (delivery_multiple_mode, so:settings:controls)"
    status: for sign-off (wave 2)
  - proposed: "v5: the base price is ALWAYS product's find_price; every other condition (discounts, surcharges, freight, rebate accruals) is a condition record here, found through an access sequence; a confirmed line's conditions are frozen with it"
    status: for sign-off (SAP full-scope pass)
  - proposed: "v5: a customer return is always a returns order (an RMA) referencing the original order line and invoice; the original order is never changed by a return; the credit is raised for what inspection accepted, against the original invoice, keyed on the returns order"
    status: for sign-off (SAP full-scope pass)
  - proposed: "v5: a deposit may be deducted in part, tracked per deposit; each deduction line carries the deposit's tax category (the same rule in ar); an unused deposit is deducted in full by the final invoice or credited on cancellation"
    status: for sign-off (SAP full-scope pass)
  - proposed: "v5: ATP gives every line a promised date (schedule lines) but never blocks a confirmation; unconfirmed quantities are re-promised daily and a later promise is shown for the rep to tell the customer"
    status: for sign-off (SAP full-scope pass)
  - proposed: "v5: rebates accrue on every invoice in the agreement's period and settle as invoicing credit notes, approved by a second person (never the person who set the agreement up)"
    status: for sign-off (SAP full-scope pass)
  - decided: "v5: payment terms on a migrated order are written as ar's own key odoo:<payment_term id> (ar's migration creates the term under that key), so sales-order needs no ar map and the migration order is unchanged (resolved 2026-10-22: shared.yaml conventions.odoo_migration.payment_terms; no ar.terms slice)"
    status: for sign-off (SAP full-scope pass)
facets:
  domain: sales
  industries:
    - any
  customer_words:
    - the customer said yes, now what
    - sales orders
    - order confirmation
    - invoice when we deliver
    - 50% deposit up front
    - what's still to deliver
    - when can you deliver
    - returns and RMA numbers
    - year-end rebate
    - ship to a different address
    - free samples
    - stock held at the customer
    - invoice in stages
  replaces:
    - an order spreadsheet
    - re-typing the quote into the accounts
    - Odoo Sales orders
  pillars:
    - sql
  first_module_fit: high
  depends_on:
    - module: business-partner
      why: the order's customer is the shared party
      required: true
    - module: product
      why: lines name products, and their invoicing policy decides when a line is invoiceable
      required: true
    - module: tax
      why: the order's tax is computed by the tax module
      required: recommended
    - module: crm
      why: an order is created from an accepted quote (brick-quote)
      required: recommended
    - module: ar
      why: invoicing raises the invoices the order asks for
      required: recommended
    - module: payments
      why: the credit hold that blocks confirmation
      required: optional
    - module: inventory
      why: reservations, promised dates (ATP), deliveries, returns inspection and consignment stock (v3, v5)
      required: recommended
    - module: purchasing
      why: third-party orders the supplier ships straight to the customer (v5)
      required: optional
    - module: gl
      why: rebate accruals are posted to the ledger (v5); without it they are reported, not posted
      required: optional
  feeds:
    - ar
    - inventory
    - purchasing
  owns_master_data: []
  references_master_data:
    - business_partner
    - product
    - tax_code
actors:
  - id: sales_rep
    name: Sales
    does: creates orders of any type (from a quote or by hand), confirms them, amends them before delivery, raises returns (RMAs) and credit or debit memo requests, tells the customer the promised dates
    sees: the orders they own; a holder of so:sales_order:read_all sees every order
    permissions:
      - so:order:read
      - so:order:write
      - so:order:confirm
  - id: order_admin
    name: Sales operations / the owner
    does: approves amendments and cancellations of confirmed orders, overrides a credit hold, sets and releases delivery and billing blocks, keeps order types, condition records and rebate agreements, asks for a rebate settlement, sets order policy
    sees: every order
    permissions:
      - so:order:read
      - so:sales_order:read_all
      - so:order:approve
      - so:order:cancel
      - so:order:block
      - so:pricing:write
      - so:rebate:write
      - so:settings:write
  - id: sales_controller
    name: A second person for money going back (the finance controller, the owner)
    does: approves credit and debit memo requests, free-of-charge orders above the limit and rebate settlements; never one they raised or set up (compared by email AND sign-in subject)
    sees: every order, condition and rebate agreement with its accruals
    permissions:
      - so:order:read
      - so:sales_order:read_all
      - so:memo:approve
      - so:rebate:approve
  - id: owner
    name: The owner or a finance controller
    does: sets the controls on order takers (whether amendments need approval, whether an accepted quote confirms itself, the business time zone, which AI steps are on), each from a later date
    sees: every order
    permissions:
      - so:order:read
      - so:sales_order:read_all
      - so:settings:controls
  - id: fulfiller
    name: Whoever delivers (operations, the project lead, the warehouse)
    does: records what has been delivered or done, line by line
    sees: confirmed orders to deliver; never prices
    permissions:
      - so:order:read
      - so:order:deliver
  - id: biller
    name: Whoever invoices
    does: asks for the invoice of what is due, raises the deposit
    sees: every confirmed order
    permissions:
      - so:order:read
      - so:sales_order:read_all
      - so:order:invoice
  - id: customer
    name: The customer
    external: true
    does: sends their purchase order, receives the confirmation
    sees: their own order confirmation, by email or the portal
    permissions: []
  - id: system
    name: The system
    does: creates the order on acceptance, suggests a draft from a PO and compares a PO with the order, derives fulfilment and invoice status, numbers confirmed orders, locks finished orders, re-promises unconfirmed quantities, accrues rebates, records return inspections and supplier shipments reported by inventory and purchasing, imports the Odoo orders once
    sees: everything, through its own service account
    permissions:
      - so:order:read
      - so:order:intake
      - so:order:suggest
      - so:order:finish
      - so:number_series:claim
      - so:order:import
      - so:order:reschedule
      - so:rebate:accrue
      - so:return:inspect
      - so:demand:read
      - so:order:deliver
stories:
  - id: SO-02
    kind: person
    actor: sales_rep
    story: As a sales rep, I want to raise an order by hand when there was no quote, so that a repeat order on the phone is still a real order.
    given: a customer with bp_id 7311, active products, and COLA-075 sold by the bottle (C62) and the 24-pack (PK24)
    when: I add 2 x PK24 of COLA-075 and 3 hours (HUR) of SETUP and save
    then: a draft order dated today (in business_timezone; it cannot be dated earlier) exists; each line is priced by product's find_price(product_id, quantity, unit_code, bp_id, currency, priced_on = today), stores the price, the unit and its conversion, and priced_from (the list, rule and row the answer named), and is taxed by the tax module; nothing is typed but products, units and quantities; a unit the product does not sell in is refused
    screen: Order
    path:
      process: sales-order.sales_order
      choices: {}
    reference: not built
  - id: SO-03
    kind: person
    actor: sales_rep
    story: As a sales rep, I want to confirm an order, so that the customer and the team know it is committed.
    given: a draft order, priced and taxed, for a customer not on credit hold
    when: I confirm it
    then: 'it gets the next number from the series (SO-2026-0001), its prices and tax are frozen, a confirmation goes to the customer when I send it; before I press confirm the order shows its readiness, each gate as {gate, met, reason, fix} (e.g. {gate: credit, met: false, reason: "on hold: 2 invoices over 60 days", fix: "ask an order admin to override"}); confirming with a gate unmet is refused with that reason, and a credit hold only an order admin overrides, with a reason'
    screen: Order
    reference: not built
    customer_varies: whether a PO from the customer is required before confirming
  - id: SO-04
    kind: person
    actor: sales_rep
    story: As a sales rep, I want to record the customer's purchase order number, so that their accounts payable team can match our invoice.
    given: a customer whose order policy says "PO required" from 2026-11-01 (a dated row; a policy cannot start today or earlier, and a correction is a new row from a later date)
    when: I confirm without one on 2026-11-02
    then: refused (gate po_ref, "this customer requires a PO number"); with PO-4471 it confirms and every invoice for the order carries PO-4471; on 2026-10-30 the policy did not yet apply
    screen: Order
    reference: not built
  - id: SO-05
    kind: person
    actor: sales_rep
    story: As a sales rep, I want to amend a confirmed order before it is delivered, so that a change of mind is a revision, not a new order.
    given: a confirmed order with 10 units, none delivered or invoiced
    when: I change it to 12 units
    then: revision 2 exists with the reason; only the changed line is re-priced, by find_price with priced_on = today and a new priced_from; the other lines keep their price and source; approval by an order admin where the control asks for it, never by the rep who amended; reducing below what is already delivered or invoiced is refused (gate not_below_done)
    screen: Order
    reference: not built
  - id: SO-06
    kind: person
    actor: order_admin
    story: As the order admin, I want to cancel an order with a reason, so that the pipeline and the books stop expecting it.
    given: a confirmed order with nothing delivered or invoiced
    when: I cancel it with the reason "customer withdrew"
    then: it is cancelled, keeps its number, and asks invoicing to cancel any draft it requested; an order with a delivery or an issued invoice cannot be cancelled ("credit the invoice, then close the order")
    screen: Order
    reference: not built
  - id: SO-07
    kind: person
    actor: fulfiller
    story: As the person who delivers, I want to record what was delivered or done, line by line, so that invoicing on delivery bills exactly that.
    given: a confirmed order with 12 units of a delivered-policy product
    when: I record 5 delivered on 2026-11-20 with delivery note DN-118
    then: the line shows 5 of 12 delivered, the order shows "partly delivered", 5 units become invoiceable; recording the same delivery note twice records it once; delivering more than ordered, or dating a delivery after today or before the confirmation, is refused; a mistake is corrected by a new correction row (DN-118-C, -2 against DN-118), never by editing DN-118, and never below what is already invoiced
    screen: Deliveries
    reference: not built
  - id: SO-08
    kind: person
    actor: biller
    story: As the biller, I want to invoice what an order has due, so that nothing is billed early, late or twice.
    given: "an order: line 1 policy ordered, 1 unit; line 2 policy delivered, 12 ordered, 5 delivered; nothing invoiced"
    when: I ask for the invoice
    then: invoicing receives one draft request for line 1 x 1 and line 2 x 5, keyed on the order and the request number; asking again with nothing new due creates nothing; the order shows "partly invoiced"
    screen: Order
    reference: not built
  - id: SO-09
    kind: person
    actor: biller
    story: As the biller, I want to raise a deposit before the work starts, so that "50% up front" is a real invoice.
    given: a confirmed order of 10,000.00 net and a setting for a 50% deposit
    when: I raise the deposit
    then: invoicing receives a deposit request of 5,000.00 net (taxed when the payment is received or the invoice issued, whichever is first, per the tax point rule); the next invoices for the order deduct it until it is used; a second deposit beyond the order total is refused
    screen: Order
    reference: not built
  - id: SO-10
    kind: person
    actor: sales_rep
    story: As a sales rep, I want one list of orders with what is still to deliver and to invoice, so that I can answer "where is my order" in a sentence.
    given: orders in every state
    when: I open the list
    then: each row shows the number, the customer, the total, the fulfilment status and the invoice status (both derived); filters by state, customer and date
    screen: Orders
    reference: not built
  - id: SO-11
    kind: person
    actor: sales_rep
    story: As a sales rep, I want to send the customer an order confirmation, so that they have in writing what was agreed.
    given: a confirmed order
    when: I send the confirmation
    then: the document (number, lines, prices, tax, delivery terms, their PO) is produced from the frozen order and the send is recorded; re-sending records a second send
    screen: Order
    reference: not built
  - id: SO-15
    kind: person
    actor: owner
    story: As the owner, I want to set the controls on how orders are taken, so that a rep cannot loosen the rules they work under.
    given: amendment_needs_approval true and the PO-draft AI step off
    when: on 2026-10-22 I set amendment approval off from 2026-11-01 and turn ai_order_from_po to suggest
    then: each control is a dated row; one starting today or earlier is refused ("starts after today, in Europe/London"); a correction is a new row from a later date; a holder of so:settings:write alone is refused on a control; turning an AI step on is recorded as the owner's consent (who, when, which step)
    screen: Settings
    reference: not built
  - id: SO-16
    kind: person
    actor: sales_rep
    story: As a sales rep, I want to accept, change or reject what the AI suggested from a customer's PO, so that nothing the AI read reaches the order without me.
    given: a draft order suggested from PO-4471 with 3 matched lines and one difference from the quote listed
    when: I accept two lines, change the third line's unit from C62 to PK24, and reject the difference as noise
    then: the draft holds the accepted and changed lines, each priced by find_price; the suggestion, the model, what I accepted, changed or rejected, and when are recorded on the order's suggestion log; nothing was on the order before I acted
    screen: Order
    reference: not built
  - id: SO-29
    kind: person
    actor: order_admin
    story: As sales operations, I want order types (standard, rush, cash, returns, credit and debit memo requests, free of charge, consignment), each behaving its own way, so that a return or a free sample is not an ordinary order someone has to remember to treat differently.
    given: "seeded types STANDARD (SO-{yyyy}-{seq:4}), RUSH, CASH, RETURNS (RE-), CREDIT_REQ (CR-), DEBIT_REQ (DR-), FREE_OF_CHARGE (FC-), CONS_FILL, CONS_ISSUE, CONS_PICKUP, CONS_RETURN (CS-), each with direction, billing relevance, a required reference and default blocks; item category rules: STANDARD + product type TRADING -> STD_STOCK, STANDARD + SERVICE -> STD_SERVICE, STANDARD + TRADING with usage drop_ship -> THIRD_PARTY, FREE_OF_CHARGE + any -> FREE"
    when: a rep raises a STANDARD order of COLA-075 and HOST-M, a RETURNS order with no reference, and later tries to change the confirmed STANDARD order to RUSH
    then: "COLA-075 gets item category STD_STOCK (delivery-relevant, billed per its invoicing policy) and HOST-M STD_SERVICE (not delivered from stock), each line keeping the category it was determined with; the RETURNS order is refused (gate reference_required, \"a return names the order line it returns\"); the type change is refused (\"an order's type is fixed once confirmed: cancel it and raise a new one\"); each type numbers from its own series at confirmation, claimed with a plain INSERT, never reused and with no gap from a refused confirmation; a type or rule is a dated config row (from tomorrow), so a confirmed order keeps the behaviour it was confirmed under"
    screen: Settings
    path:
      process: sales-order.sales_order
      choices: {}
    reference: "SAP sales document types (VOV8: OR, SO rush, BV cash, RE returns, G2 / L2 credit / debit memo requests, FD free of charge, KB / KE / KA / KR consignment) and item category determination (VOV4: TAN, TAD, TAS, TANN, REN, KBN, KEN); Odoo has one order kind"
    customer_varies: "which types are used (most firms: standard, returns, credit requests); their number formats"
  - id: SO-30
    kind: person
    actor: sales_rep
    story: As a sales rep, I want each line priced by the base price from our price lists and then the customer's agreed discounts and surcharges found automatically, so that the price is the one agreed without me looking it up.
    given: "pricing procedure STANDARD: 10 BASE (product find_price), 20 DISC_PCT (access sequence: customer + product, then customer + category, then price group + category), 30 SURCH_PCT (category); records: 7311 + COLA-075 5% from 2026-11-01; 7311 + category drinks 3%; price group TRADE + drinks 2% (4% from 100 C62); drinks surcharge 2%; base 1.20 a bottle for COLA-075 and 1.80 for COLA-150; DISC_PCT manual limit 10%"
    when: on 2026-11-02 I order 120 C62 of COLA-075 and 120 C62 of COLA-150 for 7311, then type a DISC_PCT of 12% on the second line, then confirm
    then: 'COLA-075: BASE 144.00, DISC_PCT -7.20 (customer + product found first: the access stops at the first hit), SURCH_PCT +2.74 on 136.80, net 139.54; COLA-150: BASE 216.00, DISC_PCT -6.48 (customer + category), SURCH_PCT +4.19, net 213.71; each condition is a line_condition row naming its record (priced_from per condition) and rounded once, half up, to the minor unit; 12% is refused ("DISC_PCT may be changed by hand up to 10%") and 8% is accepted and recorded as manual with who; confirming freezes every condition; an amendment re-prices only the changed line; a record dated today or earlier cannot be added (records start after today); a NUMERIC overflow (a rate or amount above its bound) is a 422 with the reason'
    screen: Order
    path:
      process: sales-order.sales_order
      choices: {}
    reference: SAP condition technique (V/06 condition types, V/07 access sequences, V/08 pricing procedure, VK11 records with scales, KONV / PRCD_ELEMENTS on the item); Odoo pricelist rules and a line discount
    customer_varies: "whether any discount or surcharge is agreed per customer, group or category (many small firms: none, the price list is enough)"
  - id: SO-31
    kind: person
    actor: sales_rep
    story: As a sales rep, I want an order-level discount and the freight charged once for the whole order and spread over its lines, so that the invoice shows the customer's deal and our carriage cost without arithmetic by hand.
    given: "the order of SO-30 (net 139.54 and 213.71 = 353.25) for ship-to 7313 in GB; condition FREIGHT for country GB: 0.12 per KGM of gross weight, at least 15.00; the bottles weigh 0.79 KGM (COLA-075) and 1.60 KGM (COLA-150) gross (product measures in force today)"
    when: I add a header discount HDR_DISC of 2% and confirm
    then: "HDR_DISC 7.07 (2% of 353.25 rounded once) spread by net: 2.79 on line 1 and the remainder 4.28 on line 2; FREIGHT 34.42 (286.8 KGM x 0.12) spread by gross weight: 11.38 on line 1 and the remainder 23.04 on the heaviest line; nets 148.13 and 232.47, order net 380.60, exactly the sum; every share lands on a line so invoicing bills and taxes it with the goods; a line with an unknown weight leaves FREIGHT uncomputable and confirmation refused (gate freight_computable, fix \"record the unit's weight in Products\"); the weights used are copied on the line with their valid_from"
    screen: Order
    path:
      process: sales-order.sales_order
      choices: {}
    reference: SAP header conditions (HA00 percentage, HB00 absolute) distributed by net value, freight KF00 by weight, group conditions; Odoo has delivery carriers adding a freight line
    customer_varies: whether freight is charged, and by weight, by order value or flat
  - id: SO-32
    kind: person
    actor: order_admin
    story: As sales operations, I want a rebate agreement with a customer (a year's purchases, tiers, paid back at the end), so that the year-end rebate is calculated from the invoices instead of a spreadsheet.
    given: customer 7311; drinks invoiced to them in 2027 will earn 1% from 0, 2% from 50,000.00 and 3% from 100,000.00, retroactive to the first pound; expected tier 2%
    when: on 2026-12-10 I open agreement RB-2027-7311 for 2027-01-01 to 2027-12-31, basis invoiced net of category drinks, accrual rate 2%, and activate it; then try one starting 2026-12-01, and change the scale after the first accrual
    then: RB-2027-7311 is active from 2027-01-01; the back-dated one is refused (gate starts_after_today); the scale change is refused once an accrual exists ("end it and open a new agreement from a later date"); an agreement names the customer (or a price group) and the products, categories or all; the basis is invoice net less credit notes, by the invoice's issue date in business_timezone
    screen: Rebates
    path:
      process: sales-order.rebate_agreement
      choices: {}
    reference: SAP rebate processing / settlement management (condition contracts, WCOCO; formerly VBO1 rebate agreements with BO01-BO03 conditions, retroactive scales, accruals, VBOF / partial settlement); Odoo has no rebates (loyalty programs only)
    customer_varies: whether rebates are agreed at all; basis (volume, value, category); retroactive or tier-by-tier
  - id: SO-34
    kind: person
    actor: sales_controller
    story: As the finance controller, I want a rebate settlement calculated and checked before the credit goes to the customer, so that we pay back exactly what the agreement earned, once.
    given: RB-2027-7311 ended 2027-12-31; invoiced drinks net 120,000.00 less credits; accrued 2,400.00; a partial settlement of 1,000.00 credited in July
    when: on 2028-01-05 the order admin asks for the final settlement; the order admin approves it under a second account; then I approve it
    then: the settlement is 3,600.00 (3% of 120,000.00, the tier reached, retroactive) less 1,000.00 already settled = 2,600.00; the order admin's second account is refused (same email or same sign-in subject); my approval posts the true-up of the accrual (1,200.00) to the ledger and asks invoicing for one credit note to 7311 keyed rebate:RB-2027-7311:2, with lines per tax category of the basis and the account purpose rebate (so invoicing debits the accrued rebates, not revenue again); approving twice credits once; the agreement closes, its accrual nets to exactly 0.00
    screen: Rebates
    path:
      process: sales-order.rebate_agreement
      choices: {}
    reference: SAP rebate settlement (VBOF, final settlement credit memo request B1 / B2, accrual reversal)
  - id: SO-35
    kind: person
    actor: sales_rep
    story: As a sales rep, I want each line to show when it can be delivered from stock and what is coming in, so that I promise the customer a date we can keep.
    given: today 2026-11-02; COLA-075 at WH1 360 LTR unrestricted, 180 LTR reserved; PO-0101 brings 720 LTR on 2026-11-09 (goods-in 1 day, product site WH1); pick and pack 1 day; ship-to 7313 is 1 day from WH1
    when: I order 480 C62 (360 LTR) for delivery on 2026-11-04
    then: "inventory's ATP answers 180 LTR now and 720 from 2026-11-10; the line gets two schedule lines: 240 C62 confirmed for 2026-11-04 and 240 C62 for 2026-11-12; the order shows \"partly confirmed: 240 on 4 Nov, 240 on 12 Nov\" and the confirmation document prints both; confirmation is never blocked by a shortfall; a lot expiring before the delivery date is not counted (the customer's minimum shelf life); with complete delivery (SO-37) the whole line is promised for 2026-11-12; without inventory installed the requested date is kept and the answer says nothing was checked"
    screen: Order
    path:
      process: sales-order.sales_order
      choices: {}
    reference: "SAP availability check with ATP quantity and delivery scheduling (backward and forward: pick-pack, loading, transit), schedule lines VBEP with confirmed quantities; Odoo shows forecasted quantity and a commitment date"
    customer_varies: whether dates are promised from stock and receipts, or only from stock on hand
  - id: SO-37
    kind: person
    actor: sales_rep
    story: As a sales rep, I want each customer's delivery rules (part deliveries allowed or not, how many, what tolerance), so that the warehouse ships the way the customer wants without a phone call.
    given: "7311: part deliveries allowed, at most 3 per line, under-delivery tolerance 2%, over-delivery 0%; 8420: complete order only"
    when: inventory asks how to deliver an order for each; 8420's order has one line short; 7311's line of 100 is delivered 98, then a fourth part delivery is tried on another line, and 101 on a line of 100
    then: "GET /sales-orders/{sales_order_id}/fulfilment answers each order's rule (copied from the customer's policy at confirmation, changeable on the order by the rep before the first delivery); inventory holds 8420's delivery until every line is reserved in full; 98 of 100 closes the line (within 2%): nothing is back-ordered and invoicing bills 98; the fourth part delivery is refused (gate max_partials) and 101 (gate within_tolerance); lines to two ship-tos or from two warehouses become two deliveries; orders of one ship-to may go in one delivery where the customer allows combination"
    screen: Order
    path:
      process: sales-order.sales_order
      choices: {}
    reference: "SAP complete delivery (KZAZU), partial delivery agreement per item (KZTLF: up to 9 partials, A / B / C / D), under / over-delivery tolerance (UNTTO / UEBTO), order combination, delivery split by ship-to and shipping point"
    customer_varies: whether customers accept part deliveries; tolerances for bulk goods
  - id: SO-38
    kind: person
    actor: order_admin
    story: As sales operations, I want to say what an order of each type must contain before it is confirmed, delivered or billed, so that an incomplete order stops at the right step and says what is missing.
    given: "incompletion rules: STANDARD: delivery_terms for a ship-to outside the company's country blocks delivery, customer_po_ref blocks billing where the customer's policy asks; RETURNS: return_reason blocks confirmation; CREDIT_REQ: reference_invoice blocks confirmation"
    when: a rep confirms an export order with no delivery terms, inventory asks to deliver it, and the biller asks to invoice it without a PO
    then: "the order's readiness lists {gate: incomplete:delivery_terms, met: false, reason: \"an export order needs its delivery terms (Incoterms)\", fix: \"Order: delivery terms\"} under delivery, and incomplete:customer_po_ref under billing; confirmation is allowed (the rule blocks delivery only); inventory's fulfilment answer says delivery blocked by incompletion; the invoice request is refused naming the field; the Orders screen filters incomplete orders by what they block; the rules are dated config rows per order type"
    screen: Settings
    path:
      process: sales-order.sales_order
      choices: {}
    reference: "SAP incompletion procedure (OVA2 / VUA2: fields per procedure with status groups blocking delivery, billing or saving; incompletion log V.02)"
  - id: SO-39
    kind: person
    actor: order_admin
    story: As sales operations, I want to stop an order from being delivered or billed for a reason, and release it, so that a dispute or a check holds the right step and nothing else.
    given: block reasons CHECK_TERMS (delivery) and PRICE_DISPUTE (billing); confirmed order SO-2026-0020
    when: I set the delivery block CHECK_TERMS with a note; inventory raises the delivery; I release it; I set PRICE_DISPUTE and the biller asks for the invoice; a rep tries to release a block
    then: "the block is an appended row with who and why; inventory still reserves but the delivery does not reach the pick list (fulfilment: delivery_blocked) until the release, also appended; the invoice request is refused (gate billing_block, \"on hold: PRICE_DISPUTE\"); the rep is refused (so:order:block); a CREDIT_REQ or FREE_OF_CHARGE order starts with its type's default block APPROVAL, released only by approval (SO-42, SO-43)"
    screen: Order
    path:
      process: sales-order.sales_order
      choices: {}
    reference: SAP delivery block (LIFSK) and billing block (FAKSK) on the header and item, with reasons (OVLS, OVV3)
  - id: SO-40
    kind: person
    actor: sales_rep
    story: As a sales rep, I want an order to know who ordered, where it goes, who gets the invoice and who pays, so that the depot gets the goods, head office gets the bill and the right account's credit is checked.
    given: "sold-to 7311 Acme Ltd; partner rows from 2026-10-01: ship-to 7312 Acme Leeds depot (default) and 7313 Acme York, bill-to 7311, payer 7400 Acme Group Treasury; 7400 is on credit hold, mode block"
    when: I raise an order for 7311, pick ship-to 7313, try ship-to 9999, and confirm
    then: "the order defaults ship-to 7312, bill-to 7311 and payer 7400 from the rows in force on the order date and copies them; 7313 is accepted; 9999 is refused (\"9999 is not a ship-to of 7311\"); the credit gate reads the PAYER (payments GET /customers/7400/credit-ok) and refuses; tax is computed for the ship-to's country and the sold-to's VAT status; invoicing receives bp_id = 7400 (the payer, whose receivable it is), sold_to 7311, ship_to 7313 and bill_to 7311 (whose billing profile addresses the invoice); each partner must be an active business partner with the customer role (ship-to: the ship_to role); a partner change after the first delivery is refused; partner rows are dated, from tomorrow"
    screen: Order
    path:
      process: sales-order.sales_order
      choices: {}
    reference: SAP partner functions SP sold-to, SH ship-to, BP bill-to, PY payer (KNVP, partner determination procedure); Odoo partner_invoice_id and partner_shipping_id
    customer_varies: whether any customer ships to depots or is paid for by a group company
  - id: SO-41
    kind: person
    actor: sales_rep
    story: As a sales rep, I want to authorise a customer's return with an RMA number before the goods come back, and credit only what the warehouse accepts, so that returns are expected, checked and refunded once.
    given: SO-2026-0012 line 1 delivered 24 C62 of COLA-075 (inv:WH1/OUT/00001), invoiced on INV-2026-0040 at 1.20; return reasons DAMAGED and WRONG_ITEM (inspect, full credit), CHANGED_MIND (inspect, 10% restocking fee); return_credit_on inspection
    when: I raise a RETURNS order for 6 C62 referencing SO-2026-0012 line 1, reason DAMAGED, and confirm it; the goods arrive and inventory reports 5 accepted (4 back to stock, 1 scrapped) and 1 rejected; I also try a return of 30
    then: "RE-2026-0001 is the RMA number on the confirmation sent to the customer; the line copies the original's price, unit and tax category (never re-priced) and names the original order line, delivery and invoice; inventory is told to expect it (POST /expected-returns); 30 is refused (gate within_delivered, \"24 delivered, 0 returned: at most 24\"); on the inspection result the order asks invoicing for one credit note against INV-2026-0040 for 5 C62 (6.00 plus VAT), keyed so:RE-2026-0001:1 and carrying the returns order's line, so the original order still reads 24 delivered, 24 invoiced; the rejected 1 is shown with inventory's reason and credited nothing; return_credit_on receipt credits at receipt instead; a serial-tracked product returns only a serial delivered to this customer (inventory's gate)"
    screen: Returns
    path:
      process: sales-order.return_order
      choices: {}
    reference: "SAP returns order RE / advanced returns management (RMA, returns delivery, inspection, logistical follow-up: restock, scrap, return to supplier; refund determination, credit memo); Odoo stock.return.picking and the RMA apps"
    customer_varies: whether returns are authorised first; restocking fees; credit on receipt or after inspection
  - id: SO-42
    kind: person
    actor: sales_controller
    story: As the finance controller, I want a credit or a debit to a customer raised as a request and approved by me before invoicing sees it, so that money only moves on an approved reason.
    given: "INV-2026-0040 to 7311: 24 C62 at 1.20 (28.80 net); the price should have been 1.10"
    when: a rep raises CREDIT_REQ for 24 C62 at 0.10 (2.40) referencing INV-2026-0040 line 1, reason PRICE_ERROR, and DEBIT_REQ for freight forgotten (15.00); the rep approves the credit under a second account; then I approve both
    then: "CR-2026-0001 and DR-2026-0001 are confirmed with the billing block APPROVAL; the rep's second account is refused (same email or same sign-in subject); my approval releases the block: invoicing receives POST /credit-notes against INV-2026-0040 keyed so:CR-2026-0001:1, its lines carrying CR-2026-0001's line (the original order's billed quantity is untouched), and a debit draft keyed so:DR-2026-0001:1 naming INV-2026-0040 in its text; a credit above the invoice line's net less earlier credits is refused (gate within_invoiced, claim rows per invoice line so two requests cannot both take the last pound); neither is delivery-relevant"
    screen: Returns
    path:
      process: sales-order.sales_order
      choices: {}
    reference: SAP credit memo request G2 and debit memo request L2 with billing block 08 until released (V.23), credit memo G2 / debit memo L2 billing
  - id: SO-43
    kind: person
    actor: sales_rep
    story: As a sales rep, I want to send free samples and replacements as orders that are delivered and costed but never billed, so that stock and cost are right and nobody invoices a gift by mistake.
    given: FREE_OF_CHARGE approval limit 250.00 of statistical value; samples of 12 C62 COLA-075 for prospect 7311; a replacement DRILL-500 (base price 320.00) referencing RE-2026-0002
    when: I raise both and confirm
    then: every line is priced by the procedure for statistics only (12 x 1.20 = 14.40 shown, net 0.00) and its item category FREE is not billing-relevant; the samples confirm; the replacement waits for a controller (gate free_of_charge_approval, 320.00 above 250.00; the requester never approves, by email and sub); inventory delivers both with purpose free_of_charge, so the cost goes to the samples account (inventory's account map), not to cost of sales; nothing is ever requested from invoicing; the order is done when delivered
    screen: Order
    path:
      process: sales-order.sales_order
      choices: {}
    reference: SAP free-of-charge delivery FD / subsequent free-of-charge delivery SDF, item category KLN / TANN (not billing relevant, statistical pricing)
  - id: SO-44
    kind: person
    actor: sales_rep
    story: As someone at the trade counter, I want a rush order that ships today and a cash sale that is delivered, invoiced and paid on the spot, so that a walk-in customer leaves with the goods and a receipt.
    given: types RUSH (delivery created at confirmation, priority 1) and CASH (delivery and invoice at confirmation, paid on the spot); invoicing's owner control auto_issue_sources contains sales_order:cash
    when: I confirm a RUSH order for 7311 at 10:00, and a CASH order of 6 C62 COLA-075 for a walk-in customer
    then: the RUSH order's reservation asks inventory for a delivery today with priority rush, first on the pick list; the CASH order skips the credit gate (paid now), inventory's delivery is validated at the counter (a service line is recorded by hand), the invoice is requested and issued in the same step, and the cashier records the payment in payments against that invoice; a CASH order takes no deposit and no billing plan; both follow the normal readiness gates otherwise
    screen: Order
    path:
      process: sales-order.sales_order
      choices: {}
    reference: SAP rush order SO (immediate delivery) and cash sale BV (immediate delivery and billing, cash receipt); Odoo Point of Sale (outside these bricks)
    customer_varies: whether there is a trade counter at all
  - id: SO-45
    kind: person
    actor: sales_rep
    story: As a sales rep, I want to keep our stock at a customer's site and bill only what they use, so that the customer has goods at hand and we invoice consumption, not shipments.
    given: 7311 keeps consignment stock of COLA-075 at its site (inventory location UK1:CONSIGNMENT:7311, ours and valued by us)
    when: "I raise CONS_FILL for 240 C62; 7311 reports using 60: CONS_ISSUE for 60; then CONS_PICKUP of 24; then CONS_RETURN of 6 of the used ones; then CONS_ISSUE for 200"
    then: "CONS_FILL is delivered by inventory into 7311's consignment stock: not invoiced, not available to other orders; CONS_ISSUE takes 60 out of it to the customer, costed then, and is invoiced at the price on the issue date (find_price priced_on the issue date); CONS_PICKUP moves 24 back to WH1 and bills nothing; CONS_RETURN credits 6 against the issue's invoice (a return, SO-41); CONS_ISSUE for 200 is refused (gate consignment_on_hand, \"7311 holds 162 C62 on consignment\"); the consignment stock is read from inventory, never kept here"
    screen: Order
    path:
      process: sales-order.sales_order
      choices: {}
    reference: SAP customer consignment KB fill-up, KE issue, KA pick-up, KR return, special stock W; Odoo has consignment only for supplier stock (owner on quants)
    customer_varies: whether any customer holds our stock
  - id: SO-46
    kind: person
    actor: biller
    story: As the biller, I want a big job invoiced in stages (on order, on installation, on acceptance), and repeating lines billed by period, so that cash comes in as the work progresses and no stage is billed twice.
    given: "order SO-2026-0030: line 1 PROJ-INSTALL 20,000.00 with milestones M1 30% on confirmation, M2 40% on installed, M3 30% on accepted; line 2 12 x HOST-M monthly"
    when: the order is confirmed, the fulfiller releases M2 when installed, M3 is released, and the invoice is requested after each
    then: 'M1 is due at once: a request of 6,000.00 (an invoice line naming the order line, "Milestone 1 of 3: on order (30%)"); line 2 goes to invoicing as a schedule (POST /schedules, SO-20); M2 holds a billing block until released, then 8,000.00; M3 takes the remainder (20,000.00 - 6,000.00 - 8,000.00 = 6,000.00) so the stages sum exactly even when percentages do not divide evenly; confirming with milestones that do not total 100% is refused (gate plan_complete); a milestone line is billed by value: its billed net never exceeds its released milestones; amending its price re-spreads only unreleased milestones; equal instalments of a fixed total go to invoicing as a schedule with billing_kind instalment'
    screen: Order
    path:
      process: sales-order.sales_order
      choices: {}
    reference: "SAP billing plans: milestone billing (billing plan type 01, milestones from the project or by date, billing block per date) and periodic billing (type 02); Odoo down payments by percentage, and subscriptions"
    customer_varies: whether large jobs are billed in stages; on what events
  - id: SO-47
    kind: person
    actor: biller
    story: As the biller, I want each invoice to take off part of a deposit in proportion, or the whole of it, so that the deposit is used up exactly by the end and the tax on it is right.
    given: order of 10,000.00 net, standard rated; deposit invoice D1 5,000.00 (tax category standard) and D2 1,000.00 (standard), both issued; deduction mode proportional (the order's default)
    when: a first part invoice of 4,000.00 of goods is requested, then the final invoice of 6,000.00
    then: "the first invoice deducts 2,400.00 (the deposits' share, 6,000 / 10,000 x 4,000 = 2,400.00, taken oldest first: 2,400.00 from D1) with one deduction line per deposit naming deducts_invoice_id and carrying the deposit's tax category; D1 has 2,600.00 left, D2 1,000.00; the final invoice deducts everything left (2,600.00 from D1 and 1,000.00 from D2); a deduction above a deposit's remaining, or from a deposit still a draft, is refused; two concurrent requests cannot deduct the same amount twice (a claim row per (deposit, seq), plain INSERT); modes full_first (each invoice deducts as much as it can) and manual (the biller types an amount per deposit) exist per order; cancelling an order with deposit left asks invoicing for a credit note against the deposit invoice"
    screen: Order
    path:
      process: sales-order.sales_order
      choices: {}
    reference: SAP down payment requests (FAZ) and clearing on the final invoice (partial clearing allowed, by the down payment's tax code); ar AR-15 keeps the same rule
  - id: SO-48
    kind: person
    actor: sales_rep
    story: As a sales rep, I want an item the supplier ships straight to the customer ordered from them when I confirm, and delivered when they ship, so that we sell what we never stock without anyone re-keying it.
    given: PRINTER-X (TRADING) sold to 7311 for ship-to 7313, usage drop_ship (item category THIRD_PARTY); purchasing installed
    when: I confirm the order; purchasing later records the supplier's shipping notice SN-55 for 2; a fulfiller tries to record a delivery by hand; I try to cancel after purchasing ordered it
    then: confirmation asks purchasing once for a purchase request for 2 PRINTER-X delivered to 7313 (POST /purchase-requests/from-sales-order, keyed so:<sales_order_id>:<line_no>@r<revision>), and nothing is reserved in inventory; purchasing records the shipment and calls record_delivery with source purchasing and delivery_ref pur:SN-55, so the line is delivered and invoiceable per its policy; the hand delivery is refused ("a third-party line is delivered by the supplier"); the cancellation is refused with purchasing's reason ("PO-0144 is confirmed with the supplier") until purchasing cancels it
    screen: Order
    path:
      process: sales-order.sales_order
      choices: {}
    reference: SAP third-party order processing (item category TAS, automatic purchase requisition, statistical goods receipt, billing on the supplier's invoice or shipment); Odoo dropship route
    customer_varies: whether any supplier drop-ships
  - id: SO-12
    kind: system
    actor: system
    trigger: on read (derived)
    story: The system works out fulfilment and invoice status from quantities, so that "delivered" and "invoiced" are never stale.
    given: a line of 12, 5 delivered, 5 invoiced
    when: anyone opens the order
    then: fulfilment partly delivered, invoice status partly invoiced, to invoice 0 (delivered policy) or 7 (ordered policy); nothing stored but the quantities
    reference: not built
  - id: SO-13
    kind: system
    actor: system
    trigger: when the last line is fully delivered and invoiced
    story: The system locks a finished order, so that a done order cannot be edited by accident.
    given: an order whose every line is delivered and invoiced in full
    when: the last invoice is issued
    then: 'the order is done; an edit is refused ("done: raise a new order"); this runs once however often it is triggered'
    reference: not built
  - id: SO-14
    kind: system
    actor: system
    trigger: when a customer's purchase order arrives by email
    story: The system drafts an order from the customer's purchase order, so that the rep checks instead of types.
    given: a PDF purchase order from a known customer quoting quote Q-2026-0042
    when: it is read
    then: a suggestion (lines matched to product_id and unit_code with a confidence, the PO number, differences from the quote) shown on an empty draft for the rep (SO-16); nothing is on the order until a person accepts it, and nothing is confirmed without a person
    reference: not built
  - id: SO-33
    kind: system
    actor: system
    trigger: every night for the previous business day's issued invoices and approved credit notes (and on demand)
    story: The system accrues each rebate agreement as invoices are issued, so that the books carry what we will owe the customer before the year ends.
    given: RB-2027-7311 active, accrual rate 2%; on 2027-02-03 invoicing issued INV-2027-0101 to 7311 with 10,000.00 of drinks; on 2027-02-10 a credit note of 500.00 against it
    when: the nightly accrual runs for 2027-02-03 and 2027-02-10, and again for 2027-02-03
    then: an accrual row of 200.00 keyed (agreement, invoice_id, line_no) and a journal to the ledger (rebate expense 200.00 debit / accrued rebates 200.00 credit, journal_id derived from (agreement, source document)); the credit note reverses 10.00 the same way; the re-run writes nothing; the basis is read from invoicing (GET /billed-lines), never from ar_ tables; the business date is today in business_timezone, never the UTC date, and a run never goes back past a signed migration or a closed period (the journal is refused by the ledger and kept pending with its reason)
    reference: SAP rebate accruals posted with each billing document (BO01 accrual condition, ERB / ERU accounts)
  - id: SO-36
    kind: system
    actor: system
    trigger: every business day at the start of the day (the composition's clock), and when an order is cancelled
    story: The system re-promises every quantity not yet delivered against the stock and receipts it can see, so that a later supply date reaches the rep before it reaches the customer.
    given: SO-2026-0041 line 1 has 240 C62 confirmed for 2026-11-12 against PO-0101 arriving 2026-11-09; purchasing moves PO-0101 to 2026-11-16; another order's cancellation frees 90 LTR today
    when: the re-promise runs on 2026-11-05, and runs again the same day
    then: "open schedule lines are re-checked in order of priority (rush first) then order date (first come, first served); the 240 C62 now confirm 120 for 2026-11-07 (from the freed 90 LTR) and 120 for 2026-11-19, appended as a new schedule version with the reason; inventory's reservation is re-sent for the same revision with schedule version 2; the order's owner gets a task \"tell 7311: 120 C62 now 19 Nov\"; an EARLIER date is applied only to quantities not yet promised to the customer and is otherwise offered, never pushed; the second run the same day writes nothing"
    reference: SAP backorder processing and rescheduling (V_V2, ATP re-check, BOP in aATP)
  - id: SO-27
    kind: person
    actor: sales_rep
    story: As a sales rep, I want a product priced per 100 to stay priced per 100 on the order, so that a line of screws bills to the penny the customer was quoted.
    given: SCREW-M4, base C62, at 2.4500 per 100 C62 on the customer's list (PRD-31); the customer's discount 10% on the line
    when: I order 250 C62, then add a line of 3 BX500 (a box of 500 with no price row of its own), then amend the first line to 400
    then: line 1 holds unit_price 2.4500, pricing_quantity 100, pricing_unit_code C62 with its conversion, and net 5.51 (250 x 2.4500 / 100 = 6.125, less 10% = 5.5125, rounded once); line 2 is in BX500 but priced in C62 per 100 (the row's unit, as find_price answered), quantity_priced 1 500 and net 36.75 before discount; nothing is divided down to a piece price; the amendment re-prices line 1 only (9.80 before discount, 8.82 after); invoicing receives the pricing quantity on each line so the invoice nets the same
    screen: Order
    reference: SAP condition pricing unit carried on the sales item (KOMV-KPEIN / KMEIN, VBAP net value); Odoo has none
  - id: SO-28
    kind: person
    actor: sales_rep
    story: As a sales rep, I want to be told when a quantity breaks the product's delivery unit, so that we do not promise 20 bottles that ship in sixes.
    given: COLA-075 delivery rule multiples of 6 C62 (PRD-30); delivery_multiple_mode warn (the default)
    when: I confirm an order of 20 C62; then the owner sets block from tomorrow and I confirm another order of 20 C62, and one of 2 PK24, and amend the first order to 22
    then: 'the first confirms with the gate met in warn mode and its reason shown and recorded on the order {gate: delivery_multiple, met: true, reason: "COLA-075 is delivered in multiples of 6 C62: 20 is not one (18 or 24)", fix: "change to 18 or 24, or confirm as it is"}; under block the second is refused with met false and the same reason; 2 PK24 (48 C62) passes; the amendment to 22 is checked the same way under the mode in force on its date; an order from an accepted quote meets the same gate; a line of a product with no delivery rule always passes'
    screen: Order
    reference: SAP delivery unit and minimum delivery quantity in the sales item (MVKE-SCHME, MVKE-LFMNG), the rounding message in VA01
    customer_varies: whether a broken pack is a warning or not allowed at all
  - id: SO-01
    kind: integration
    actor: system
    trigger: when a quote version is accepted (brick-quote decision)
    story: An accepted quote becomes a draft order in one step, so that nothing is re-typed.
    given: quote Q-2026-0042 version 2 accepted, with three lines and a customer
    when: the acceptance is handed over
    then: "one draft order keyed sales_order_id = \"quote:Q-2026-0042@v2\" with the version's lines copied as accepted: product_id, description, quantity, unit_code (the quote line's, or the product's sales unit for a quote line written before units), list_price and unit_price, and priced_from = the quote line (quote:Q-2026-0042@v2#1) with the quote's own source and priced_on; the order never re-prices an accepted line; tax is computed by the tax module for the order date; handing it over twice returns the same order; where the control says so it is confirmed at once, through the same readiness gates as a person. v5, the exact seam: the composition's adapter is the ONE caller of brick-quote's POST /quotes/{quote_id}/versions/{version}/decision for an acceptance; on its 2xx with outcome ACCEPTED it reads GET /quotes/{quote_id} (the accepted version) and calls POST /sales-orders/from-quote; a quote line not priced by product (its priced_from does not name a product price list row, PRD-20) is refused (409, gate priced_by_product, fix \"re-price the quote from product before it is sent\"), so a price from a second price book never reaches an order; the order's partners (SO-40) and type STANDARD are defaulted as for a hand order"
    owner: sales-order
    reference: "the route exists (erp-brick-sales-order POST /sales-orders/from-quote, idempotent on the key); the adapter is not built, and brick-quote still prices from its own book (l2c leftovers): until quote reads find_price (product PRD-20), the composition does not install SO-01"
  - id: SO-20
    kind: integration
    actor: system
    trigger: when an order is confirmed and a line is recurring or metered
    story: A repeating line becomes a billing schedule in invoicing, so that monthly lines bill themselves.
    given: a confirmed order with a recurring line of 12 periods at 120.00
    when: it is confirmed
    then: invoicing receives plan_billing for that line, keyed "{sales_order_id}|{line_no}"; repeating the call creates nothing
    owner: ar
    reference: not built
  - id: SO-21
    kind: integration
    actor: biller
    trigger: when the biller asks for an invoice or a deposit (SO-08, SO-09)
    story: The order asks invoicing for a draft; invoicing owns the invoice.
    given: invoiceable quantities on an order
    when: the request is made
    then: invoicing raises one draft per request, keyed "so:{sales_order_id}:{request_no}", each line carrying sales_order_id and line_no; the order reads invoiced quantities back from invoicing and never writes ar_ tables
    owner: ar
    reference: not built
  - id: SO-22
    kind: integration
    actor: system
    trigger: before confirmation
    story: The order reads whether the customer is on credit hold.
    given: payments derives a hold for the customer
    when: the rep confirms
    then: the hold, its reason and the hold mode (warn | block) come from payments' read route (credit holds are payments', decided 2026-10-18); the order refuses or warns as that mode says
    owner: payments
    reference: not built
  - id: SO-23
    kind: integration
    actor: system
    trigger: when inventory validates a delivery or a customer return (milestone M4; v3)
    story: With inventory installed, a stocked goods line is delivered only from inventory, so that the warehouse and the order agree and nobody keys a delivery twice.
    given: inventory installed; an order with line 1 of 48 bottles of COLA-075 (stocked) and line 2 of 3 HUR installation (a service)
    when: inventory validates WH1/OUT/00001 for 24 bottles of line 1, and a fulfiller records 5 delivered by hand on line 1 and 3 HUR on line 2
    then: "inventory's call (POST /sales-orders/{sales_order_id}/deliveries, source inventory, delivery_ref inv:WH1/OUT/00001) records 24 on line 1 once, however often it is retried; the hand delivery on line 1 is refused (\"COLA-075 is stocked: its deliveries come from inventory\"); the 3 HUR on line 2 are recorded by hand as in v2; the order's rules (no over-delivery, idempotent per reference) apply unchanged; without inventory every line is delivered by hand"
    owner: sales-order
    reference: not built
  - id: SO-24
    kind: integration
    actor: system
    trigger: on the one-off Odoo migration (milestone M8), after business-partner, product and tax have migrated
    story: The customer's Odoo sales orders arrive once, open ones live and the rest as history, and can be re-run safely.
    given: an Odoo database with 40 confirmed orders, 6 of them open (part delivered or part invoiced), 3 cancelled
    when: the migration runs twice
    then: orders keyed "odoo:<company_id>:<sale.order name>" keep their Odoo number and prices; open orders are confirmed with an opening delivery per line of qty_delivered; the rest are done or cancelled, read-only, never re-priced or re-taxed, and ask invoicing for nothing; the second run changes nothing; the reconciliation (migration.odoo.reconcile) shows zero unexplained differences before the customer signs it
    owner: sales-order
    reference: not built
  - id: SO-25
    kind: integration
    actor: system
    trigger: when an order is confirmed, amended or cancelled with inventory installed (v3)
    story: The order reserves its stocked lines in inventory, so that what is promised to one customer is not sold to another.
    given: inventory installed; an order of 48 bottles of COLA-075 and 3 HUR installation
    when: it is confirmed (revision 1), amended to 60 bottles (revision 2), then cancelled
    then: confirm calls POST /reservations/sales-orders/{sales_order_id} with revision 1 and line 1 only as stocked (inventory ignores and names the service line, and the order keeps stocked false on it); the amendment calls it again with revision 2 and 60; cancel calls POST /reservations/sales-orders/{sales_order_id}/release with the reason; a retry of any call changes nothing; a short reservation is shown on the order, and never blocks confirmation
    owner: inventory
    reference: not built
  - id: SO-26
    kind: system
    actor: system
    trigger: when a delivery or a correction is recorded (v3)
    story: A delivered quantity converts exactly to the product's base unit, so that the order, the stock and the invoice agree to the last unit.
    given: line 1 in bottles (unit_numerator 3 / unit_denominator 4 of a LTR, base LTR to 3 decimals)
    when: 24 bottles are delivered, then 0.3333 of a bottle
    then: 24 bottles are recorded as 18 LTR in the base unit beside the line's unit; 0.3333 is refused ("0.3333 bottles is not an exact quantity of LTR to 3 decimals") and nothing is recorded; never rounded
    reference: not built
  - id: SO-49
    kind: integration
    actor: system
    trigger: when inventory receives and inspects a returned line (inventory INV-14)
    story: Inventory reports what came back and what passed inspection on the returns order, so that the credit follows the warehouse's decision.
    given: RE-2026-0001 line 1 expects 6 C62 of COLA-075
    when: "inventory records the receipt (record_delivery on the returns order: 6, source inventory, delivery_ref inv:WH1/RET/00001) and then POST /sales-orders/RE-2026-0001/return-inspections with 5 accepted (4 restock, 1 scrap) and 1 rejected, twice"
    then: the returns line reads received 6, accepted 5, rejected 1, recorded once however often it is repeated; accepted + rejected never exceed received (409 within_received); with return_credit_on inspection the credit request for 5 is made (SO-41); the returns order is done when every line is inspected and its credit issued
    owner: sales-order
    reference: not built
  - id: SO-50
    kind: integration
    actor: system
    trigger: when manufacturing's MRP-lite reads demand (MFG-23)
    story: Planning reads the open quantity of every order for a product, a warehouse and a date range in one call, so that production is planned from what customers ordered without reading orders one by one.
    given: "open lines for BAG-ETH-250 from ROASTERY: SO-2026-0100 line 1, 40 C62 requested 2026-11-20 with 10 delivered; SO-2026-0104 line 2, 24 C62 requested 2026-11-22, confirmed for 2026-11-23; a draft order for 50; a cancelled order for 12"
    when: manufacturing calls GET /demand?product_id=BAG-ETH-250&warehouse_id=ROASTERY&from=2026-11-16&to=2026-11-29
    then: "two rows: (2026-11-20, open 30 C62 = 30 base) and (2026-11-23, open 24 C62), each with its order and line, dated by the latest schedule line's confirmed date, else the requested date; open = ordered - delivered - closed short, in the line's unit and in the base unit; only confirmed orders of goods lines delivered from that warehouse are demand (drafts, quotes, cancelled and THIRD_PARTY lines are not); no price, customer name or amount is answered"
    owner: sales-order
    reference: not built
  - id: SO-51
    kind: integration
    actor: system
    trigger: when timesheets approves billable hours on a project planned from this order (timesheets TS-12)
    story: Approved hours are delivered on the order's service line by timesheets, so that time and materials are invoiced by the order at the price it was sold at.
    given: "order quote:Q-2026-0042@v2 line 2: 120 HUR of CONSULT-SR at 95.0000, invoicing policy delivered, 40 HUR delivered"
    when: timesheets calls POST /sales-orders/quote:Q-2026-0042@v2/deliveries {line_no 2, quantity "19.0000", source timesheets, delivery_ref "ts:4410:2026-W47:r1:1"} twice, then a correction {quantity "-2.0000", delivery_ref "ts:4410:2026-W47:r2:1", corrects_ref "ts:4410:2026-W47:r1:1"}
    then: "the line reads 59 HUR delivered once, then 57; the order invoices delivered quantities by its own policy (SO-21); a delivery on a goods line is refused 409 {gate: service_line}; above the ordered quantity 409 {gate: within_tolerance} unless the line allows over-delivery (v11: one gate name, the signed workflow's, for every source; the story and two routes said within_ordered); a correction that would take delivered below what is already invoiced is refused 409 {gate: not_below_invoiced, fix: \"credit the invoice in invoicing\"}; the order never reads ts_ tables"
    owner: sales-order
    reference: not built
  - id: SO-52
    kind: person
    actor: sales_rep
    trigger: when a rep orders goods worth less than the owner's minimum order value, at confirmation, and on an amendment
    story: A shop owner sets a minimum order value per currency, so that orders too small to be worth picking, packing and invoicing are topped up, held or flagged instead of losing money.
    given: "a policy of 100.00 GBP for orders in GBP (set by the owner, so:settings:controls, from a later date: mode surcharge, block or warn; optional price group); a draft in GBP with goods worth 40.00 net"
    when: the rep prices and confirms the order; in block mode, an order admin who is not the order's owner calls POST /sales-orders/{sales_order_id}/override-minimum-order with a reason; the rep later amends the confirmed order
    then: "surcharge: ONE MIN_ORDER header condition of 60.00 (minimum - net goods, before header conditions) tops the order up to 100.00, spread over the lines and taxed like the goods, recalculated on every re-price: an amendment that lifts the order to or over the minimum removes it, one that lowers it below adds it; exactly at the minimum no surcharge. block: confirmation is refused 409 {gate: minimum_order, reason, fix} until a holder of so:order:approve who is not the owner overrides it with a reason (recorded on the order; the owner's own override is refused); an amendment below the minimum applies only by another person's approval. warn: the same gate, met, with the warning. Returns, credit and debit requests, free-of-charge orders and consignment fill and pick-up never trigger it; no policy, or a policy in another currency, is no effect. Policies are dated, append-only rows (POST /minimum-order-policies, GET /minimum-order-policies, so:settings:controls to set, so:order:read to list)"
    owner: sales-order
    reference: not built
  - id: SO-53
    kind: person
    actor: sales_rep
    trigger: when a rep enters a line for a product that has a substitution record
    story: A distributor replaces a discontinued or short product with its successor at line entry, so that customers get what ships instead of an order line nobody can fill.
    given: a record (so:settings:write, from 1 Dec) replacing COLA-075 with COLA-150 for reason discontinued, mode automatic or propose, optional price group, optional valid_to, priority
    when: a rep enters COLA-075 on a draft (by hand, add_order_line, or an accepted AI suggestion); in propose mode the rep calls accept_substitute with COLA-150 or keep_original
    then: "automatic: the line is COLA-150 at COLA-150's own price (find_price and the pricing procedure, never the original's), keeping COLA-075 as the product entered (entered_product_id) and discontinued as the reason (substitution_reason); both survive an amendment. propose: the line stays COLA-075 and offers COLA-150; the rep accepts it (re-priced) or keeps the original, and an open offer never blocks confirmation. A group's own record wins over the general one, then the lowest priority; A to B to C resolves to C and a cycle stops before it repeats. Outside its dates no effect; out_of_stock applies only while inventory's GET /atp says the original is short (no inventory, warehouse or answer = not short). The substitute is ordered in the unit the customer entered; one not counted in that unit refuses the line 422 naming it. Returns, credit and debit requests, consignment movements, quote-priced and Odoo-imported lines are never substituted. Records: POST /substitutions (so:settings:write, dated, append-only), GET /substitutions (so:order:read), POST /sales-orders/{sales_order_id}/lines/{line_no}/accept-substitute (so:order:write)"
    owner: sales-order
    reference: not built
processes:
  - key: sales_order
    pcf_id: 10185
    pcf_name: Manage sales orders
    reference_names:
      - Quote to Order
      - Order to Cash
    brick: sales-order
  - key: return_order
    pcf_id: null
    pcf_name: Manage customer returns (authorise, receive, inspect, credit)
    reference_names:
      - Returns
      - RMA
      - Advanced returns management
    brick: sales-order
  - key: rebate_agreement
    pcf_id: null
    pcf_name: Manage customer rebates (agree, accrue, settle)
    reference_names:
      - Rebates
      - Settlement management
    brick: sales-order
workflows:
  - entity: sales_order
    states:
      - draft
      - confirmed
      - done
      - cancelled
    terminal:
      - done
      - cancelled
    transitions:
      - key: order_from_quote
        name: Create the order from the accepted quote
        from: none
        to: draft
        by: system
        gate: "a quote version was accepted; readiness: priced_by_product (every quote line priced by product's find_price, v5)"
        effect: type STANDARD; partners defaulted (v5); lines copied, keyed quote:{quote_id}@v{version}; a second hand-over returns the same order
      - key: draft_by_hand
        name: Raise an order by hand
        from: none
        to: draft
        by: sales_rep
        gate: "ordered_on is today in business_timezone; every unit is one the product sells in; an order type (v5); readiness: partners_valid (sold-to, ship-to, bill-to, payer, v5), reference_required (returns, memo requests, consignment issue: the order line or invoice referenced, v5)"
        effect: each line's item category determined from its type and the product's type (v5), priced by the pricing procedure, the BASE condition from find_price (priced_on today); taxed by the tax module for the ship-to
      - key: ai_order_from_po
        name: AI suggests the order from the customer's PO (suggest)
        from: none
        to: draft
        by: system
        gate: a purchase order arrived and the owner turned the step on
        effect: "an empty draft with a suggestion: lines matched to product and unit, the PO number, differences from the quote; nothing on the order yet"
      - key: accept_order_suggestion
        name: Accept, change or reject the AI suggestion
        from: draft
        to: draft
        by: sales_rep
        effect: accepted lines priced by the pricing procedure; what was accepted, changed or rejected, by whom, logged in so_suggestion
      - key: customer_sends_po
        name: The customer sends their purchase order
        from: draft
        to: draft
        by: customer
        gate: the customer requires a PO
      - key: ai_check_po
        name: AI compares the PO with the order (suggest)
        from: draft
        to: draft
        by: system
        gate: a PO document is attached
        effect: price, quantity and term differences listed for the rep
      - key: substitute_product
        name: Swap a discontinued or short product at line entry (substitution)
        from: draft
        to: draft
        by: system
        gate: "v12 SO-53: a so_substitution record is in force on that date for the entered product (the order's price group's own records before the general ones, then lowest priority; A to B to C resolves to C, a cycle stops before it repeats); reason out_of_stock only where inventory's GET /atp says the original is short (no inventory, warehouse or answer = not short); not returns, credit or debit requests, consignment movements, quote-priced or Odoo-imported lines"
        effect: "automatic mode: the line takes the substitute and keeps the entered product (entered_product_id) and the reason (substitution_reason), priced by the substitute's own conditions, never the original's; propose mode: the line keeps the original and carries the offers; both survive an amendment"
      - key: accept_substitute
        name: Accept the proposed substitute, or keep the original
        from: draft
        to: draft
        by: sales_rep
        gate: the line has a substitute waiting (an offer); the chosen product is one of the offers; not a line billed by milestones
        effect: the line takes the chosen substitute, re-priced by its own conditions, keeping the entered product and the reason; or keep_original closes the offer; an open offer never blocks confirmation
      - key: price_order
        name: Price the lines and the header (pricing procedure)
        from: draft
        to: draft
        by: sales_rep
        gate: "readiness: base_price_found (find_price answered every line), manual_within_limit (a typed condition within its type's limit), freight_computable (every line's weight known where FREIGHT applies)"
        effect: "line_condition rows per line and the header's shares, each naming its record; nets rounded once and summed exactly (v5); v12 SO-52 surcharge mode: where the net goods value (before header conditions) is below the minimum order value in force for the order's currency and price group (a dated so_minimum_order row, set with so:settings:controls), ONE MIN_ORDER header condition = minimum minus net goods is spread over the lines and taxed like the others, recalculated on every re-price (an amendment over the minimum drops it, under it adds it); exactly at the minimum no surcharge; no policy or another currency no effect; returns, credit and debit requests, free-of-charge and consignment fill/pick-up orders are exempt"
      - key: promise_dates
        name: Check availability and promise dates (ATP)
        from: draft
        to: draft
        by: system
        gate: inventory installed and the line is stocked (else the requested date is kept and said so)
        effect: "schedule lines per line from inventory's GET /atp: confirmed quantities and dates (v5); a shortfall never blocks"
      - key: review_order
        name: Review lines
        prices and tax: null
        from: draft
        to: draft
        by: sales_rep
      - key: override_minimum_order
        name: Override the minimum order value (block mode)
        from: draft
        to: draft
        by: order_admin
        approval: true
        requires: reason
        gate: "v12 SO-52: readiness minimum_order is unmet (block mode, net goods below the minimum); approver_not_owner (a holder of so:order:approve who is not the order's owner, compared by email AND sign-in subject)"
        effect: the override and its reason recorded on the order; the minimum_order gate is then met at confirmation
      - key: confirm_sales_order
        name: Confirm the order
        from: draft
        to: confirmed
        by: sales_rep
        gate: "readiness all met: customer_active, lines_priced (every line has priced_from), units_valid, lines_taxed, credit (the PAYER not on hold, or an admin overrode it with a reason; mode warn is met with its reason; skipped for CASH, v5), po_ref (where the customer's policy on that date requires one), no_open_suggestion, delivery_multiple (v4: each line a multiple of its product's delivery rule; mode warn is met with its reason, block is not), incomplete:* (v5: every field the type's incompletion rules require for confirmation), minimum_order (v12 SO-52: block mode, the net goods value reaches the minimum order value in force, or an approver other than the owner overrode it with a reason; warn mode is met with its warning; surcharge mode has no gate; exempt order types and no policy are met), site_allows_sale (v5: product site status at the delivering warehouse), plan_complete (v5: milestones total 100%), reference_required (v5)"
        effect: numbered from the order type's series (v5); prices, conditions and tax frozen; repeating lines handed to invoicing as schedules; with inventory installed, its goods lines reserved with their schedule lines (POST /reservations/sales-orders/{sales_order_id}, revision 1) and each line's stocked flag kept from the answer; third-party lines sent to purchasing as purchase requests (v5); RUSH asks for a delivery today; CASH has its delivery and invoice made at once; CREDIT_REQ, DEBIT_REQ and FREE_OF_CHARGE above the limit take the type's APPROVAL block; RETURNS follow the return_order workflow
      - key: cancel_draft_order
        name: Cancel the draft
        from: draft
        to: cancelled
        by: sales_rep
      - key: send_confirmation
        name: Send the order confirmation
        from: confirmed
        to: confirmed
        by: sales_rep
        effect: the document from the frozen order, with the promised dates per schedule line (v5); the send recorded
      - key: receive_confirmation
        name: The customer receives the confirmation
        from: confirmed
        to: confirmed
        by: customer
      - key: approve_memo_request
        name: Approve a credit or debit memo request, or a free-of-charge order
        from: confirmed
        to: confirmed
        by: sales_controller
        approval: true
        gate: "readiness: approver_not_requester (neither the rep who raised it nor anyone with the same email or sign-in subject), within_invoiced (a credit never above the invoice line's net less earlier credits)"
        effect: the APPROVAL block released; a credit request asks invoicing for a credit note against the referenced invoice, a debit request for a draft; a free-of-charge order may be delivered (v5)
      - key: set_order_block
        name: Set a delivery or billing block
        from: confirmed
        to: confirmed
        by: order_admin
        requires: reason
        gate: a block reason of the right kind (delivery | billing)
        effect: a block row appended; the fulfilment answer or the invoice request stops at it (v5)
      - key: release_order_block
        name: Release a block
        from: confirmed
        to: confirmed
        by: order_admin
        requires: reason
        gate: the block is set; an APPROVAL block only by approve_memo_request
        effect: a release row appended
      - key: reschedule_order
        name: Re-promise open quantities (daily)
        from: confirmed
        to: confirmed
        by: system
        gate: an open schedule line not yet delivered; once per business date
        effect: a new schedule version with the reason; a later date raises a task for the owner; the reservation re-sent with the same revision and the new schedule version (v5)
      - key: raise_deposit
        name: Raise the deposit invoice
        from: confirmed
        to: confirmed
        by: biller
        gate: "readiness: deposit_set (the order's deposit percentage is above zero), within_total (deposits never exceed the order total); not CASH"
        effect: invoicing raises a deposit draft; later invoices deduct it in part or in full (v5)
      - key: record_delivery
        name: Record what was delivered or done
        from: confirmed
        to: confirmed
        by: fulfiller
        gate: delivered_on not after today nor before the confirmation; no line beyond its ordered quantity plus its over-delivery tolerance (v5); a correction never below what is invoiced; the quantity converts exactly to the base unit (v3); with inventory installed, a stocked line only with source inventory (v3); a third-party line only with source purchasing (v5); max_partials (v5); no delivery block (v5)
        effect: delivered quantities per line, with the base quantity beside them, a correction as a new row; a line within its under-delivery tolerance is closed (v5); fulfilment status derived
      - key: inventory_delivers
        name: Inventory delivers a stocked line
        from: confirmed
        to: confirmed
        by: system
        gate: inventory installed; the line is stocked; delivery_ref inv:<delivery number>
        effect: record_delivery with source inventory, called inside inventory's validation; a repeat with the same delivery_ref records once
      - key: supplier_delivers
        name: The supplier ships a third-party line
        from: confirmed
        to: confirmed
        by: system
        gate: the line's item category is THIRD_PARTY; delivery_ref pur:<shipping notice>
        effect: record_delivery with source purchasing, called by purchasing; a repeat records once (v5)
      - key: release_milestone
        name: Release a billing milestone
        from: confirmed
        to: confirmed
        by: fulfiller
        gate: the milestone's event happened (or its date is today or past); not released before
        effect: the milestone's billing block released; its value becomes due (v5)
      - key: request_invoice
        name: Ask invoicing for what is due
        from: confirmed
        to: confirmed
        by: biller
        gate: "readiness: something_due (a line has quantity or milestone value to invoice, per its policy), billing_block (none set, v5), incomplete:* (the fields the type requires for billing, v5), billing_relevant (not a FREE_OF_CHARGE or CONS_FILL order, v5), deduction_within_remaining (no deposit deducted beyond what is left, v5)"
        effect: one draft request with its deposit deductions per deposit, each carrying the deposit's tax category (v5); invoice status derived
      - key: amend_sales_order
        name: Amend the order
        from: confirmed
        to: confirmed
        by: sales_rep
        approval: true
        requires: reason
        gate: "readiness: not_done, not_below_done (no line below what is delivered or invoiced), approver_not_amender (where amendment_needs_approval), minimum_order (v12 SO-52, block mode: an amendment that leaves the order below the minimum applies only by another person's approval; the surcharge is recalculated by the re-price), delivery_multiple (v4, on changed lines), partners_unchanged_after_delivery (v5)"
        effect: revision n+1; only changed lines re-priced by the pricing procedure (priced_on today), the header shares re-spread; changed lines re-promised; a new confirmation can be sent; with inventory installed, the reservation re-sent with revision n+1
      - key: finish_sales_order
        name: Lock the finished order
        from: confirmed
        to: done
        by: system
        gate: every line delivered (or closed within tolerance) and invoiced in full, or not billing-relevant
        effect: edits refused
      - key: cancel_sales_order
        name: Cancel the confirmed order
        from: confirmed
        to: cancelled
        by: order_admin
        requires: reason
        approval: true
        gate: "readiness: nothing_delivered, nothing_invoiced, third_party_cancellable (purchasing agreed, v5)"
        effect: drafts it requested are cancelled in invoicing; an unused deposit is credited (v5); with inventory installed, the reservation released (POST /reservations/sales-orders/{sales_order_id}/release)
    note: "Fulfilment status (not started, partly delivered, delivered) and invoice status (nothing to invoice, to invoice, partly invoiced, invoiced) are DERIVED from the quantities on read; nothing stores them. For the screens and agents, the brick answers each order's readiness for its next transitions as a list of {gate, met, reason, fix}: the gate's key (as named in each transition's gate), met true or false, the reason in words (\"this customer requires a PO number\"), and a fix (the field or the person who can clear it), so no screen or agent re-derives a rule. \"Today\" is the date in business_timezone. v5: the order TYPE decides which transitions apply (a FREE_OF_CHARGE order is never invoiced, a CREDIT_REQ never delivered, a RETURNS order follows the return_order workflow), and the incompletion rules add their incomplete:<field> gates to confirm, delivery (the fulfilment answer) and billing."
    readiness:
      - transition: order_from_quote
        gate: priced_by_product
        reason: a quote line was priced from the quote's own price book, not by product
        fix: re-price the quote from product (PRD-20) before it is sent
      - transition: draft_by_hand
        gate: partners_valid
        reason: a ship-to, bill-to or payer is not one of the sold-to's partners in force today, or is not an active customer
        fix: "Settings: customer partners, or pick another"
      - transition: draft_by_hand
        gate: reference_required
        reason: this order type names the order line or invoice it refers to
        fix: pick the original order line or invoice
      - transition: price_order
        gate: base_price_found
        reason: product has no price for this product, unit, customer and currency today
        fix: ask the pricing manager to add one (Price lists)
      - transition: price_order
        gate: manual_within_limit
        reason: a condition typed by hand is beyond its type's manual limit
        fix: stay within the limit, or ask an order admin to change the condition record
      - transition: price_order
        gate: freight_computable
        reason: a line's unit has no gross weight and freight is charged by weight
        fix: record the unit's weight in Products
      - transition: confirm_sales_order
        gate: site_allows_sale
        reason: the product is blocked for sale at the delivering warehouse
        fix: "deliver from another warehouse, or ask the planner (Products: sites)"
      - transition: confirm_sales_order
        gate: plan_complete
        reason: the milestones of a line do not add up to 100%
        fix: "Order: billing plan"
      - transition: confirm_sales_order
        gate: minimum_order
        reason: the order is worth less than the minimum order value for its currency (block mode), or only carries a warning (warn mode)
        fix: add lines, or ask an order admin who is not the order's owner to override with a reason (override_minimum_order)
      - transition: amend_sales_order
        gate: minimum_order
        reason: the amended order would be worth less than the minimum order value (block mode)
        fix: keep the order at or over the minimum, or have another person approve the amendment
      - transition: override_minimum_order
        gate: approver_not_owner
        reason: "you own this order: a second person overrides the minimum"
        fix: ask another holder of so:order:approve
      - transition: substitute_product
        gate: substitute_in_force
        reason: no substitution record is in force for this product today, or out_of_stock and inventory does not say the original is short
        fix: an order admin keeps substitutions from a later date (set_substitution)
      - transition: accept_substitute
        gate: offer_waiting
        reason: the line has no proposed substitute, or the product is not among the offers
        fix: choose one of the offered products, or keep the original
      - transition: approve_memo_request
        gate: approver_not_requester
        reason: "you raised this request (same email or sign-in subject): a second person approves"
        fix: ask a sales controller
      - transition: approve_memo_request
        gate: within_invoiced
        reason: the credit is above what is left of the invoice line after earlier credits
        fix: reduce it to the amount left
      - transition: record_delivery
        gate: max_partials
        reason: the customer accepts at most this many part deliveries per line
        fix: deliver the rest in one, or change the order's rule before delivery
      - transition: record_delivery
        gate: within_tolerance
        reason: more than ordered plus the over-delivery tolerance
        fix: deliver no more than the tolerance allows
      - transition: request_invoice
        gate: billing_block
        reason: the order has a billing block
        fix: an order admin releases it
      - transition: request_invoice
        gate: deduction_within_remaining
        reason: a deposit has less left than the deduction asked
        fix: deduct what is left
      - transition: cancel_sales_order
        gate: third_party_cancellable
        reason: purchasing refused to cancel the purchase for a third-party line (named)
        fix: ask the buyer to cancel it with the supplier first
  - entity: return_order
    states:
      - draft
      - authorised
      - received
      - closed
      - cancelled
    terminal:
      - closed
      - cancelled
    transitions:
      - key: raise_return
        name: Raise the return
        from: none
        to: draft
        by: sales_rep
        gate: "readiness: reference_required (the original order line, its delivery and invoice), within_delivered (no more than delivered less already returned on that line), return_reason"
        effect: a sales_order of type RETURNS; each line copies the original line's price, unit and tax category, never re-priced
      - key: authorise_return
        name: Authorise the return (RMA)
        from: draft
        to: authorised
        by: sales_rep
        gate: "readiness: incomplete:* (the RETURNS type's rules)"
        effect: "numbered RE-{yyyy}-{seq:4}: the RMA the customer quotes; the confirmation sent; inventory told to expect it (POST /expected-returns)"
      - key: receive_returned_goods
        name: The goods come back
        from: authorised
        to: received
        by: system
        gate: inventory received them against the RMA; a serial is one delivered to this customer
        effect: record_delivery on the return line with source inventory (positive, received)
      - key: record_return_inspection
        name: Inventory reports the inspection
        from: received
        to: received
        by: system
        gate: accepted + rejected never above received
        effect: accepted and rejected quantities per line with the decision (restock, scrap, to supplier) and reason (POST /sales-orders/{sales_order_id}/return-inspections)
      - key: request_return_credit
        name: Ask invoicing for the credit
        from: received
        to: received
        by: system
        gate: "readiness: credit_point_reached (return_credit_on receipt, or the line inspected), within_invoiced (never above the original invoice line's net less earlier credits)"
        effect: one credit note against the original invoice for what is accepted, less a restocking fee where the reason has one, keyed so:{sales_order_id}:{request_no}, its lines carrying the returns order's line
      - key: close_return
        name: Close the return
        from: received
        to: closed
        by: system
        gate: every line inspected, and credited or rejected
        effect: edits refused
      - key: cancel_return
        name: Cancel the return
        from:
          - draft
          - authorised
        to: cancelled
        by: sales_rep
        requires: reason
        gate: nothing received
        effect: inventory's expected return withdrawn
    note: "a return never changes the original order: it is its own order (type RETURNS) whose lines reference the original line, delivery and invoice; returned and credited quantities per original line are derived from the returns orders that name it"
    readiness:
      - transition: raise_return
        gate: within_delivered
        reason: more than was delivered on that line less what was already returned
        fix: return at most the quantity named
      - transition: raise_return
        gate: return_reason
        reason: a return needs its reason
        fix: pick a return reason
      - transition: request_return_credit
        gate: credit_point_reached
        reason: the goods are not yet inspected (credit on inspection)
        fix: wait for inventory's inspection
  - entity: rebate_agreement
    states:
      - draft
      - active
      - ended
      - settled
      - cancelled
    terminal:
      - settled
      - cancelled
    transitions:
      - key: open_rebate_agreement
        name: Open a rebate agreement
        from: none
        to: draft
        by: order_admin
        gate: a customer or price group; a basis (products, categories or all); a validity period
        effect: the agreement and its scale, editable
      - key: activate_rebate_agreement
        name: Activate the agreement
        from: draft
        to: active
        by: order_admin
        gate: "readiness: starts_after_today, scale_valid (tiers ascending, rates from 0 to 100 percent)"
        effect: invoices from its start accrue against it
      - key: accrue_rebate
        name: Accrue on issued invoices (nightly)
        from: active
        to: active
        by: system
        gate: an invoice or credit note in the basis issued on the business date
        effect: accrual rows keyed (agreement, document, line) and the accrual journal posted to the ledger
      - key: request_partial_settlement
        name: Ask for a partial settlement
        from: active
        to: active
        by: order_admin
        requires: reason
        effect: "a settlement draft: the rate reached so far on the basis so far, less settled"
      - key: approve_partial_settlement
        name: Approve the partial settlement
        from: active
        to: active
        by: sales_controller
        approval: true
        gate: "readiness: approver_not_requester (by email and sign-in subject)"
        effect: a credit note in invoicing keyed rebate:{agreement_id}:{settlement_no}; the accrual released by its amount
      - key: end_rebate_agreement
        name: The agreement period ends
        from: active
        to: ended
        by: system
        gate: valid_to is before today
        effect: no further accruals; the final basis fixed once the last day's invoices are accrued
      - key: request_final_settlement
        name: Ask for the final settlement
        from: ended
        to: ended
        by: order_admin
        effect: the tier reached on the whole basis, retroactive, less what partial settlements paid
      - key: approve_final_settlement
        name: Approve the final settlement
        from: ended
        to: settled
        by: sales_controller
        approval: true
        gate: "readiness: approver_not_requester"
        effect: the accrual trued up in the ledger, one credit note in invoicing, the accrual account for the agreement nets to 0.00
      - key: cancel_rebate_agreement
        name: Cancel a draft agreement
        from: draft
        to: cancelled
        by: order_admin
    readiness:
      - transition: activate_rebate_agreement
        gate: starts_after_today
        reason: an agreement starts tomorrow at the earliest (business time zone)
        fix: pick a later start
      - transition: activate_rebate_agreement
        gate: scale_valid
        reason: the tiers are not ascending, or a rate is outside 0 to 100 percent
        fix: correct the scale
      - transition: approve_final_settlement
        gate: approver_not_requester
        reason: you asked for this settlement or set the agreement up (same email or sign-in subject)
        fix: ask a sales controller
entities:
  - id: sales_order
    meaning: what a customer has committed to buy, and on what terms
    natural_key: 'sales_order_id: VARCHAR, derived from its source ("quote:<quote_id>@v<version>", "po:<bp_id>:<customer PO>") or a uuid for an order by hand (shared.yaml keys.sales_order_id). The order NUMBER is stamped at confirmation, never the key'
    key_attributes:
      - order_no
      - order_type_code (v5; fixed once confirmed)
      - bp_id (the sold-to)
      - "ship_to_bp_id, bill_to_bp_id, payer_bp_id (v5: copied from customer_partner at creation)"
      - "ship_to_address (v5: copied from business-partner when it serves addresses, else typed on the order; v8: the address shape {lines, city, postcode, region, country}, shared.yaml conventions.address)"
      - owner
      - currency
      - price_list_id
      - price_group (v5)
      - pricing_procedure_code
      - lifecycle
      - revision
      - customer_po_ref
      - ordered_on
      - requested_delivery_on
      - confirmed_at
      - delivery_terms
      - payment_terms_id
      - deposit_pct (percent)
      - "deposit_deduction_mode (v5: proportional | full_first | manual)"
      - "partial_delivery (v5: allowed | complete_line | complete_order), max_partials, under_tolerance_pct, over_tolerance_pct, combine_allowed"
      - "priority (v5: normal | rush)"
      - "ref_sales_order_id, ref_line_no, ref_invoice_id (v5: returns, memo requests, consignment returns, replacements)"
      - return_reason (v5)
      - "approved_by_email, approved_by_sub, approved_at (v5: memo requests, free of charge)"
      - subtotal
      - tax_total
      - total
      - source_kind
      - source_id
    relationships:
      - -> business_partner
      - 1..n order_line
      - 0..n delivery
      - 0..n invoice_request
      - 0..n send
    master_data: module-owned
    reference_table: so_order
    note: "owner is the rep the order belongs to (the caller, or the quote's owner on hand-over): row visibility scopes on it. v5: the PAYER is whose receivable it is (invoicing's bp_id, the credit check); the sold-to is whose order and prices it is; the ship-to decides the tax place of supply for goods and the freight"
  - id: order_line
    meaning: one product, quantity and price on the order
    natural_key:
      - sales_order_id
      - line_no
    key_attributes:
      - product_id (the SKU: one variant)
      - description
      - "category_code (v8: copied from product's price answer, line.category_code; what the category accesses match)"
      - unit_code (UN/ECE Rec 20)
      - quantity (in unit_code
      - to the unit's quantity_decimals)
      - unit_numerator
      - unit_denominator (the unit's conversion to the base unit
      - copied)
      - list_price
      - unit_price (NUMERIC 19,4, per pricing_quantity of pricing_unit_code)
      - "pricing_unit_code, pricing_numerator, pricing_denominator, pricing_quantity (v4: copied from find_price; default the line's unit and 1)"
      - discount_pct (percent)
      - priced_on
      - priced_from
      - tax_category
      - tax_code
      - net_amount
      - tax_amount
      - invoicing_policy (ordered | delivered)
      - "stocked (v3: inventory's reservation answer took it)"
      - "item_category_code (v5: determined at line time, kept)"
      - "usage (v5: normal | drop_ship)"
      - "warehouse_id (v5: the delivering site)"
      - "gross_weight, weight_unit_code, measure_valid_from (v5: copied from product for freight)"
      - "statistical_value (v5: free-of-charge lines)"
      - "min_remaining_shelf_life_days (v5: from the customer's policy)"
      - billing_kind
      - billing_plan (single | periodic | arrears | milestone (v5) | instalment (v5))
      - "ref_sales_order_id, ref_line_no, ref_invoice_id, ref_invoice_line_no, ref_delivery_ref (v5: what a returns, memo or consignment-return line refers to)"
      - quote_ref (quote_id
      - version
      - line_no)
    master_data: module-owned
    reference_table: so_line
    note: description, unit and its conversion, tax category, invoicing policy and billing are COPIES taken when the line was added (product PRD-21). priced_from is the source find_price named (price list, rule, row), or the quote line for a line from an accepted quote, or odoo:<pricelist> for a migrated line; a line is re-priced only when an amendment changes it
  - id: line_condition
    meaning: one condition on a line (BASE, a discount, a surcharge, a share of a header condition, freight, a rebate accrual rate) as priced (v5)
    natural_key:
      - sales_order_id
      - line_no
      - step
      - revision
    key_attributes:
      - condition_type_code
      - "rate (NUMERIC(19,4): an amount per pricing quantity, or a percent)"
      - amount (NUMERIC(18,2), signed)
      - basis (NUMERIC(18,2))
      - "source (the record found: condition_record key and the access step, or product's priced_from for BASE, or manual with who)"
      - statistical (bool)
      - header_share_of (the header condition it is a share of)
    master_data: module-owned (append per revision; frozen at confirmation)
    reference_table: so_line_condition
    note: line 0 holds the header conditions as typed; each line holds its share, the remainder on the largest (by net, or by weight for freight), so the shares sum exactly
  - id: schedule_line
    meaning: a quantity of a line promised for a date, from inventory's ATP (v5)
    natural_key:
      - sales_order_id
      - line_no
      - schedule_version
      - seq
    key_attributes:
      - requested_on, requested_quantity
      - confirmed_on (the delivery date promised), material_available_on, confirmed_quantity (in the line's unit), confirmed_base
      - reason
      - at
    master_data: "module-owned (append-only: a re-promise is a new schedule_version; the latest version is in force)"
    reference_table: so_schedule_line
  - id: billing_milestone
    meaning: "one stage of a line billed by milestone: a percent or an amount, on a date or an event (v5)"
    natural_key:
      - sales_order_id
      - line_no
      - milestone_no
    key_attributes:
      - percent or amount (NUMERIC(18,2); the last milestone takes the remainder)
      - trigger (on_confirm | on_date | on_event)
      - due_on
      - event_name
      - released_by
      - released_at
      - request_no
    master_data: module-owned
    reference_table: so_billing_milestone
  - id: deposit_deduction
    meaning: how much of one deposit invoice an invoice request deducts (v5; the claim row two concurrent requests race for)
    natural_key:
      - sales_order_id
      - deposit_request_no
      - seq
    key_attributes:
      - request_no
      - deposit_invoice_id
      - amount (NUMERIC(18,2))
      - tax_category (the deposit line's)
      - remaining_after
    master_data: "module-owned (append-only; seq claimed with a plain INSERT: the loser re-reads what is left)"
    reference_table: so_deposit_deduction
  - id: return_inspection
    meaning: what inventory found when a returned line was inspected (v5)
    natural_key:
      - sales_order_id
      - line_no
      - inspection_ref
    key_attributes:
      - received_quantity
      - accepted_quantity
      - rejected_quantity
      - decision (restock | scrap | to_supplier)
      - reason
      - inspected_on
    master_data: module-owned (append-only; written only by inventory's service client)
    reference_table: so_return_inspection
  - id: credit_claim
    meaning: how much of an invoice line a credit or return request takes (v5; stops two requests crediting the last pound twice)
    natural_key:
      - invoice_id
      - invoice_line_no
      - seq
    key_attributes:
      - sales_order_id
      - request_no
      - amount (NUMERIC(18,2))
      - remaining_after
    master_data: module-owned (append-only; plain INSERT on (invoice_id, invoice_line_no, seq))
    reference_table: so_credit_claim
  - id: order_block
    meaning: a delivery or billing block set or released on an order, with why (v5)
    natural_key:
      - sales_order_id
      - seq
    key_attributes:
      - kind (delivery | billing)
      - block_reason_code
      - action (set | release)
      - note
      - by_email
      - by_sub
      - at
    master_data: module-owned (append-only); a block is in force while its last row is set
    reference_table: so_order_block
  - id: delivery
    meaning: a record that some quantity of a line was delivered or done
    natural_key:
      - sales_order_id
      - line_no
      - delivery_ref
    key_attributes:
      - quantity (negative on a correction)
      - "quantity_base (v3: exact, in the product's base unit)"
      - "catch_quantity, catch_unit_code (RESERVED until M7: the actual weight delivered, inventory deferred.catch_weight; NULL)"
      - kind (delivery | correction | opening)
      - corrects_ref
      - delivered_on
      - recorded_by
      - source (manual | inventory | migration)
    master_data: module-owned
    reference_table: so_delivery
    note: "append-only: a mistake is a correction row against the original, never an edit; delivered_on is never after today"
  - id: invoice_request
    meaning: what the order asked invoicing to bill, and when
    natural_key:
      - sales_order_id
      - request_no
    key_attributes:
      - kind (regular | deposit | final)
      - lines_json
      - invoice_id
      - requested_at
      - requested_by
    master_data: module-owned
    reference_table: so_invoice_request
    note: invoiced quantities are read back from invoicing (its lines carry sales_order_id and line_no); this table is the request log, not the truth of what was billed
  - id: revision
    meaning: a change to a confirmed order, with why and who approved it
    natural_key:
      - sales_order_id
      - revision
    key_attributes:
      - reason
      - changed_lines_json
      - approved_by
      - approved_at
    master_data: module-owned
    reference_table: so_revision
  - id: send
    meaning: a record that the confirmation went out
    natural_key:
      - sales_order_id
      - sent_at
    key_attributes:
      - channel
      - address
      - revision
    master_data: module-owned
    reference_table: so_send
  - id: number_series
    meaning: the counter behind order numbers (state, not a setting); v5 one series per order type
    natural_key: series_id
    key_attributes:
      - high_water_mark
    note: "v5: claimed by a plain INSERT of (series_id, number) in so_number_claim within the confirmation's write, so two confirmations never share a number, a refused one leaves no gap, and a number is never reused; a migrated series continues after Odoo's highest"
    master_data: module-owned (state)
    reference_table: so_number_series
  - id: number_claim
    meaning: one order number claimed from a type's series (v5)
    natural_key:
      - series_id
      - number
    key_attributes:
      - sales_order_id
      - claimed_at
    master_data: module-owned (a claim row per number, plain INSERT in the confirmation's own write)
    reference_table: so_number_claim
  - id: suggestion
    meaning: what an AI step suggested on an order, and what a person did with it (the audit of an AI step)
    natural_key:
      - sales_order_id
      - step
      - suggestion_no
    key_attributes:
      - model
      - inputs_ref (the PO document's object key)
      - output_json
      - decision (accepted | changed | rejected | open)
      - decided_by
      - decided_at
    master_data: module-owned
    reference_table: so_suggestion
  - id: minimum_order_policy
    meaning: the smallest order value worth taking in a currency, and what happens below it (v12, SO-52)
    natural_key:
      - currency
      - customer_group
      - valid_from
    key_attributes:
      - customer_group (the order's price group; empty = every group)
      - minimum (NUMERIC(18,2))
      - mode (surcharge | block | warn)
      - set_by
    master_data: module-owned (configuration)
    reference_table: so_minimum_order
    note: "dated and append-only: valid_from is after today; the row in force is the latest valid_from on or before the date, a group's own row before the general one; a correction is a new row from a later date. The order carries min_order_override_by and min_order_override_reason (so_order) once an approver overrode a block"
  - id: substitution_record
    meaning: one product that replaces another, from a date, and how (v12, SO-53)
    natural_key:
      - original_product_id
      - substitute_product_id
      - customer_group
      - valid_from
    key_attributes:
      - customer_group (the order's price group; empty = every group)
      - valid_to
      - priority (lowest wins)
      - reason (discontinued | out_of_stock | superseded | promotion)
      - mode (automatic | propose)
      - set_by
    master_data: module-owned (configuration)
    reference_table: so_substitution
    note: dated and append-only like the other policies. A substituted line (so_line) carries entered_product_id, substitution_reason and substitute_proposals (the open offers in propose mode)
  - id: customer_order_policy
    meaning: how one customer orders (PO required, default deposit), from a date
    natural_key:
      - bp_id
      - valid_from
    key_attributes:
      - po_required
      - deposit_pct (percent)
      - deposit_deduction_mode (v5)
      - delivery_terms
      - partial_delivery, max_partials, under_tolerance_pct, over_tolerance_pct, combine_allowed (v5)
      - "price_group (v5: the key condition records and rebates may name)"
      - min_remaining_shelf_life_days (v5)
      - set_by
    master_data: module-owned (configuration)
    reference_table: so_customer_policy
    note: "dated and append-only: valid_from is after today; the row in force on a date is the latest valid_from on or before it; a correction is a new row from a later date"
  - id: order_type
    meaning: what kind of order this is and how it behaves (v5, SAP sales document type)
    natural_key: order_type_code (STANDARD, RUSH, CASH, RETURNS, CREDIT_REQ, DEBIT_REQ, FREE_OF_CHARGE, CONS_FILL, CONS_ISSUE, CONS_PICKUP, CONS_RETURN seeded)
    key_attributes:
      - name
      - series_id (its number series)
      - direction (out | in | none)
      - billing (invoice | credit | debit | none)
      - delivery_relevant
      - reference (none | order_line | invoice | consignment)
      - default_block (none | APPROVAL)
      - pricing_procedure_code
      - workflow (sales_order | return_order)
      - priority
      - credit_check (bool)
      - special_stock (none | to_consignment | from_consignment)
      - approval_limit (free of charge)
      - valid_from
      - status
    master_data: module-owned (configuration, dated; seeded)
    reference_table: so_order_type
  - id: item_category
    meaning: "how one line behaves (v5, SAP item category): delivered from stock, a service, third party, free, returned"
    natural_key: item_category_code (STD_STOCK, STD_SERVICE, THIRD_PARTY, FREE, RETURN, CONS_FILL, CONS_ISSUE seeded)
    key_attributes:
      - fulfilment (stock | service | supplier | none)
      - billing_relevant
      - pricing (full | statistical)
      - schedule_lines (bool)
      - returns (bool)
    master_data: module-owned (configuration, seeded)
    reference_table: so_item_category
  - id: item_category_rule
    meaning: which item category a line gets from its order type, its product's type and its usage, and which others the rep may choose (v5, SAP VOV4)
    natural_key:
      - order_type_code
      - product_type_code
      - usage
      - valid_from
    key_attributes:
      - item_category_code
      - allowed_alternatives
    master_data: module-owned (configuration, dated)
    reference_table: so_item_category_rule
  - id: condition_type
    meaning: "a kind of price element: BASE, DISC_PCT, DISC_ABS, SURCH_PCT, SURCH_ABS, HDR_DISC, FREIGHT, REBATE (v5)"
    natural_key: condition_type_code
    key_attributes:
      - calculation (percent | per_unit | fixed | per_weight)
      - level (item | header)
      - header_spread (net | weight)
      - sign (minus | plus)
      - access_sequence_code
      - manual_allowed
      - manual_limit_pct (or amount)
      - statistical (bool)
      - scale_basis (quantity | value | weight)
      - account_purpose (revenue | discount | freight | rebate)
    master_data: module-owned (configuration)
    reference_table: so_condition_type
    note: "BASE has no records here: it is always product's find_price (one price book). Tax is not a condition: the tax module computes it after the net"
  - id: access_sequence
    meaning: the order in which condition records are looked for, most specific first; the first hit wins (v5)
    natural_key:
      - access_sequence_code
      - step
    key_attributes:
      - "key_fields (customer + product | customer + category | price_group + product | price_group + category | category | customer | ship_to_country | all); v8: category is the line's category_code, copied from product's price answer (line.category_code) when the line is priced and frozen with it"
      - exclusive (bool: stop at the first hit
      - the default)
    master_data: module-owned (configuration)
    reference_table: so_access_sequence
  - id: condition_record
    meaning: "an agreed discount, surcharge or freight rate for a key (customer 7311 + COLA-075: 5%), with validity and an optional scale (v5)"
    natural_key:
      - condition_type_code
      - key_fields
      - key_values
      - valid_from
    key_attributes:
      - valid_to
      - rate (NUMERIC(19,4) or percent)
      - unit_code
      - pricing_quantity
      - currency
      - "scale: [{from (quantity, value or weight), rate}]"
      - minimum_amount (FREIGHT)
      - set_by
    master_data: module-owned (append-only; valid_from after today; a correction is a new row from a later date)
    reference_table: so_condition_record
  - id: pricing_procedure
    meaning: the steps a line's price is built from, in order, with their subtotals (v5)
    natural_key:
      - pricing_procedure_code
      - step
    key_attributes:
      - condition_type_code
      - from_step, to_step (what a percent applies to)
      - subtotal_name
      - required (bool)
      - statistical (bool)
    master_data: module-owned (configuration)
    reference_table: so_pricing_procedure
    note: "seeded STANDARD: 10 BASE, 20 DISC_PCT, 30 DISC_ABS, 40 SURCH_PCT, 50 SURCH_ABS, 100 NET (subtotal), 110 HDR_DISC, 120 FREIGHT, 200 REBATE (statistical, the accrual rate shown, never billed)"
  - id: customer_partner
    meaning: "who ships, bills and pays for a sold-to: its ship-tos, bill-to and payer (v5, SAP partner functions)"
    natural_key:
      - sold_to_bp_id
      - function (ship_to | bill_to | payer)
      - partner_bp_id
      - valid_from
    key_attributes:
      - is_default
      - transit_days (ship-to: days from each warehouse
      - for the promised date)
      - status (active | ended)
      - set_by
    master_data: module-owned (append-only; valid_from after today); every partner is a business partner (business-partner's bp_id)
    reference_table: so_customer_partner
  - id: incompletion_rule
    meaning: a field an order of a type must have before it is confirmed, delivered or billed (v5, SAP incompletion procedure)
    natural_key:
      - order_type_code
      - field
      - valid_from
    key_attributes:
      - blocks (confirm | delivery | billing)
      - condition (always | export_ship_to | customer_policy_requires)
      - reason_text
    master_data: module-owned (configuration, dated)
    reference_table: so_incompletion_rule
  - id: block_reason
    meaning: why an order is held for delivery or billing (v5)
    natural_key: block_reason_code
    key_attributes:
      - kind (delivery | billing)
      - name
    master_data: module-owned (configuration; APPROVAL seeded)
    reference_table: so_block_reason
  - id: return_reason
    meaning: why goods come back and what that means for the credit (v5)
    natural_key: return_reason_code
    key_attributes:
      - name
      - inspect (bool)
      - restocking_fee_pct (percent)
      - credit_on (receipt | inspection)
    master_data: module-owned (configuration)
    reference_table: so_return_reason
  - id: rebate_agreement
    meaning: what a customer earns back on a period's purchases (v5)
    natural_key: rebate_agreement_id (RB-{yyyy}-{bp_id}, or the customer's own code)
    key_attributes:
      - bp_id or price_group
      - basis (products | categories | all), basis_values
      - valid_from
      - valid_to
      - "scale: [{from_value, rate_pct}]"
      - retroactive (bool)
      - accrual_rate_pct
      - currency
      - lifecycle
      - set_by_email
      - set_by_sub
    master_data: module-owned
    reference_table: so_rebate_agreement
  - id: rebate_accrual
    meaning: the accrual one invoice or credit note line adds to an agreement (v5)
    natural_key:
      - rebate_agreement_id
      - document_id
      - line_no
    key_attributes:
      - issue_date
      - basis_amount (NUMERIC(18,2))
      - accrual_amount (NUMERIC(18,2), signed)
      - journal_id
      - posting_status (posted | pending | reported)
    master_data: module-owned (append-only)
    reference_table: so_rebate_accrual
  - id: rebate_settlement
    meaning: a partial or final payout of an agreement, with who asked and who approved (v5)
    natural_key:
      - rebate_agreement_id
      - settlement_no
    key_attributes:
      - kind (partial | final)
      - basis_amount, rate_pct, earned_amount, settled_before, amount (NUMERIC(18,2))
      - true_up_amount
      - requested_by_email
      - requested_by_sub
      - approved_by_email
      - approved_by_sub
      - credit_id (invoicing's)
      - status
    master_data: module-owned
    reference_table: so_rebate_settlement
  - id: posting
    meaning: what was asked of the ledger for a rebate accrual or true-up, and its answer (v5)
    natural_key:
      - document_id
      - event
    key_attributes:
      - journal_id (BIGINT derived from document_id and event)
      - status (posted | pending | reported)
      - reason
      - attempts
    master_data: module-owned
    reference_table: so_posting
  - id: task
    meaning: something a person should do because the system changed a promise (tell the customer a new date) (v5)
    natural_key:
      - sales_order_id
      - kind
      - raised_on
    key_attributes:
      - owner
      - text
      - closed_by
      - closed_at
    master_data: module-owned
    reference_table: so_task
  - id: settings
    meaning: how this business takes orders
    natural_key:
      - key
      - valid_from
    key_attributes:
      - value
      - set_by
    note: "dated like the customer policy: a change starts after today; the controls (so:settings:controls) are rows here too"
    master_data: module-owned (configuration)
    reference_table: so_settings
master_data:
  owns:
    - so_order
    - so_line
    - so_delivery
    - so_invoice_request
    - so_revision
    - so_send
    - so_suggestion
    - so_number_series
    - so_customer_policy
    - so_settings
    - so_minimum_order
    - so_substitution
    - so_line_condition
    - so_schedule_line
    - so_billing_milestone
    - so_deposit_deduction
    - so_return_inspection
    - so_credit_claim
    - so_order_block
    - so_order_type
    - so_item_category
    - so_item_category_rule
    - so_condition_type
    - so_access_sequence
    - so_condition_record
    - so_pricing_procedure
    - so_customer_partner
    - so_incompletion_rule
    - so_block_reason
    - so_return_reason
    - so_rebate_agreement
    - so_rebate_accrual
    - so_rebate_settlement
    - so_posting
    - so_task
    - so_number_claim
  references:
    - entity: business_partner
      owner: business-partner
      how: so_order.bp_id = business_partner.bp_id
      if_absent: "orders keep their own customer names: the duplication the party master exists to prevent"
    - entity: product
      owner: product
      how: so_line.product_id and unit_code, copied fields at line time; the price from find_price
      if_absent: lines are free text, priced and unit-ed by hand, and invoicing policy is chosen per line
    - entity: tax_code
      owner: tax
      how: so_line.tax_code, from the tax module's compute()
      if_absent: tax is entered per line
    - entity: business_partner (partner functions, v5)
      owner: business-partner
      how: so_customer_partner.partner_bp_id and so_order.ship_to_bp_id / bill_to_bp_id / payer_bp_id = business_partner.bp_id, checked through GET /partners/{bp_id} (status, roles)
      if_absent: every partner function is the sold-to
    - entity: stock and availability
      owner: inventory
      how: reservations, ATP, deliveries, expected returns and consignment stock through inventory's routes; never inv_ tables
      if_absent: no promised dates (the requested date is kept), deliveries and returns recorded by hand, no consignment
    - entity: purchase request
      owner: purchasing
      how: a third-party line's purchase request keyed so:<sales_order_id>:<line_no>@r<revision>
      if_absent: no third-party lines (the item category is refused)
    - entity: account
      owner: gl
      how: rebate accrual journals name the ledger's account_id per purpose (rebate_expense, accrued_rebates) from so_settings' account map
      if_absent: accruals are reported monthly for the accountant, not posted
  warning: An order system that also writes invoices is how a part-delivered order bills in full. The order asks; invoicing decides and owns the invoice.
jobs:
  - story: SO-12
    trigger: on read
    runs: fulfilment and invoice status
    where_options:
      - derived on read
    idempotent: nothing stored
  - story: SO-13
    trigger: when the last invoice issues (invoicing's event) or the last delivery is recorded
    runs: lock the order
    where_options:
      - in the same request
    idempotent: done is set once; a second trigger finds it done
  - story: SO-33
    trigger: nightly, for the previous business day (the composition's clock worker, --reserved 1 --max-replicas 1, or an external scheduler)
    runs: rebate accruals from invoicing's GET /billed-lines and their journals
    where_options:
      - the composition's clock worker
      - external scheduler
    idempotent: "accruals keyed (agreement, document_id, line_no); journal_id derived from (document, event): a re-run posts nothing more"
  - story: SO-36
    trigger: at the start of each business day, and when an order is cancelled
    runs: re-promise of open schedule lines through inventory's GET /atp
    where_options:
      - the composition's clock worker
      - external scheduler
    idempotent: "one schedule version per (order, line, business date): a second run the same day writes nothing"
  - story: SO-14
    trigger: when a PO arrives in the order inbox
    runs: the PO extraction (DataK3 invoice-intake recipe shape over the order inbox bucket prefix), as a suggestion only
    where_options:
      - in the same request as the upload
      - external scheduler polling the inbox
    idempotent: keyed sales_order_id = "po:<bp_id>:<customer PO>"; re-running replaces an open suggestion, never an accepted one
seams:
  - story: SO-02
    with: product
    owner: product
    direction: outbound
    route: GET /products/{product_id}/price?quantity=&unit_code=&bp_id=&currency=&priced_on=
    permission: product:price_list:read
    response: "{product_id, currency, unit_price (string, NUMERIC 19,4, per pricing_quantity of pricing_unit_code), pricing_quantity (int), pricing_unit_code, pricing_numerator, pricing_denominator, amount (string, NUMERIC 18,2: the exact line amount for the asked quantity, rounded once), priced_from {price_list_id, rule_seq, row}, line {description, unit_code, unit_numerator, unit_denominator, tax_category, category_code (v6: the product template's category, product_template.category_code; what sales-order's category conditions match), invoicing_policy, billing_kind, billing_plan, product_type_code, sellable (v3), measures {gross_weight, net_weight, weight_unit_code, volume, volume_unit_code, valid_from} (v3: the unit's row in force on priced_on, for freight)}}"
    rule: every line added or amended calls product's find_price and stores the price, its pricing quantity and pricing unit (v4) and the source it names as priced_from; net_amount = round_half_up(quantity_priced x unit_price / pricing_quantity x (1 - discount_pct / 100), minor unit); the order never reads prod_ tables
    request: "query: quantity (string, in unit_code), unit_code (default the sales unit), bp_id, currency, priced_on (default today)"
    status: "aligned 2026-10-22 with product PRD-31; v8: line.category_code (product v6) copied onto the line for the category accesses"
  - story: SO-28
    with: product
    owner: product
    direction: outbound
    route: GET /products/{product_id}/rounding?role=&quantity=&unit_code=&on=
    permission: product:product:read
    request: "query: role delivery, quantity (string, the line's), unit_code (the line's), on (the order date)"
    response: "{product_id, role, rule | null, quantity_in_rule_unit, met, next_down, next_up, reason}"
    rule: "asked for each line at confirm and for each changed line at amend; met false becomes the delivery_multiple gate, met true with its reason in warn mode and met false in block mode; nothing stored but the warning shown on the order; this call: GET /products/{product_id}/rounding?role=delivery&quantity=&unit_code=&on=; this call: query: role delivery, the line's quantity and unit_code, on = the order or amendment date"
    status: aligned 2026-10-22 with product PRD-32
  - story: SO-02
    with: product
    owner: product
    direction: outbound
    route: POST /prices/batch
    permission: product:price_list:read
    request: "body: {bp_id (the order's), currency (the order's), priced_on (the order or amendment date), lines: [{line_no, product_id, quantity, unit_code, price: true | false, rounding_role: delivery (at confirm and amend)}]}"
    request_schema:
      - field: bp_id
        type: bp_id
        required: false
      - field: currency
        type: currency
        required: true
      - field: priced_on
        type: date
        required: false
      - field: lines
        type: array
        required: true
        items:
          - field: line_no
            type: integer
            required: true
          - field: product_id
            type: product_id
            required: true
          - field: quantity
            type: decimal
            required: true
          - field: unit_code
            type: unit_code
            required: false
          - field: price
            type: boolean
            required: false
          - field: rounding_role
            type: string
            required: false
            values:
              - delivery
          - field: convert
            type: boolean
            required: false
    response: "{bp_id, currency, priced_on, lines: [{line_no, product_id, price (the GET /products/{product_id}/price answer or {status, reason}), rounding (the GET .../rounding answer, {status, reason} or null), conversion}]}"
    rule: "v10: every line priced in one request (draft, add and amend, re-price) and the delivery rounding of every line asked at confirm and amend go in ONE call per order; each line's answer is used exactly as the one-line route's (SO-02 copies, SO-28 delivery_multiple gate), and a line's {status, reason} is refused exactly as that route's refusal was (404 / 409 / 422 -> 422 naming the product). The one-line routes stay the fallback for a product module that predates PRD-41 (a 404 or 405 on the batch route)"
    status: "added 2026-10-25 (v10): the caller side of product v7 PRD-41"
  - story: SO-20
    with: ar
    owner: ar
    rule: the order calls invoicing's plan_billing (POST /schedules, source_kind sales_order, keyed {sales_order_id}|{line_no}; SO-46 has the full request); invoicing owns ar_schedule
  - story: SO-21
    with: ar
    owner: ar
    rule: the order calls invoicing's raise_draft (POST /invoices/raise, source_kind sales_order, source_id so:{sales_order_id}:{request_no}, bp_id = the payer, lines; SO-47 adds deductions); invoiced quantities and nets are read back through GET /sources/sales_order/{sales_order_id}/billed (issued less approved credit notes carrying that order's lines); a draft it requested is cancelled through POST /invoices/{invoice_id}/cancel
  - story: SO-22
    with: payments
    owner: payments
    rule: the order reads GET /customers/{bp_id}/credit-ok from payments for the payer (SO-40); it never computes a balance itself
  - story: SO-23
    with: inventory
    owner: sales-order
    direction: inbound
    route: POST /sales-orders/{sales_order_id}/deliveries
    permission: so:order:deliver
    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_tolerance | exact_base, reason, fix}"
    rule: inventory calls record_delivery inside its validation and never writes so_ tables; with inventory installed a stocked line accepts only source inventory, and a hand delivery on it is refused; a service line is delivered by hand as in v2
    status: aligned 2026-10-22 with inventory INV-23
  - story: SO-25
    with: inventory
    owner: inventory
    direction: outbound
    route: POST /reservations/sales-orders/{sales_order_id}
    permission: inv:reservation:intake
    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)"
    rule: "called on confirm (revision 1) and on every amendment (revision n); keyed (sales_order_id, revision), so a retry changes nothing; a short line is shown, never a confirmation blocker; this call: {revision: int, warehouse_id (optional), lines: [{line_no, product_id, unit_code, quantity (string), unit_numerator, unit_denominator}]}"
    status: aligned 2026-10-22 with inventory INV-22
  - story: SO-25
    with: inventory
    owner: inventory
    direction: outbound
    route: POST /reservations/sales-orders/{sales_order_id}/release
    permission: inv:reservation:intake
    request: "{reason}"
    response: "{sales_order_id, released_base_by_line: [{line_no, quantity_base}]}"
    rule: called on cancel; releases what is reserved and not delivered; a repeat releases nothing more
    status: aligned 2026-10-22 with inventory INV-22
  - story: SO-01
    with: crm
    owner: sales-order
    direction: inbound
    route: POST /sales-orders/from-quote
    permission: so:order:intake
    request: "{quote_id, quote_version, bp_id, currency, owner, customer_po_ref, lines: [{line_no, product_id, description, quantity (string), unit_code, list_price, unit_price, discount_pct, pricing_quantity, pricing_unit_code, priced_from (product's: {price_list_id, rule_seq, row}), priced_on}]}"
    response: "the draft order view; 409 {gate: priced_by_product, reason, fix} naming the first line not priced by product"
    status: built (erp-brick-sales-order 0.x, without the v5 priced_by_product gate and pricing_quantity); the adapter is not built
    rule: the composition's adapter calls brick-quote's POST /quotes/{quote_id}/versions/{version}/decision (quote:quote:decide) with outcome ACCEPTED (it is the one caller for acceptances), then GET /quotes/{quote_id}?version= for the accepted version, then this route; keyed quote:{quote_id}@v{version}, so a retry of any step returns the same order; quote prices each line by product's GET /products/{product_id}/price and stores its answer (product PRD-20), which is what priced_from carries here
  - story: SO-01
    with: crm
    owner: crm
    direction: outbound
    route: GET /quotes/{quote_id}?version=
    permission: quote:quote:read_all
    request: path quote_id (the adapter reads the accepted version from the answer)
    response: the quote with its versions and lines (status ACCEPTED on exactly one version)
    status: built (brick-quote 0.2.0); the line's priced_from from product is brick-quote's change (crm, PRD-20)
    rule: read by the adapter, never by this brick's code; this brick never reads quote_ tables
  - story: SO-35
    with: inventory
    owner: inventory
    direction: outbound
    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}"
    rule: "the line's schedule lines are the confirmations moved by the pick-and-pack days (inventory's) and the ship-to's transit_days (customer_partner); nothing here is a reservation: confirm reserves (SO-25); this call: query: warehouse_id (the line's delivering site), quantity (string, in unit_code), requested_on (the material availability date wanted), min_shelf_life_days, exclude_sales_order_id (the order's own reservation, on a re-promise)"
    status: aligned 2026-10-22 with inventory INV-49
  - story: SO-36
    with: inventory
    owner: inventory
    direction: outbound
    route: POST /reservations/sales-orders/{sales_order_id}
    permission: inv:reservation:intake
    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)"
    rule: "the v3 route with the schedule added; keyed (sales_order_id, revision, schedule_version), so a re-promise re-sends the same revision with a higher schedule version and a retry changes nothing; this call: {revision, schedule_version (v5), priority (normal | rush), lines: [{line_no, product_id, unit_code, quantity, unit_numerator, unit_denominator, warehouse_id, schedule: [{confirmed_on, quantity_base}]}]}"
    status: aligned 2026-10-22 with inventory INV-22
  - story: SO-37
    with: inventory
    owner: sales-order
    direction: inbound
    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}"
    rule: "inventory reads it when it raises and when it validates a delivery: a delivery block or an incomplete:* delivery gate holds it off the pick list; complete_order waits for every line; the purpose decides the account inventory costs the goods to"
    status: aligned 2026-10-22 with inventory INV-23
  - story: SO-40
    with: business-partner
    owner: business-partner
    direction: outbound
    route: GET /partners/{bp_id}
    permission: bp:partner:read
    request: path bp_id (each of sold-to, ship-to, bill-to, payer)
    response: "{bp_id, bp_key, legal_name, country (ISO 3166 alpha-2: a ship-to partner's country, what delivery_terms and the place of supply read, v7), tax_id, status, roles [customer, ship_to, ...], can_transact, kind, version}; no postal address: business-partner keeps none"
    status: "v7: business-partner v2 already answers country on GET /partners/{bp_id}; the order copies it as ship_to_country; a full postal address stays out of business-partner (no addresses, its non-goals)"
    rule: a partner function is accepted only for an active partner with the role it plays (customer for sold-to and payer, ship_to or customer for a ship-to); the address is copied onto the order when it is raised
  - story: SO-40
    with: payments
    owner: payments
    direction: outbound
    route: GET /customers/{bp_id}/credit-ok
    permission: pay:credit:read
    request: path bp_id = the order's PAYER
    response: "{gate: credit_ok, met, reason, fix, hold_mode (warn | block), bp_id}"
    status: built; aligned 2026-10-22 with payments PAY-40
    rule: "read at confirm for the payer, never the sold-to; skipped for CASH orders; this call: path bp_id = the order's PAYER (v5)"
  - story: SO-40
    with: tax
    owner: tax
    direction: outbound
    route: POST /documents/compute
    permission: tax:document_tax:compute
    request: "{document_ref, direction (sale | purchase; default sale, so every v2 caller is unchanged), tax_point (YYYY-MM-DD), bp_id, currency, treatment_code (optional), prices_include_tax (optional), fx_rate (optional), ship_to_country (optional, v4: ISO 3166; goods lines are taxed where the ship-to receives them, services by the customer), self_billed (optional, v4: a purchase-direction invoice we issue on the supplier's behalf under a self-billing agreement), lines: [{line_no, description, category_code (the product's tax_category), supply (goods | services), amount, quantity, unit_price, pinned_from (optional; an earlier frozen document_ref), tax_code (with pinned_from)}]}"
    response: "{document_ref, status, lines: [{line_no, tax_code, rate_pct, net, vat, gross, vat_reclaimable, vat_non_reclaimable (purchase)}], summary: [{tax_code, rate_pct, net, vat, vat_due, gross}], totals: {net, vat, vat_due, gross, method, vat_reclaimable, vat_non_reclaimable}, gates: [{gate, met, reason, fix}], version}; a pinned line answers the earlier document's frozen code and rate, or the gates pinned_code / pinned_within_original"
    status: built; aligned 2026-10-22 with tax TAX-20
    rule: sales-order sends document_ref so:{sales_order_id}@r{revision}, bp_id the sold-to and ship_to_country; the order never derives a rate
  - story: SO-41
    with: inventory
    owner: inventory
    direction: outbound
    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}]}"
    response: "{rma_ref, expected: [{line_no, quantity_base}]}"
    rule: "called at authorise_return; idempotent on rma_ref; cancel_return calls POST /expected-returns/{rma_ref}/cancel; inventory receives only against an open RMA (its INV-14); this call: {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 (inv:...), serials (if tracked), inspect (bool)}]}"
    status: aligned 2026-10-22 with inventory INV-14
  - story: SO-49
    with: inventory
    owner: sales-order
    direction: inbound
    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
    rule: idempotent on (sales_order_id, line_no, inspection_ref); accepted + rejected never above received (409 within_received); the receipt itself arrives first through POST /sales-orders/{sales_order_id}/deliveries with source inventory
    status: aligned 2026-10-22 with inventory INV-14
  - story: SO-41
    with: ar
    owner: ar
    direction: outbound
    route: POST /credit-notes
    permission: ar:credit_note:write
    request: "{invoice_id (optional; the original invoice), full (optional), bp_id, currency, reason, source_id (v4; so:{sales_order_id}:{request_no} | rebate:{rebate_agreement_id}:{settlement_no}; idempotent on it), account_purpose (optional, v4: rebate = posted against accrued rebates, not revenue), lines: [{invoice_line_no (against an invoice) | description, quantity, unit_price, discount_pct, net_amount, tax_category, sales_order_id, so_line_no}]}"
    response: "201 {credit_id, status: draft, lines, tax}; 200 the same for the same source_id"
    status: built (goodwill credits); aligned 2026-10-22 with ar AR-04
    rule: idempotent on source_id; approval of the credit note stays invoicing's own second-person step
  - story: SO-42
    with: ar
    owner: ar
    direction: outbound
    route: POST /invoices/raise
    permission: ar:invoice:raise
    request: "{source_kind: sales_order, source_id: so:{sales_order_id}:{request_no}, bp_id (the payer), currency, kind (regular | deposit | final), customer_po_ref, issue_hint (optional, v4: cash = issued at once when the owner control auto_issue_sources contains sales_order:cash, else a draft), lines: [{description, quantity, unit_code (optional: copied from the product when left out), unit_price, discount_pct, tax_category (optional: copied from the product when left out), product_id, sales_order_id, so_line_no, pricing_unit_code (optional, v6), pricing_quantity (optional, v6; v8: the count unit_price is per, the line's own pricing_quantity), quantity_priced (v8: the line's quantity_priced, sent with pricing_unit_code), net_amount (optional, v6; the line's exact net, sent for a conditioned line)}], sold_to_bp_id, ship_to_bp_id, bill_to_bp_id (optional business-partner ids, v6: sales-order SO-40 partner functions), deductions (a final invoice or a part invoice, v6; never a deposit): [{deposit_invoice_id, net_amount, tax_category}]}"
    request_schema:
      - field: source_kind
        type: string
        required: true
        values:
          - sales_order
      - field: source_id
        type: string
        required: true
      - field: bp_id
        type: bp_id
        required: true
      - field: currency
        type: currency
        required: true
      - field: kind
        type: string
        required: false
        values:
          - regular
          - deposit
          - final
      - field: customer_po_ref
        type: string
        required: false
      - field: issue_hint
        type: string
        required: false
        values:
          - cash
      - field: sold_to_bp_id
        type: bp_id
        required: false
      - field: ship_to_bp_id
        type: bp_id
        required: false
      - field: bill_to_bp_id
        type: bp_id
        required: false
      - field: lines
        type: array
        required: true
        items:
          - field: description
            type: string
            required: false
          - field: quantity
            type: decimal
            required: true
          - field: unit_code
            type: unit_code
            required: false
          - field: unit_price
            type: decimal
            required: true
          - field: discount_pct
            type: decimal
            required: false
          - field: tax_category
            type: tax_category
            required: false
          - field: product_id
            type: product_id
            required: false
          - field: sales_order_id
            type: sales_order_id
            required: false
          - field: so_line_no
            type: so_line_no
            required: false
          - field: pricing_quantity
            type: integer
            required: false
          - field: pricing_unit_code
            type: unit_code
            required: false
          - field: quantity_priced
            type: decimal
            required: false
          - field: net_amount
            type: decimal
            required: false
      - field: deductions
        type: array
        required: false
        items:
          - field: deposit_invoice_id
            type: invoice_id
            required: true
          - field: net_amount
            type: decimal
            required: true
          - field: tax_category
            type: tax_category
            required: true
    response: "201 the invoice {invoice_id, status: draft | issued, lines (a negative line per deduction naming deducts_invoice_id, in the deposit's tax category), tax, totals}; 200 the same for the same (source_kind, source_id); 409 {gate: deposit_remaining, reason, fix}"
    status: built; aligned 2026-10-22 with ar AR-20
    rule: a debit memo request's approval raises its draft; the credit side uses POST /credit-notes (SO-41)
  - story: SO-44
    with: ar
    owner: ar
    direction: outbound
    route: POST /invoices/raise
    permission: ar:invoice:raise
    request: "{source_kind: sales_order, source_id: so:{sales_order_id}:{request_no}, bp_id (the payer), currency, kind (regular | deposit | final), customer_po_ref, issue_hint (optional, v4: cash = issued at once when the owner control auto_issue_sources contains sales_order:cash, else a draft), lines: [{description, quantity, unit_code (optional: copied from the product when left out), unit_price, discount_pct, tax_category (optional: copied from the product when left out), product_id, sales_order_id, so_line_no, pricing_unit_code (optional, v6), pricing_quantity (optional, v6; v8: the count unit_price is per, the line's own pricing_quantity), quantity_priced (v8: the line's quantity_priced, sent with pricing_unit_code), net_amount (optional, v6; the line's exact net, sent for a conditioned line)}], sold_to_bp_id, ship_to_bp_id, bill_to_bp_id (optional business-partner ids, v6: sales-order SO-40 partner functions), deductions (a final invoice or a part invoice, v6; never a deposit): [{deposit_invoice_id, net_amount, tax_category}]}"
    request_schema:
      - field: source_kind
        type: string
        required: true
        values:
          - sales_order
      - field: source_id
        type: string
        required: true
      - field: bp_id
        type: bp_id
        required: true
      - field: currency
        type: currency
        required: true
      - field: kind
        type: string
        required: false
        values:
          - regular
          - deposit
          - final
      - field: customer_po_ref
        type: string
        required: false
      - field: issue_hint
        type: string
        required: false
        values:
          - cash
      - field: sold_to_bp_id
        type: bp_id
        required: false
      - field: ship_to_bp_id
        type: bp_id
        required: false
      - field: bill_to_bp_id
        type: bp_id
        required: false
      - field: lines
        type: array
        required: true
        items:
          - field: description
            type: string
            required: false
          - field: quantity
            type: decimal
            required: true
          - field: unit_code
            type: unit_code
            required: false
          - field: unit_price
            type: decimal
            required: true
          - field: discount_pct
            type: decimal
            required: false
          - field: tax_category
            type: tax_category
            required: false
          - field: product_id
            type: product_id
            required: false
          - field: sales_order_id
            type: sales_order_id
            required: false
          - field: so_line_no
            type: so_line_no
            required: false
          - field: pricing_quantity
            type: integer
            required: false
          - field: pricing_unit_code
            type: unit_code
            required: false
          - field: quantity_priced
            type: decimal
            required: false
          - field: net_amount
            type: decimal
            required: false
      - field: deductions
        type: array
        required: false
        items:
          - field: deposit_invoice_id
            type: invoice_id
            required: true
          - field: net_amount
            type: decimal
            required: true
          - field: tax_category
            type: tax_category
            required: true
    response: "201 the invoice {invoice_id, status: draft | issued, lines (a negative line per deduction naming deducts_invoice_id, in the deposit's tax category), tax, totals}; 200 the same for the same (source_kind, source_id); 409 {gate: deposit_remaining, reason, fix}"
    status: built; aligned 2026-10-22 with ar AR-20
    rule: "issue_hint: cash; the cashier then records the payment in payments under their own permissions; sales-order never records money"
  - story: SO-45
    with: inventory
    owner: inventory
    direction: outbound
    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}]}"
    rule: CONS_ISSUE, CONS_PICKUP and CONS_RETURN are gated on it (consignment_on_hand); the stock is inventory's, never kept here
    status: aligned 2026-10-22 with inventory INV-45
  - story: SO-46
    with: ar
    owner: ar
    direction: outbound
    route: POST /schedules
    permission: ar:schedule:plan
    request: "{source_kind: sales_order, source_id: sales_order_id, line_id: line_no, bp_id (payer), starts_on, periods, unit_price, currency, billing_kind (recurring | instalment), billing_plan (monthly | quarterly | annual | periodic), quantity, discount_pct, unit_code, product_id, description, tax_category, in_advance}"
    response: 201 the schedule, keyed {sales_order_id}|{line_no}; 200 the same for the same key
    status: built; aligned 2026-10-22 with ar AR-27
    rule: periodic and instalment lines are invoicing's schedules (SO-20); milestone lines stay here and are requested through POST /invoices/raise by value
  - story: SO-47
    with: ar
    owner: ar
    direction: outbound
    route: POST /invoices/raise
    permission: ar:invoice:raise
    request: "{source_kind: sales_order, source_id: so:{sales_order_id}:{request_no}, bp_id (the payer), currency, kind (regular | deposit | final), customer_po_ref, issue_hint (optional, v4: cash = issued at once when the owner control auto_issue_sources contains sales_order:cash, else a draft), lines: [{description, quantity, unit_code (optional: copied from the product when left out), unit_price, discount_pct, tax_category (optional: copied from the product when left out), product_id, sales_order_id, so_line_no, pricing_unit_code (optional, v6), pricing_quantity (optional, v6; v8: the count unit_price is per, the line's own pricing_quantity), quantity_priced (v8: the line's quantity_priced, sent with pricing_unit_code), net_amount (optional, v6; the line's exact net, sent for a conditioned line)}], sold_to_bp_id, ship_to_bp_id, bill_to_bp_id (optional business-partner ids, v6: sales-order SO-40 partner functions), deductions (a final invoice or a part invoice, v6; never a deposit): [{deposit_invoice_id, net_amount, tax_category}]}"
    request_schema:
      - field: source_kind
        type: string
        required: true
        values:
          - sales_order
      - field: source_id
        type: string
        required: true
      - field: bp_id
        type: bp_id
        required: true
      - field: currency
        type: currency
        required: true
      - field: kind
        type: string
        required: false
        values:
          - regular
          - deposit
          - final
      - field: customer_po_ref
        type: string
        required: false
      - field: issue_hint
        type: string
        required: false
        values:
          - cash
      - field: sold_to_bp_id
        type: bp_id
        required: false
      - field: ship_to_bp_id
        type: bp_id
        required: false
      - field: bill_to_bp_id
        type: bp_id
        required: false
      - field: lines
        type: array
        required: true
        items:
          - field: description
            type: string
            required: false
          - field: quantity
            type: decimal
            required: true
          - field: unit_code
            type: unit_code
            required: false
          - field: unit_price
            type: decimal
            required: true
          - field: discount_pct
            type: decimal
            required: false
          - field: tax_category
            type: tax_category
            required: false
          - field: product_id
            type: product_id
            required: false
          - field: sales_order_id
            type: sales_order_id
            required: false
          - field: so_line_no
            type: so_line_no
            required: false
          - field: pricing_quantity
            type: integer
            required: false
          - field: pricing_unit_code
            type: unit_code
            required: false
          - field: quantity_priced
            type: decimal
            required: false
          - field: net_amount
            type: decimal
            required: false
      - field: deductions
        type: array
        required: false
        items:
          - field: deposit_invoice_id
            type: invoice_id
            required: true
          - field: net_amount
            type: decimal
            required: true
          - field: tax_category
            type: tax_category
            required: true
    response: "201 the invoice {invoice_id, status: draft | issued, lines (a negative line per deduction naming deducts_invoice_id, in the deposit's tax category), tax, totals}; 200 the same for the same (source_kind, source_id); 409 {gate: deposit_remaining, reason, fix}"
    status: built; aligned 2026-10-22 with ar AR-20
    rule: "the same deposit rule in both specs (v7: on a part invoice as well as the final one, never on a deposit): a deposit may be deducted in part, tracked per deposit, never beyond what is left, each deduction line in the deposit's tax category so the tax module accepts it"
  - story: SO-48
    with: purchasing
    owner: purchasing
    direction: outbound
    route: POST /purchase-requests/from-sales-order
    permission: purchasing:request:intake
    request: "{request_ref: so:{sales_order_id}:{line_no}@r{revision}, product_id, quantity (string), unit_code, needed_by (YYYY-MM-DD), ship_to_bp_id, ship_to_address (v8: {lines, city, postcode, region, country}, shared.yaml conventions.address), sales_order_id, so_line_no}"
    request_schema:
      - field: request_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: needed_by
        type: date
        required: true
      - field: ship_to_bp_id
        type: bp_id
        required: true
      - field: ship_to_address
        type: object
        required: true
        items:
          - field: lines
            type: array
            required: true
            items:
              - string
          - field: city
            type: string
            required: true
          - field: postcode
            type: string
            required: false
          - field: region
            type: string
            required: false
          - field: country
            type: string
            required: true
            pattern: ^[A-Z]{2}$
      - field: sales_order_id
        type: sales_order_id
        required: true
      - field: so_line_no
        type: so_line_no
        required: true
    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; v8: the address object both sides (purchasing v8)"
    rule: called at confirm for each THIRD_PARTY line; idempotent on request_ref; cancel calls POST /purchase-requests/{request_id}/cancel and a refusal there refuses the order's cancellation with purchasing's reason; purchasing reports the supplier's shipment through POST /sales-orders/{sales_order_id}/deliveries with source purchasing and delivery_ref pur:<shipping notice>
  - story: SO-48
    with: purchasing
    owner: sales-order
    direction: inbound
    route: POST /sales-orders/{sales_order_id}/deliveries
    permission: so:order:deliver
    request: "{line_no, quantity, source: purchasing, delivery_ref: pur:<shipping notice>, delivered_on}"
    response: the order view
    rule: accepted only on a THIRD_PARTY line; a repeat records once
  - story: SO-33
    with: ar
    owner: ar
    direction: outbound
    route: GET /billed-lines?bp_id=&issued_from=&issued_to=
    permission: ar:invoice:read
    request: "query bp_id, issued_from, issued_to (business dates), include_drafts (optional, default false: draft lines count toward credit headroom, v7)"
    response: 200 [{document_id, kind (invoice | credit_note), status (issued | draft), line_no, issue_date (null for a draft), product_id, category_code, net_amount, tax_category, sales_order_id, so_line_no}]
    status: aligned 2026-10-22 with ar AR-20
    rule: the rebate basis is read here; sales-order never reads ar_ tables
  - story: SO-33
    with: gl
    owner: gl
    direction: outbound
    route: POST /journal-entry/journals
    permission: gl:journal:post
    request: '{journal_id (BIGINT as string, derived_id(document_id, event)), source_module: "sales-order", source_document: "rebate:{rebate_agreement_id}:{document_id}", event (accrual | true_up | release), company_code, journal_date, currency, memo, lines: [{account_id | purpose (rebate_expense | accrued_rebates), debit | credit, bp_id}]}'
    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}"
    rule: the ledger owns journals; a refusal leaves the accrual pending with its reason in so_posting and it is retried
    status: aligned 2026-10-22 with gl GL-30
  - story: SO-34
    with: ar
    owner: ar
    direction: outbound
    route: POST /credit-notes
    permission: ar:credit_note:write
    request: "{invoice_id (optional; the original invoice), full (optional), bp_id, currency, reason, source_id (v4; so:{sales_order_id}:{request_no} | rebate:{rebate_agreement_id}:{settlement_no}; idempotent on it), account_purpose (optional, v4: rebate = posted against accrued rebates, not revenue), lines: [{invoice_line_no (against an invoice) | description, quantity, unit_price, discount_pct, net_amount, tax_category, sales_order_id, so_line_no}]}"
    response: "201 {credit_id, status: draft, lines, tax}; 200 the same for the same source_id"
    status: built (goodwill credits); aligned 2026-10-22 with ar AR-04
    rule: one credit note per settlement, idempotent on source_id; invoicing posts it against the accrued-rebates account so revenue is not reduced twice
  - story: SO-23
    with: inventory
    owner: sales-order
    direction: inbound
    route: GET /sales-orders/{sales_order_id}
    permission: so:order:read
    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"
    rule: "built (erp-brick-sales-order): inventory reads it when a delivery is raised from the order; it never reads so_ tables"
    status: aligned 2026-10-22 with inventory INV-22
  - story: SO-33
    with: ar
    owner: sales-order
    route: GET /sales-orders/{sales_order_id}
    permission: so:order:read
    request: path sales_order_id
    request_schema:
      - field: sales_order_id
        type: sales_order_id
        required: true
        in: path
    response: "200 the order whole: {sales_order_id, version, lines: [{line_no, product_id, unit_code, ...}], ...}; 404 when the caller may not see it"
    rule: ar reads each line's unit_code and product_id to bill in the ordered unit; a caller sees only its own orders unless it holds so:sales_order:read_all, which ar's service client holds
    status: added 2026-10-23, seam-gap PR
  - story: SO-24
    with: ar
    owner: sales-order
    route: GET /migration-map/{db}/{model}?ids=
    permission: so:order:read
    request: path db (the Odoo database), model sale.order.line; query ids=1,2,3 (comma-separated Odoo ids, at most 500)
    request_schema:
      - field: db
        type: string
        required: true
        in: path
      - field: model
        type: string
        required: true
        in: path
        values:
          - sale.order
          - sale.order.line
      - field: ids
        type: array
        required: true
        in: query
        items:
          - integer
    response: "200 [{odoo_model, odoo_id, ours: sales_order_id, or sales_order_id|line_no for a sale.order.line}]; an id not migrated is omitted, never a 404"
    rule: the one map route (shared.yaml conventions.odoo_migration.map_route); ar links each carried invoice line to its order line through it, so sales-order's migration runs before ar's
    status: added 2026-10-23, seam-gap PR
  - story: SO-21
    with: ar
    owner: ar
    direction: outbound
    route: GET /sources/{source_kind}/{source_id}/billed
    permission: ar:invoice:read
    request: path source_kind (sales_order), source_id (the sales_order_id)
    response: "200 {source_kind, source_id, lines: [{so_line_no, quantity_billed, net_billed}]}"
    rule: invoiced quantities and nets per order line; sales-order never reads ar_ tables
    status: added 2026-10-24, seam-gap PR 2
  - story: SO-21
    with: ar
    owner: ar
    direction: outbound
    route: POST /invoices/{invoice_id}/cancel
    permission: ar:invoice:write
    request: path invoice_id; body {version (optional)}
    response: "200 the invoice with lifecycle cancelled; 422 {gate: draft_only, reason, fix} when issued"
    rule: a cancelled invoice request cancels the draft it raised
    status: added 2026-10-24, seam-gap PR 2
  - story: SO-40
    with: ar
    owner: ar
    direction: outbound
    route: GET /invoice-totals
    permission: ar:invoice:read
    request: query invoice_ids=<comma-separated, at most 200> OR bp_id with limit and offset
    response: "200 {invoices: {invoice_id: {bp_id, lifecycle, total, currency, issue_date, due_date, invoice_no}}, more: bool}"
    rule: the issued totals of the invoices the order raised, and with bp_id of a customer (credit headroom reads these with GET /billed-lines include_drafts=true)
    status: added 2026-10-24, seam-gap PR 2
  - story: SO-41
    with: inventory
    owner: inventory
    direction: outbound
    route: POST /expected-returns/{rma_ref}/cancel
    permission: inv:return:expect
    request: path rma_ref (so:{sales_order_id})
    response: "200 {rma_ref, status: cancelled}; 422 when the RMA is partly received (it can no longer be cancelled)"
    rule: cancel_return withdraws the RMA while nothing is received; idempotent
    status: added 2026-10-24, seam-gap PR 2
  - story: SO-48
    with: purchasing
    owner: purchasing
    direction: outbound
    route: POST /purchase-requests/{request_id}/cancel
    permission: purchasing:request:intake
    request: path request_id; body {reason}
    request_schema:
      - field: request_id
        type: string
        required: true
        in: path
      - field: reason
        type: string
        required: true
    response: "200 {request_id, status: cancelled} (also for a request already cancelled with its purchase order); 422 {gate: not_cancellable, reason, fix} once the request is ordered, the reason naming the purchase order and the supplier"
    rule: "cancelling an order cancels the purchase request raised for each THIRD_PARTY line; a refusal refuses the cancel with purchasing's reason. v8 (purchasing PUR-67): an ordered request is cancelled only by cancelling its purchase order, which cancels the request with it; the order admin may then cancel the sales order again and the call answers 200"
    status: added 2026-10-24, seam-gap PR 2
  - story: SO-26
    with: product
    owner: product
    direction: outbound
    route: GET /products/{product_id}/convert?quantity=&from_unit=&to_unit=
    permission: product:product:read
    request: query quantity (string), from_unit, to_unit
    request_schema:
      - field: product_id
        type: product_id
        required: true
        in: path
      - field: quantity
        type: string
        required: true
        in: query
      - field: from_unit
        type: unit_code
        required: true
        in: query
      - field: to_unit
        type: unit_code
        required: true
        in: query
    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)"
    rule: a delivered quantity converts exactly to the base unit (SO-26); the order keeps the fraction
    status: added 2026-10-24, seam-gap PR 2
  - story: SO-36
    with: sales-order
    owner: sales-order
    direction: inbound
    route: GET /tasks?mine=
    permission: so:order:read
    request: "query mine (optional boolean, default true: your own open tasks; false = everyone's, needs so:sales_order:read_all)"
    request_schema:
      - field: mine
        type: boolean
        required: false
        in: query
    response: "200 {tasks: [{sales_order_id, kind (tell | offer), raised_on, owner, text}]}: the open tasks only (closed_by empty)"
    rule: 'SO-36: "tell" = tell the customer a later date; "offer" = an earlier date is offered to the customer, never pushed; the owner of the order is the task owner; the screen Orders lists them (built: erp-brick-sales-order list_tasks)'
    status: added 2026-10-24, seam-gap PR 2
  - story: SO-50
    with: manufacturing
    owner: sales-order
    direction: inbound
    route: GET /demand?product_id=&warehouse_id=&from=&to=
    permission: so:demand:read
    request: query product_id, warehouse_id, from, to (YYYY-MM-DD, inclusive), limit (1 to 1000, default 500), offset
    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
      - field: limit
        type: integer
        required: false
        in: query
      - field: offset
        type: integer
        required: false
        in: query
    response: "200 {product_id, warehouse_id, from, to, demand: [{needed_on, sales_order_id, line_no, open_quantity (string, in unit_code), unit_code, open_base (string, in the base unit), confirmed (bool: needed_on is a confirmed schedule date)}], more (bool)}; ordered by needed_on, sales_order_id, line_no"
    rule: "SO-50: derived on read from confirmed orders' goods lines delivered from the warehouse (open = ordered - delivered - closed short); no prices, no customer; manufacturing never reads so_ tables"
    status: added 2026-10-25 (v8) for manufacturing v1 MFG-23
  - story: SO-51
    with: timesheets
    owner: sales-order
    direction: inbound
    route: POST /sales-orders/{sales_order_id}/deliveries
    permission: so:order:deliver
    request: "{line_no, quantity (string, NUMERIC 19,4, in the line's unit: HUR or DAY; negative only with corrects_ref), source: timesheets, delivery_ref: \"ts:<sheet_id>:r<rev>:<line_no>\", delivered_on (the approval business date), corrects_ref (optional: the delivery_ref this corrects)}"
    request_schema:
      - field: sales_order_id
        type: sales_order_id
        required: true
        in: path
      - field: line_no
        type: so_line_no
        required: true
      - field: quantity
        type: decimal
        required: true
      - field: source
        type: string
        required: true
        values:
          - timesheets
      - field: delivery_ref
        type: string
        required: true
        pattern: "^ts:"
      - field: delivered_on
        type: date
        required: true
      - field: corrects_ref
        type: string
        required: false
    response: "the order view; 409 {gate: service_line | within_tolerance | not_below_invoiced, reason, fix}"
    rule: record_delivery with source timesheets, accepted only on a service line; idempotent on delivery_ref; the same rules as every other source (no over-delivery, exact in the base unit)
    status: added 2026-10-25 (v9) for timesheets v1 TS-12
tool_names:
  - tool: cancel_draft_order
    route: POST /sales-orders/{sales_order_id}/cancel-draft
    was: cancel_draft
  - tool: accept_order_suggestion
    route: POST /sales-orders/{sales_order_id}/suggestions/{step}/{suggestion_no}/decide
    was: accept_suggestion
  - tool: reconcile_order_migration
    route: GET /migration/odoo/reconcile
    was: reconcile_odoo_orders
screens:
  - id: orders
    name: Orders
    stories:
      - SO-10
    actors:
      - sales_rep
      - order_admin
      - biller
    note: "v5: filters by order type, by what an incomplete order blocks (confirm, delivery, billing), by block, and by lines not fully confirmed (promised later than requested); the owner's re-promise tasks"
  - id: order
    name: Order
    stories:
      - SO-02
      - SO-03
      - SO-04
      - SO-05
      - SO-06
      - SO-08
      - SO-09
      - SO-11
      - SO-16
      - SO-27
      - SO-28
      - SO-30
      - SO-31
      - SO-35
      - SO-37
      - SO-39
      - SO-40
      - SO-43
      - SO-44
      - SO-45
      - SO-46
      - SO-47
      - SO-48
      - SO-52
      - SO-53
    actors:
      - sales_rep
      - order_admin
      - biller
      - sales_controller
    note: "shows the readiness of the next step ({gate, met, reason, fix}) beside its button, and an open AI suggestion with accept / change / reject. v5: the type and its partners (sold-to, ship-to, bill-to, payer) in the header; per line its item category, its conditions (each with the record it came from, manual ones marked) and its schedule lines (requested and promised dates); the header conditions and freight with their spread; the billing plan with milestones and releases; deposits with what each has left; blocks with who set them"
  - id: returns
    name: Returns
    stories:
      - SO-41
      - SO-42
    actors:
      - sales_rep
      - sales_controller
    note: "v5: RMAs with their reference, received, inspected (accepted / rejected with inventory's reason) and credited quantities; credit and debit memo requests waiting for approval, with the approver never the requester"
  - id: rebates
    name: Rebates
    stories:
      - SO-32
      - SO-34
    actors:
      - order_admin
      - sales_controller
    note: "v5: agreements with their scale, the basis so far, the tier reached, accrued, settled and still to settle; settlement requests waiting for a second person"
  - id: deliveries
    name: Deliveries
    stories:
      - SO-07
    actors:
      - fulfiller
  - id: settings
    name: Settings
    stories:
      - SO-15
      - SO-29
      - SO-38
      - SO-52
      - SO-53
    actors:
      - order_admin
      - owner
    note: "every config_row below, each with the date it starts: number format, PO rules, deposits, contracts billing directly or through an order; the controls (confirm on acceptance, amendment approval, lock, business time zone, AI step modes) only for so:settings:controls"
permissions:
  namespace: so
  catalog:
    - so:order:read
    - so:order:write
    - so:order:confirm
    - so:order:approve
    - so:order:cancel
    - so:order:deliver
    - so:order:invoice
    - so:settings:write
    - so:settings:controls
    - so:sales_order:read_all
    - so:order:block
    - so:pricing:write
    - so:rebate:write
    - so:rebate:approve
    - so:memo:approve
    - so:order:intake
    - so:order:suggest
    - so:order:finish
    - so:number_series:claim
    - so:order:import
    - so:order:reschedule
    - so:rebate:accrue
    - so:return:inspect
    - so:demand:read
  machine:
    - so:demand:read
    - so:order:reschedule
    - so:rebate:accrue
    - so:return:inspect
    - so:order:intake
    - so:order:suggest
    - so:order:finish
    - so:number_series:claim
    - so:order:import
  decided_by: "permissions only, never a role's name: the brick is generic; a composition maps its own roles to these"
  row_visibility:
    rule: a caller sees the orders they own; so:sales_order:read_all sees every order; a fulfiller sees confirmed orders without prices; the fulfilment route (inventory's client) answers no prices
    enforced: "in the use case: auth.owner_scope(caller, see_all=so:sales_order:read_all); prices are projected out for a caller holding neither so:order:write nor so:sales_order:read_all"
    not_found_not_forbidden: true
  composition_roles: "v5, stated for the composition: sales-order's service client holds product:price_list:read and product:product:read (find_price, rounding, sites), inv:reservation:intake, inv:availability:read and inv:receipt:intake (ATP, consignment stock, expected returns), ar:invoice:raise, ar:invoice:read, ar:invoice:write (cancel a draft it raised), ar:credit_note:write and ar:schedule:plan, pay:credit:read, tax:document_tax:compute, bp:partner:read, purchasing:request:intake, gl:journal:post and gl:period:read; inventory's client holds so:order:deliver, so:order:read and so:return:inspect; purchasing's client holds so:order:deliver; the quote adapter holds so:order:intake, quote:quote:decide and quote:quote:read_all; a cashier holds ar:invoice:read and the payments receipt permissions"
config_rows:
  - table: so_settings
    changes: how this business takes orders
    settings:
      - key: order_number_format
        type: str
        default: SO-{yyyy}-{seq:4}
        changes: the order number stamped at confirmation
      - key: number_restarts_yearly
        type: bool
        default: true
        changes: whether the order number restarts each year
      - key: confirm_on_acceptance
        type: bool
        default: false
        changes: whether an accepted quote's order is confirmed at once instead of waiting as a draft for a person (SO-01); so:settings:controls
      - key: amendment_needs_approval
        type: bool
        default: true
        changes: whether amending a confirmed order waits for so:order:approve by someone other than the amender (SO-05); so:settings:controls
      - key: default_deposit_pct
        type: int
        default: 0
        changes: the deposit percentage a new order asks for; a customer's policy overrides it (SO-09)
      - key: lock_done_orders
        type: bool
        default: true
        changes: whether a fully delivered and invoiced order locks (SO-13); so:settings:controls
      - key: delivery_multiple_mode
        type: str
        default: warn
        changes: "warn | block: what a line off its product's delivery multiple does at confirm and amend (SO-28); so:settings:controls"
      - key: contract_creates_order
        type: bool
        default: false
        changes: "where contracts are signed: false bills an active contract directly through invoicing's contract adapter; true raises a draft order from it instead"
      - key: return_credit_on
        type: str
        default: inspection
        changes: "receipt | inspection: when a return is credited, unless its reason says otherwise (SO-41)"
      - key: free_of_charge_limit
        type: str
        default: "250.00"
        changes: the statistical value of a free-of-charge order above which a second person approves (SO-43); so:settings:controls
      - key: pick_pack_days
        type: int
        default: 1
        changes: days between stock being available and goods leaving, for promised dates (SO-35), unless inventory answers its own
      - key: reschedule_mode
        type: str
        default: later_only
        changes: "later_only | both: whether the daily re-promise also moves dates earlier on its own for quantities not yet promised (SO-36)"
      - key: rebate_accrual_mode
        type: str
        default: null
        changes: "post | report: unset = post when the ledger is installed, else a monthly report; switch from the first day of a later month (SO-33); so:settings:controls"
      - key: rebate_accounts
        type: str
        default: null
        changes: the ledger accounts per company for rebate_expense and accrued_rebates (SO-33)
      - key: default_deposit_deduction_mode
        type: str
        default: proportional
        changes: "proportional | full_first | manual: how invoices take deposits off (SO-47); a customer's policy overrides it"
  - table: so_settings
    changes: "each AI step's mode (ai_steps: off | suggest); so:settings:controls, and turning a step on is recorded as the owner's consent"
  - table: so_customer_policy
    changes: "per customer, from a date after today: PO required, deposit percentage and deduction mode, delivery terms, part deliveries and tolerances, price group, minimum shelf life"
  - table: so_order_type
    changes: the order types, their series, billing, reference, default block, pricing procedure, approval limit (v5)
  - table: so_item_category
    changes: how each kind of line behaves (v5)
  - table: so_item_category_rule
    changes: which item category a line gets per order type, product type and usage (v5)
  - table: so_condition_type
    changes: "discounts, surcharges, header conditions, freight: how each is calculated, its manual limit, its account purpose (v5)"
  - table: so_access_sequence
    changes: where each condition type looks for a record, most specific first (v5)
  - table: so_condition_record
    changes: the agreed discounts, surcharges and freight rates per key, with validity and scales (v5); so:pricing:write
  - table: so_pricing_procedure
    changes: the steps a price is built from (v5)
  - table: so_customer_partner
    changes: each customer's ship-tos (and their transit days), bill-to and payer, from a date (v5)
  - table: so_incompletion_rule
    changes: what each order type needs before confirmation, delivery or billing (v5)
  - table: so_block_reason
    changes: the reasons for delivery and billing blocks (v5)
  - table: so_return_reason
    changes: "return reasons: inspect or not, restocking fee, credit on receipt or inspection (v5)"
in_code_not_rows:
  - that a confirmed order's prices and tax are frozen; a change is a revision with a reason
  - that fulfilment and invoice status are derived from quantities
  - that nothing is delivered beyond the ordered quantity, and nothing invoiced beyond what the policy makes due
  - that an order with a delivery or an issued invoice cannot be cancelled
  - that the order asks invoicing and never writes an invoice
  - that nothing dated takes effect today or earlier, and a correction is a new row, never an edit
  - that an accepted quote's prices are copied, never re-priced; a line is priced only by find_price
  - that a line nets from its pricing quantity and pricing unit exactly, rounded once; a price per 100 is never divided down
  - that a line off its product's delivery multiple warns or is refused per delivery_multiple_mode, the same for a hand order, a quote's order and an amendment
  - "that an AI step only suggests: its output lands in so_suggestion and reaches the order only when a person accepts it"
  - that the base price is only ever product's find_price; this module's records only add or take away from it (v5)
  - that the access sequence stops at the first record found, most specific first, and a confirmed line's conditions are frozen (v5)
  - that a header condition is spread to the lines with the remainder on the largest, so the lines sum exactly (v5)
  - "that a return or a memo request never changes the original order: it is its own order referencing the original (v5)"
  - that money going back (a credit or debit memo, a free-of-charge order over the limit, a rebate settlement) is approved by a second person, by email and sign-in subject (v5)
  - that ATP never blocks a confirmation and a re-promise never moves a customer's promise earlier on its own (v5)
  - that a deposit is deducted per deposit, never beyond what is left, in its own tax category (v5)
  - that the credit check reads the payer, the tax the ship-to, and the invoice goes to the payer (v5)
ai_steps:
  - key: ai_order_from_po
    benefit: a customer's PO by email becomes a checked draft in seconds instead of ten minutes of typing
    mode: suggest
    modes_allowed:
      - off
      - suggest
    safe_for_auto: false
    inputs:
      - the PO document (PDF or email text)
      - the customer's products and recent orders
      - the referenced quote
    output: "a suggestion on an empty draft: lines matched to product_id and unit_code with confidence, the PO number, and differences from the quote; the rep accepts, changes or rejects each (SO-16)"
    fallback: the PO is attached to an empty draft for the rep
    audit: "so_suggestion: model, the PO's object key, the output, and who accepted, changed or rejected what, when"
    eval: POs with the orders a person keyed from them; line-match accuracy and PO-number exact match
  - key: ai_check_po
    benefit: a PO that quietly changes a price or a quantity is caught before confirmation, not at invoicing
    mode: suggest
    modes_allowed:
      - off
      - suggest
    safe_for_auto: false
    inputs:
      - the PO document
      - the draft order
    output: a list of differences (price, quantity, terms, delivery date) with the PO text that shows each; the rep marks each one resolved or noise before confirming (gate no_open_suggestion)
    fallback: the rep compares by eye
    audit: so_suggestion, as for ai_order_from_po
    eval: PO and order pairs with seeded differences; recall of the seeded differences
  - table: so_minimum_order
    changes: "the smallest order value worth taking, per currency and optional price group, and what happens below it: surcharge | block | warn (SO-52); dated, append-only; so:settings:controls"
  - table: so_substitution
    changes: which product replaces which, from when, for which price group, by what reason, automatically or as a proposal (SO-53); dated, append-only; so:settings:write
tests:
  acceptance: one per story id above, named for it
  access:
    - a rep sees and changes only their own orders; another rep's order is a 404
    - a fulfiller records deliveries and never sees a price
    - with inventory installed, a fulfiller's hand delivery on a stocked line is refused even with so:order:deliver; only source inventory (inventory's service client) records it (v3)
    - only a holder of so:order:cancel cancels a confirmed order, and of so:order:approve overrides a credit hold
    - only so:settings:controls changes confirm_on_acceptance, amendment_needs_approval, lock_done_orders, delivery_multiple_mode or an AI step's mode; so:settings:write is refused on them
    - a wildcard grant (so:*:*) does not reach so:order:intake, :suggest, :finish, :import or so:number_series:claim
    - an amendment is never approved by the rep who made it
    - "v12: only so:settings:controls sets a minimum order policy and only a holder of so:order:approve who is not the order's owner overrides a block; so:settings:write sets a substitution record and is refused on the minimum"
    - "v5: only so:pricing:write changes condition records, order types, item categories, pricing procedures, incompletion rules and customer partners; only so:order:block sets or releases a block; only so:memo:approve approves a memo request or free-of-charge order, and never its requester (email AND sign-in subject); only so:rebate:approve approves a settlement, never its requester nor the agreement's author"
    - "v5: so:return:inspect, so:order:reschedule and so:rebate:accrue are reached by no wildcard grant; a person holding so:order:deliver cannot record an inspection"
    - "v5: the fulfilment route answers no price, condition or value"
  invariants:
    - the same accepted quote version yields one order
    - a confirmed order's lines, prices and tax never change except by a revision
    - delivered <= ordered per line; invoiced <= due per the line's policy
    - fulfilment and invoice status are never stored
    - the same invoice request (order, request_no) yields one invoice
    - a deposit is deducted until used, and never exceeds the order total
    - every line has priced_from; a line from an accepted quote keeps the quote's price; only an amended line is re-priced
    - "'today' is the date in business_timezone; nothing dated (an order, a policy, a setting, a delivery) is back-dated, and a delivery is never in the future"
    - a transition refused for a gate names the gate, its reason and its fix, the same as the readiness answer
    - nothing from an AI step is on an order unless a person accepted it, and so_suggestion records who
    - "v3: with inventory installed, every delivery on a stocked line has source inventory; a service line is delivered by hand; without inventory every line is delivered by hand"
    - "v3: confirm, every amendment and cancel each call inventory's reservation route once per (sales_order_id, revision) or release; a retry changes nothing; a short reservation never blocks a confirmation"
    - "v3: every delivered quantity converts exactly to the base unit (quantity x numerator / denominator, no float) and is stored beside it; an inexact one is refused, never rounded"
    - the Odoo migration run twice writes the same rows once; history is never re-priced, re-taxed or invoiced
    - "v4: every line has pricing_quantity (whole, >= 1) and a pricing unit with its conversion; net_amount = round_half_up(quantity_base x pricing_denominator / pricing_numerator x unit_price / pricing_quantity x (1 - discount_pct/100), minor unit), no float; a line with pricing_quantity 1 in its own unit nets exactly as v3"
    - "v4: in warn mode a line off its delivery multiple confirms and the order shows the reason; in block mode it is refused with the gate named; the mode in force is the one on the confirmation's (or amendment's) date"
    - 'v4: catch_quantity and catch_unit_code are NULL on every delivery; a delivery carrying them is a 422 ("catch weight arrives in M7")'
    - "v5: an order's type never changes after confirmation; each type's series claims a number with a plain INSERT on (series_id, number): never reused, no gap from a refused confirmation, a migrated series continues after Odoo's highest"
    - "v5: BASE on every priced line equals find_price's answer for (product, quantity, unit, sold-to, currency, priced_on); the access sequence takes the first record found; a confirmed line's conditions never change except by a revision; net = BASE + the sum of the line's condition amounts, each rounded once, half up"
    - "v5: header conditions and freight are spread so the lines' shares sum exactly to the header amount (the remainder on the largest line by net, or the heaviest for freight)"
    - "v5: a rate or amount above its NUMERIC bound (19,4 / 18,2) or a quantity above 10^12 is a 422 with the reason, never a 500"
    - "v5: ATP never blocks a confirmation; the schedule lines of a line never confirm more than its quantity; a re-promise runs once per business date ('today' in business_timezone, never the UTC date, and never going backwards) and never moves a promised date earlier on its own unless reschedule_mode is both"
    - "v5: a returns order line never returns more than delivered less already returned on the original line; accepted + rejected never exceed received; a credit is requested once per (returns order, request_no) and only for accepted quantities (or received, with credit on receipt); the original order's delivered and invoiced quantities never change because of a return"
    - "v5: two concurrent credit or return requests on the last pound of an invoice line: one wins the credit_claim row, the other is refused with what is left"
    - "v5: two concurrent invoice requests never deduct the same deposit amount twice (deposit_deduction claim rows); a deduction line carries the deposit's tax category; at order end every issued deposit is fully deducted or credited"
    - "v5: a milestone line's billed net never exceeds its released milestones; the last milestone takes the remainder exactly; milestones that do not total 100% refuse confirmation"
    - "v5: a rebate accrual is written once per (agreement, document, line) and its journal once per (document, event); a settlement credits once per (agreement, settlement_no); after the final settlement the agreement's accrual nets to exactly 0.00"
    - "v5: a CASH order is never credit-checked and never takes a deposit or a billing plan; a FREE_OF_CHARGE or CONS_FILL order is never invoiced; a CREDIT_REQ or DEBIT_REQ is never delivered"
    - "v5: a THIRD_PARTY line accepts deliveries only with source purchasing, and is never reserved in inventory"
    - "v5: the partners on an order are copied at creation and change only by an amendment before the first delivery; the credit check reads the payer; invoicing receives bp_id = the payer"
    - "v5: a migration re-run never rewrites a signed run, and never re-prices, re-taxes, re-promises or invoices history"
  scenarios:
    - id: SC-SO-01
      name: quote to order to invoice, ordered policy
      stories:
        - SO-01
        - SO-03
        - SO-08
      given: quote Q-2026-0042 v2 accepted, 3 service lines, policy ordered
      when: the acceptance is handed over twice, the order confirmed, the invoice requested twice
      then: one order, numbered at confirmation; one draft invoice with the 3 lines; the second request creates nothing
    - id: SC-SO-02
      name: part delivery, delivered policy
      stories:
        - SO-07
        - SO-08
        - SO-12
      given: a confirmed order of 12 units, policy delivered
      when: 5 are delivered and invoiced, then 7 more delivered and invoiced
      then: two invoices of 5 and 7; the order is done after the second; recording DN-118 twice counts once
    - id: SC-SO-03
      name: deposit then final
      stories:
        - SO-09
        - SO-08
      given: an order of 10,000.00 net with a 50% deposit
      when: the deposit is raised, then the full order invoiced
      then: a deposit invoice of 5,000.00 net and a final invoice of 10,000.00 net less the 5,000.00 deposit
    - id: SC-SO-04
      name: credit hold
      stories:
        - SO-03
        - SO-22
      given: a customer with an invoice 75 days overdue and hold mode block
      when: the rep confirms
      then: refused with the reason; an order admin overrides with a reason and it confirms
    - id: SC-SO-05
      name: amend before delivery
      stories:
        - SO-05
      given: a confirmed order of 10, 4 delivered
      when: the rep changes 10 to 12, then to 3
      then: revision 2 at 12 after approval; 3 is refused (below 4 delivered)
    - id: SC-SO-06
      name: units and prices on a hand order
      stories:
        - SO-02
        - SO-05
      given: COLA-075 at 1.20 a bottle (C62) and 24.00 a pack (PK24) on the customer's list from 2026-10-01, and 1.30 a bottle from 2026-12-01
      when: on 2026-11-02 the rep orders 2 x PK24 and 6 x C62, confirms, then on 2026-12-03 amends the bottles to 12
      then: the pack line is 48.00 with priced_from the pack's row; the bottle line was 7.20 and after the amendment is 15.60 with a new priced_from; the pack line is untouched; an order dated 2026-11-01 on 2026-11-02 is refused
    - id: SC-SO-07
      name: AI suggestion is only a suggestion
      stories:
        - SO-14
        - SO-16
        - SO-03
      given: the owner turned ai_order_from_po to suggest; PO-4471 arrives with a quantity that differs from the quote
      when: the suggestion is made, then the rep tries to confirm, then accepts the lines and marks the difference resolved
      then: the draft is empty until accepted; confirming with the difference open is refused (gate no_open_suggestion); so_suggestion records the rep's decisions
    - id: SC-SO-09
      name: priced per 100, delivered in sixes
      stories:
        - SO-27
        - SO-28
        - SO-03
      given: SCREW-M4 at 2.4500 per 100 C62; COLA-075 delivered in multiples of 6 C62; delivery_multiple_mode warn
      when: an order of 250 C62 SCREW-M4 and 20 C62 COLA-075 is confirmed; the owner sets block from tomorrow; the next day the COLA line is amended to 22, then to 24
      then: the screw line nets 6.13 with pricing_quantity 100; the confirmation passes with the delivery_multiple reason shown; the amendment to 22 is refused (block), to 24 accepted
    - id: SC-SO-10
      name: procedure pricing, header discount and freight
      stories:
        - SO-30
        - SO-31
        - SO-02
      given: the records of SO-30; FREIGHT 0.12 per KGM in GB
      when: 120 C62 of COLA-075 and 120 C62 of COLA-150 are ordered for 7311, HDR_DISC 2% added, the order confirmed and invoiced
      then: nets 148.13 and 232.47, order net 380.60 exactly; invoicing receives the two lines with those nets; the invoice nets the same
    - id: SC-SO-11
      name: promise, re-promise and deliver in parts
      stories:
        - SO-35
        - SO-36
        - SO-37
        - SO-25
      given: COLA-075 360 LTR free, PO-0101 720 LTR due 2026-11-09; 7311 accepts at most 3 part deliveries
      when: 480 C62 are ordered for 2026-11-04 and confirmed; PO-0101 moves to 2026-11-16; the re-promise runs twice; inventory delivers 240 then 240
      then: 240 promised for 4 Nov and 240 for 12 Nov; after the move one new schedule version and one task; two part deliveries; the line delivered
    - id: SC-SO-12
      name: a return through inspection to credit
      stories:
        - SO-41
        - SO-49
        - SO-42
      given: SO-2026-0012 delivered and invoiced 24 C62 at 1.20
      when: an RMA for 6 is authorised, 6 come back, 5 are accepted, a credit memo request for 0.10 x 24 is raised and approved by a controller, and the requester's second account tries first
      then: one credit of 6.00 net for the return, one of 2.40 for the price; the second account refused; the original order still 24 delivered and 24 invoiced
    - id: SC-SO-13
      name: a rebate year
      stories:
        - SO-32
        - SO-33
        - SO-34
      given: RB-2027-7311, 1% / 2% / 3% retroactive, accrual 2%
      when: invoices of 120,000.00 drinks are issued over 2027 and accrued nightly (one night twice), 1,000.00 settled in July, the final settlement approved by a second person
      then: accruals 2,400.00, each journal once; the final credit 2,600.00; the true-up 1,200.00; the accrual nets to 0.00
    - id: SC-SO-14
      name: milestones and part deposits
      stories:
        - SO-46
        - SO-47
        - SO-20
      given: PROJ-INSTALL 20,000.00 with milestones 30 / 40 / 30 and a deposit of 2,000.00 deducted proportionally
      when: M1 is billed at confirmation, M2 released and billed, M3 released and billed, two requests racing on M2
      then: 6,000.00, 8,000.00 and 6,000.00, each less its share of the deposit (600.00, 800.00, 600.00); the racing request deducts nothing twice
    - id: SC-SO-15
      name: partners, cash, free of charge and consignment
      stories:
        - SO-40
        - SO-44
        - SO-43
        - SO-45
        - SO-48
      given: 7311 with payer 7400 on hold; a walk-in; samples; consignment stock at 7311; a drop-shipped printer
      when: an order for 7311 is confirmed, a CASH sale made, samples sent, 60 issued from consignment and the printer shipped by the supplier
      then: the credit refusal names 7400; the cash sale is delivered and invoiced at once; the samples are never invoiced; the 60 are invoiced at the issue date's price; the printer is delivered from purchasing's call only
    - id: SC-SO-08
      name: Odoo migration reconciles to zero
      stories:
        - SO-24
      given: an Odoo test database with open, done and cancelled orders, a down payment, a line in a non-base unit and a section line
      when: the migration runs twice and the reconciliation is computed
      then: every check in migration.odoo.reconcile is equal or explained by a listed reason; the section line is counted as not carried; no invoice request exists for a history order
scale:
  reads: "the tables reader serves 16 concurrent reads; the order list derives statuses from deliveries and invoicing's billed quantities: read them in one query per page"
  hot_paths:
    - the order list with derived statuses
    - request_invoice reading billed quantities
  workers: none
  volumes: thousands of orders a month is comfortable; page the list and read billed quantities per page
customer_varies:
  - question: When the customer says yes to a quote, is that the order, or do you wait for their PO?
    changes: so_settings (auto-confirm on acceptance), so_customer_policy.po_required
    typical:
      b2b_services: the signed quote is the order
      larger_customers: nothing starts without their PO number on the invoice
  - question: Do you invoice when the order is confirmed, or when you deliver?
    changes: each product's invoicing_policy (ordered | delivered)
    typical:
      subscriptions_and_fixed_fees: on order
      goods_and_time_and_materials: on delivery
  - question: Do you take a deposit up front?
    changes: so_settings default deposit, so_customer_policy.deposit_pct
    standard: "HMRC VAT Notice 700 section 14: a payment received before the basic tax point creates a tax point for the amount received"
  - question: Should an overdue customer be able to order?
    changes: payments' pay_settings credit-hold rule and mode (warn | block); the order reads them (SO-22)
    typical:
      small_firms: a warning, the owner decides
      distributors: block above the credit limit
  - question: Can a confirmed order change, and who agrees?
    changes: so_settings (amendment approval)
  - question: Which kinds of order do you have besides a normal sale (rush, cash at a counter, returns, credit requests, free samples, stock held at customers)?
    changes: so_order_type rows in use, their series and approval limits
    typical:
      b2b_services: standard, credit requests
      wholesale: standard, rush, returns, credit and debit requests, free of charge
      trade_counter: cash sales as well
  - question: Besides the price list, do customers have agreed discounts, surcharges or freight?
    changes: so_condition_type, so_access_sequence, so_condition_record, so_pricing_procedure
    typical:
      most_small_firms: the price list only (BASE and a manual line discount)
      distributors: customer and group discounts by category, freight by weight
  - question: Do customers earn year-end rebates?
    changes: so_rebate_agreement; rebate_accrual_mode and the rebate accounts
  - question: Does any customer have goods delivered to depots, invoiced to head office, or paid by a group company?
    changes: so_customer_partner (ship-to, bill-to, payer)
  - question: "How are returns handled: authorised first, inspected, credited when?"
    changes: so_return_reason, return_credit_on
  - question: Are large jobs billed in stages?
    changes: billing milestones per line; billing_plan milestone | instalment
  - question: Do you sign contracts for what you sell (a subscription, a retainer)?
    changes: so_settings.contract_creates_order
    typical:
      reference: the active contract bills directly through invoicing (no order), decided 2026-10-18
      firms_that_report_on_orders: a draft order per contract, confirmed by a person
variation_points:
  - node: Task_order_from_quote
    op: row_value
    default: a draft, confirmed by a person
    depth: 1
    guideline: warn - confirming automatically skips the PO check most B2B customers expect
  - node: Task_customer_sends_po
    op: on_off
    default: only for customers whose policy requires a PO
    depth: 1
    guideline: warn - a missing PO is the commonest reason a large customer's AP team rejects an invoice
  - node: Task_raise_deposit
    op: on_off
    default: off
    depth: 1
    guideline: warn - with a deposit on, the tax point of the deposit is when it is paid or invoiced (VAT Notice 700 s14)
  - node: Task_amend_sales_order
    op: row_value
    default: approval by an order admin
    depth: 1
    guideline: warn - an unapproved amendment changes a commitment nobody signed
  - node: Task_record_delivery
    op: re_lane
    default: a person records deliveries
    depth: 2
    guideline: warn - with the deliveries brick (M4) installed, deliveries come from it; keep one source
  - node: Task_approve_memo_request
    op: row_value
    default: a second person approves every credit and debit memo request
    depth: 1
    requirement: refuse - money going back to a customer on one person's word is the commonest sales-side fraud
  - node: Task_promise_dates
    op: on_off
    default: on with inventory installed
    depth: 1
    guideline: warn - without it the requested date is printed as if promised
  - node: Task_request_return_credit
    op: row_value
    default: credit after inspection
    depth: 1
    guideline: warn - crediting on receipt pays for goods the warehouse may reject
reference:
  repos:
    - name: erp-brick-sales-order
      role: brick
      https: https://git.dodil.io/dodil/erp-brick-sales-order.git
      ssh: git@git.dodil.io:dodil/erp-brick-sales-order.git
      tag: v0.2.0
      read_first:
        - README.md
        - AGENTS.md
      clone: git clone --depth 1 --branch v0.2.0 https://git.dodil.io/dodil/erp-brick-sales-order.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: brick-business-partner
      role: brick
      https: https://git.dodil.io/dodil/erp-brick-business-partner.git
      ssh: git@git.dodil.io:dodil/erp-brick-business-partner.git
      tag: v0.4.0
      read_first:
        - README.md
        - AGENTS.md
      clone: git clone --depth 1 --branch v0.4.0 https://git.dodil.io/dodil/erp-brick-business-partner.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:
    - "no picking or shipping here: with inventory installed (v3) stocked lines are reserved and delivered by inventory; without it, deliveries are recorded by a person"
    - "no back-order documents: a part-delivered line simply has quantity left to deliver, with its schedule lines (v5)"
    - "no margin on the order: cost is inventory's valuation (or the product's standard cost), shown only to the order admin"
    - no customer portal view of the order; the confirmation is emailed
    - no optional products, upsell or order templates; quote templates belong to the quote brick
    - "no blanket orders or call-offs against a quantity or value contract: a signed contract bills through invoicing (contracts); scheduling agreements with delivery schedules are not modelled"
    - version 5 (order types, the pricing procedure, rebates, ATP dates, partner functions, returns, memo requests, free of charge, cash, consignment, milestones, part deposits, third party) is specified, not built
    - "cross-module, assumed by v5 and not yet in the other specs: business-partner addresses (ship-to), tax's place of supply by ship_to_country, invoicing's credit notes keyed by source_id with the caller's order lines and an account purpose, deductions by amount, issue_hint cash, GET /billed-lines; purchasing's POST /purchase-requests/from-sales-order; inventory's GET /atp, GET /sales-orders/{id}/fulfilment use, POST /expected-returns, GET /consignment-stock (inventory v3 specifies them)"
    - version 4 (pricing quantity on the line, the delivery multiple gate) is specified, not built
    - catch weight on deliveries (the actual kilograms of pieces shipped, invoiced by weight) is designed in inventory and deferred to M7 (`deferred:`)
    - the AI-step marker in the BPMN is a task name until erp-platform draws dodil:ai / dodil:mode (M0 AI-step contract)
migration:
  odoo:
    runs_after:
      - business-partner
      - product
      - tax
    reads:
      - model: sale.order
        fields:
          - id
          - name
          - company_id
          - state
          - locked
          - partner_id
          - partner_invoice_id
          - partner_shipping_id
          - client_order_ref
          - date_order
          - commitment_date
          - user_id
          - currency_id
          - pricelist_id
          - payment_term_id
          - incoterm
          - origin
          - amount_untaxed
          - amount_tax
          - amount_total
          - invoice_status
        filter: state in ('sale', 'done', 'cancel'), every company being migrated; draft and sent are read only to count them (they go to brick-quote, see door)
        why: "the order header: who, which number, which terms, and the totals the reconciliation compares"
      - model: sale.order.line
        fields:
          - id
          - order_id
          - sequence
          - display_type
          - is_downpayment
          - product_id
          - name
          - product_uom_qty
          - product_uom
          - price_unit
          - discount
          - tax_id
          - price_subtotal
          - price_tax
          - price_total
          - qty_delivered
          - qty_invoiced
          - qty_to_invoice
          - invoice_status
        filter: order_id in the orders read
        why: the lines with their unit, price, and what Odoo says was delivered and invoiced
      - model: product.pricelist
        fields:
          - id
          - name
          - currency_id
        filter: id in the orders' pricelist_id
        why: only to name priced_from on migrated lines; the price lists themselves are product's migration
      - model: account.move.line
        fields:
          - id
          - move_id
          - sale_line_ids
          - quantity
          - product_uom_id
          - parent_state
        filter: sale_line_ids in the lines read, parent_state = 'posted'
        why: to check that invoicing's migrated invoice lines carry sales_order_id and line_no for every Odoo sale line link (qty_invoiced is read back from invoicing, never stored here)
    maps:
      - from: sale.order.company_id + name
        to: sales_order.sales_order_id
        rule: odoo:<company_id>:<name> (e.g. odoo:1:S00042); the key a re-run matches
      - from: sale.order.name
        to: sales_order.order_no
        rule: kept as is, never renumbered; so_number_series.high_water_mark is set past the highest migrated number of the current year
      - from: sale.order.state
        to: sales_order.lifecycle
        rule: sale and not locked with anything left to deliver or invoice -> confirmed (open); sale fully delivered and invoiced, done, or locked -> done; cancel -> cancelled; draft and sent -> not here (door)
      - from: sale.order.partner_id
        to: sales_order.bp_id
        rule: the commercial partner, through business-partner's migration map; the invoice and delivery addresses through the same map
      - from: sale.order.client_order_ref
        to: sales_order.customer_po_ref
        rule: copied
      - from: sale.order.date_order
        to: sales_order.ordered_on and confirmed_at
        rule: Odoo stamps date_order at confirmation; both take it in business_timezone; migration is the one writer allowed a past date
      - from: sale.order.user_id
        to: sales_order.owner
        rule: through the user map; an unmapped user -> the migration owner named at the door
      - from: sale.order.currency_id / pricelist_id / payment_term_id
        to: sales_order.currency / price_list_id / payment_terms_id
        rule: ISO 4217 code; price list through product's map; payment terms written as invoicing's own key odoo:<payment_term_id> (ar's migration creates the term under that key, so no ar map is read and ar may run after sales-order, v5); the reconcile checks every key exists once ar has run
      - from: sale.order.partner_id / partner_invoice_id / partner_shipping_id
        to: so_order bp_id / bill_to_bp_id / ship_to_bp_id, payer_bp_id = the invoice partner's commercial partner (v5)
        rule: through business-partner's map; a delivery or invoice contact that is a child address of the customer maps to the customer itself with the address copied on the order; distinct companies become so_customer_partner rows dated the cut-over
      - from: sale.order.type_id (OCA sale_order_type, where installed) or the door's rule
        to: so_order.order_type_code (v5)
        rule: STANDARD unless the door names a type (a sale.order.type per Odoo type); every migrated line's item category from the product's type
      - from: sale.order.commitment_date
        to: so_order.requested_delivery_on and one schedule line per open line (v5)
        rule: one schedule version 0 per open line, confirmed for the commitment date (else the order date); re-promised by the first daily run after cut-over
      - from: sale.order.line (sequence, id)
        to: order_line.line_no
        rule: 1..n by (sequence, id) over carried lines only; recorded with the Odoo line id so a re-run numbers the same
      - from: sale.order.line.product_id
        to: order_line.product_id
        rule: the variant's default_code through product's map (product_id is the SKU)
      - from: sale.order.line.product_uom
        to: order_line.unit_code
        rule: uom.uom through product's unit map to UN/ECE Rec 20; the unit's conversion to the product's base unit is copied onto the line
      - from: sale.order.line.product_uom_qty
        to: order_line.quantity
        rule: copied, in that unit
      - from: sale.order.line.price_unit / discount
        to: order_line.unit_price, list_price / discount_pct
        rule: copied, never re-priced; list_price = price_unit, unit_price = price_unit x (1 - discount/100); pricing_unit_code = unit_code, pricing_quantity 1 (Odoo prices per one of the line's unit); priced_from = odoo:<pricelist name>, priced_on = date_order
      - from: sale.order.line.tax_id / price_subtotal / price_tax
        to: order_line.tax_code / net_amount / tax_amount
        rule: tax_code through tax's map; amounts copied as Odoo computed them, never recomputed
      - from: sale.order.line.qty_delivered
        to: delivery
        rule: "one row per line with qty_delivered > 0: kind opening, delivery_ref odoo:<sale.order.line id>, delivered_on = the cut-off date, source migration"
      - from: sale.order.line.qty_invoiced
        to: (read back from invoicing)
        rule: not stored; invoicing's migrated lines carry sales_order_id and line_no (ar's migration) and the order reads them back
      - from: sale.order.line where is_downpayment
        to: invoice_request (kind deposit)
        rule: "not an order line: one deposit request per down payment on an open order, naming the migrated deposit invoice, so the later invoices still deduct what is unused"
      - from: product.template.invoice_policy (order | delivery)
        to: order_line.invoicing_policy (ordered | delivered)
        rule: copied from the migrated product at line time
      - from: sale.order.line.discount
        to: line_condition DISC_PCT, source manual odoo (v5)
        rule: the BASE condition is price_unit, the discount a manual DISC_PCT, the net copied; nothing re-priced
    door:
      - "where Odoo quotations (draft, sent) go: open quotes in brick-quote, draft orders here, or left in Odoo"
      - "the cut-off date: Odoo sales are frozen at it, and opening deliveries are dated on it"
      - "how much history comes over: every order, or only orders of the open years plus every open order"
      - every Odoo unit, product, tax, price list, payment term and user on an open order maps to ours (an unmapped one stops the run with a list)
      - who owns migrated orders whose salesperson no longer works here
      - which Odoo order types (if any) map to our order types, and whether any open order is really a return or a sample
      - "open rebate agreements and milestone jobs: re-entered by hand, with what was earned or billed so far"
      - whether delivery addresses differing from the customer's main address come over as order addresses or are left on the history
    reconcile:
      - check: orders per state
        odoo: count sale.order by state (sale open, sale finished + done + locked, cancel)
        ours: count so_order by lifecycle with source_kind odoo
        must: equal
      - check: draft and sent orders accounted for
        odoo: count sale.order where state in (draft, sent)
        ours: count of quotes brick-quote migrated, or so_order drafts, or the number the customer chose to leave
        must: explained
      - check: totals per currency, open and history
        odoo: sum amount_untaxed, amount_tax, amount_total by currency
        ours: sum subtotal, tax_total, total by currency
        must: equal
      - check: lines carried
        odoo: count sale.order.line where display_type is null and not is_downpayment
        ours: count so_line of migrated orders
        must: equal
      - check: lines not carried
        odoo: count sale.order.line where display_type in (line_section, line_note) or is_downpayment
        ours: the not-carried count in the run log, by reason
        must: explained
      - check: prices unchanged
        odoo: per line price_unit, discount
        ours: per line list_price, discount_pct
        must: equal
      - check: to deliver per open line
        odoo: product_uom_qty - qty_delivered
        ours: quantity - sum(delivery.quantity)
        must: equal
      - check: to invoice per open line
        odoo: qty_to_invoice
        ours: the derived quantity to invoice, with invoicing's billed quantity read back
        must: equal | explained (a credit note not linked to its sale line, listed by invoice)
      - check: invoiced per line
        odoo: qty_invoiced
        ours: invoicing's billed-per-source for (sales_order_id, line_no)
        must: equal | explained (as above)
      - check: partner functions on open orders
        odoo: per open order partner_id, partner_invoice_id, partner_shipping_id
        ours: bp_id, bill_to_bp_id, ship_to_bp_id through business-partner's map
        must: equal | explained (a child address mapped to its company, listed)
      - check: payment terms resolve
        odoo: distinct payment_term_id on migrated orders
        ours: count of those odoo:<id> keys found in invoicing's terms after ar has run
        must: equal
      - check: unused deposits per open order
        odoo: per order, the down payments invoiced less those deducted on later invoices (the is_downpayment line's invoiced amount, positive and negative)
        ours: sum of deposit requests less deductions
        must: equal
    not_carried:
      - "section and note lines (display_type): layout, not commitments; their text stays on the read-only history export"
      - "Odoo's invoice_status and delivery status: derived here from quantities"
      - "the chatter, tracking values and activities (mail.message): kept in the Odoo export, not in orders"
      - "optional products (sale.order.option) and quotation templates: quote brick concerns, and an option nobody ordered is not a commitment"
      - "stock pickings and moves: only the delivered quantity per line comes over, as one opening delivery; the M4 delivery bricks migrate stock"
      - "online signatures and portal access tokens: a new confirmation is sent from ours if needed"
      - "analytic distribution and margin: no analytic accounts or order margin in this brick"
      - "price lists and their rules: migrated by product; a migrated line names its Odoo list only as priced_from text"
      - "a pricing quantity: Odoo has none (every migrated line is per 1 of its unit)"
      - "the packaging chosen on an Odoo 16-18 line (product_packaging_id / product_packaging_qty): the line stays in its product_uom; the pack is a product unit and its delivery multiple a product rule from now; migrated orders are never re-gated"
      - "catch weight: Odoo has none (no actual weight per delivery); nothing to carry"
      - "rebates: Odoo has none (loyalty programmes are a different thing); open agreements are entered by hand from the cut-over, with what was earned so far as a partial settlement figure (door)"
      - "returns (stock.return.picking, OCA rma): open returns are raised again as RMAs after cut-over; done ones stay as Odoo history and their credit notes are invoicing's migration"
      - "billing plans: Odoo has none on a sale order (a down payment by percentage is the deposit map above); open milestone jobs are given their remaining milestones by hand (door)"
      - "condition records: Odoo pricelist rules are product's migration; customer discounts typed per line come over as manual conditions only"
    idempotent_on: sales_order_id = odoo:<company_id>:<sale.order name>; lines on (sales_order_id, line_no) with the Odoo line id recorded; opening deliveries on delivery_ref odoo:<sale.order.line id>
deferred:
  - id: catch_weight
    milestone: M7
    sap: "catch weight in sales: the parallel unit recorded at goods issue and billed (CWM in SD)"
    design: a product with a parallel unit is sold in pieces with a pricing unit of that parallel unit (KGM). Inventory's delivery records the actual weight (catch_quantity, catch_unit_code) and passes it to record_delivery; the order keeps it on the delivery row, and the quantity due for invoicing in the pricing unit is the sum of the delivered catch_quantity, not the nominal conversion; invoicing bills it in the pricing unit.
    reserved_columns:
      - table: so_delivery
        columns:
          - catch_quantity NUMERIC(19,6) NULL
          - catch_unit_code VARCHAR NULL
    until_then: the columns are NULL; record_delivery carrying catch_quantity is a 422; invoicing quantities come from the line's conversion
sap_parity:
  - sap: Inquiry and quotation (VA11, VA21) to sales order with reference
    ours: covered
    where: SO-01 (quotes are brick-quote's, crm; the adapter and its routes exact in v5)
  - sap: Sales document types (OR, SO rush, BV cash, RE, G2, L2, FD, KB / KE / KA / KR) with their number ranges and controls
    ours: covered
    where: SO-29, order_type, number_claim
  - sap: "Item categories and their determination (VOV4: TAN, TAD, TAS, TANN, REN, KBN, KEN)"
    ours: covered
    where: SO-29, item_category, item_category_rule
  - sap: Pricing procedure and condition technique (condition types, access sequences, condition records with scales and validity)
    ours: covered
    where: SO-30, condition_type, access_sequence, condition_record, pricing_procedure, line_condition; the base price is product's find_price (PRD-11)
  - sap: Header conditions, group conditions and freight (HA00, HB00, KF00) distributed to items
    ours: covered
    where: SO-31
  - sap: Manual condition changes with limits
    ours: covered
    where: SO-30 (manual_limit per condition type)
  - sap: "Condition pricing unit on the item (KPEIN / KMEIN: price per 100)"
    ours: covered
    where: SO-27, order_line
  - sap: Sales unit and conversion to the base unit on the item (VRKME, UMVKZ / UMVKN)
    ours: covered
    where: SO-02, SO-26, order_line
  - sap: Delivery unit and minimum delivery quantity checks
    ours: covered
    where: SO-28
  - sap: Availability check against stock (ATP) at order entry
    ours: covered
    where: SO-35, SO-25, inventory INV-49
  - sap: ATP with delivery scheduling and confirmed dates (schedule lines, backward / forward scheduling)
    ours: covered
    where: SO-35, schedule_line
  - sap: Backorder processing and rescheduling (V_V2)
    ours: covered
    where: SO-36
  - sap: "Credit management: credit limit check and release of blocked orders (FSCM, VKM1)"
    ours: covered
    where: SO-22, SO-40, SO-03 (payments' hold on the payer, admin override with a reason)
  - sap: "Partner functions: sold-to, ship-to, bill-to, payer"
    ours: covered
    where: SO-40, customer_partner, sales_order
  - sap: Incompletion procedure (V.02) with status groups for delivery and billing
    ours: covered
    where: SO-38, incompletion_rule, readiness {gate, met, reason, fix}
  - sap: Customer purchase order number and PO-required rules
    ours: covered
    where: SO-04, customer_order_policy
  - sap: Order confirmation output
    ours: covered
    where: send_confirmation (with promised dates, v5)
  - sap: Order changes with versions and approval
    ours: covered
    where: SO-05, revision
  - sap: Delivery and billing blocks on the order, with reasons
    ours: covered
    where: SO-39, order_block, block_reason
  - sap: Partial and complete delivery, partial delivery agreements, under / over-delivery tolerances, delivery split, order combination
    ours: covered
    where: SO-37, inventory INV-07
  - sap: Order-related and delivery-related billing
    ours: covered
    where: SO-08, invoicing_policy
  - sap: "Billing plans: periodic and milestone"
    ours: covered
    where: SO-46 (milestones here, periodic and instalment as invoicing's schedules, SO-20)
  - sap: Down payment requests and clearing in the final invoice (FAZ), partial clearing
    ours: covered
    where: SO-09, SO-47, deposit_deduction
  - sap: "Returns: return order, returns delivery, inspection and credit (RE, advanced returns management)"
    ours: covered
    where: SO-41, SO-49, return_order workflow, inventory INV-14
  - sap: Credit and debit memo requests with release (G2, L2, billing block)
    ours: covered
    where: SO-42, approve_memo_request
  - sap: Free-of-charge deliveries and subsequent free-of-charge deliveries (FD, SDF)
    ours: covered
    where: SO-43
  - sap: Rebate agreements, accruals and settlement (condition contracts / settlement management)
    ours: covered
    where: SO-32, SO-33, SO-34, rebate_agreement workflow
  - sap: Quantity and value contracts with call-offs (WK1, WK2) and scheduling agreements (LP)
    ours: different
    where: contracts module; known_gaps
    why: a signed contract bills directly through invoicing; call-offs against a quantity contract and delivery schedules are not modelled (an SME re-orders on a standard order)
  - sap: Customer consignment (KB / KE / KA / KR, special stock W)
    ours: covered
    where: SO-45, inventory INV-45
  - sap: Third-party order and drop shipment (item category TAS)
    ours: covered
    where: SO-48, item_category THIRD_PARTY, purchasing
  - sap: Make-to-order and sales order stock (special stock E)
    ours: deferred
    where: "-"
    milestone: M7
    why: stock produced for one order line needs production orders and their costing (M7 Make & sell); a stocked or third-party line covers buy-to-sell today
  - sap: Tax determination on the order
    ours: covered
    where: SO-02, SO-40 (tax module, by the ship-to for goods)
  - sap: Cash sales and rush orders (BV, SO)
    ours: covered
    where: SO-44
  - sap: Catch weight in sales (parallel unit at goods issue and billing)
    ours: deferred
    where: "deferred: catch_weight"
    milestone: M7
    why: designed, columns reserved; catch weight changes purchasing, sales-order and invoicing together for weighed goods (an industry need SAP first shipped as IS-CWM); off until M7
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
