# Tax (VAT) — module spec (generated from modules/tax/module.yaml)
# A starting vocabulary for phase 2: correct it with the customer, then write ERP_TAX.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 tax): 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 tax; (2) SHOW the customer the diagram — `erp-compose process --module tax --playbook <playbook>` for a brick with playbooks (hr), else `erp-compose bpmn --from ERP_TAX.md --out processes/tax.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 tax  (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 tax
  repos:
    - name: erp-brick-tax
      role: brick
      tag: v0.2.2
      clone: git clone --depth 1 --branch v0.2.2 https://git.dodil.io/dodil/erp-brick-tax.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 tax` 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>-tax
    version: 0.1.0
    tier: 1
    bricks:
      - { name: tax, brick: "brick_tax.application.use_cases:TAX", version: 0.2.2 }
    # capabilities: omit to let each capability's only provider be used; a capability no brick
    # provides becomes a manual task. Map one only to choose between two providers.
  test_composition_py: |
    """The composition boots, its bricks answer through HTTP together, and a signed-in caller can read each one."""
    import inspect
    import pathlib
    from contextlib import ExitStack

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

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


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

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

        with ExitStack() as st:
            app = stage(Catalogue("t", compose=comp, roles=None), st, lambda name: engine).app
            assert anyio.run(get, app, "/healthz").status_code == 200
            for m in comp.members:
                reads = [u for u in m.brick.use_cases if u.kind == "query" and u.method == "GET" and u.tool
                         and not u.path_params and all(d is not inspect.Parameter.empty for _, _, d in u.inputs)]
                assert reads, f"{m.name}: no plain read use case to call"
                # The first plain read may refuse an empty question (activity's GET /contacts wants a bp_id or an
                # email: 422). A refusal is the use case answering; a 5xx is the composition broken. So: no read
                # may 5xx, and at least one must answer 200.
                answers = []
                for u in reads:
                    r = anyio.run(get, app, f"/{m.name}{u.path}")
                    assert r.status_code < 500, f"{m.name} {u.path}: {r.status_code} {r.text[:200]}"
                    answers.append(f"{u.path} {r.status_code}")
                    if r.status_code == 200:
                        break
                else:
                    raise AssertionError(f"{m.name}: no plain read answered 200 ({', '.join(answers)})")
id: tax
name: Tax (VAT)
short: Tax
version: 7
maturity: tested
summary: "The right VAT on every quote, order and invoice without anyone choosing a rate: standard, reduced, zero, exempt and reverse charge worked out from what you sell and who you sell it to, rounded the way HMRC allows, and frozen on the invoice so a rate change never rewrites what a customer received."
decisions:
  - decided: this module owns tax_code (sole writer, shared.yaml keys.tax_code); the ledger only maps each code to an account
    by: Seemo, DODIL (reference customer)
    date: 2026-10-18
  - decided: the DEFAULT rounding is per line, to the nearest penny (VAT Notice 700 para 17.5.1); the per-invoice round-down (17.5) stays a setting
    by: Seemo, DODIL (reference customer)
    date: 2026-10-18
  - decided: "the VAT-number check against HMRC (TAX-13) is deferred to M2: no check step in the M1 process; the AI name comparison stays listed in ai_steps as deferred"
    by: Seemo, DODIL (reference customer)
    date: 2026-10-18
  - decided: the UK seed pack is S 20%, R 5%, Z, E, OS, RC, NV (TAX-02)
    by: Seemo, DODIL (reference customer)
    date: 2026-10-18
  - proposed: "v4: the VAT-number check (TAX-13) is designed now and runs before a reverse-charge or overseas treatment is used; this supersedes the 2026-10-18 deferral to M2 once re-signed"
    status: for the SAP full-scope re-sign (2026-10-22)
  - proposed: "v4: the VAT return is prepared by the tax admin and submitted by a person who makes HMRC's declaration; a second person submits by default where the business has more than one (vat_return_needs_second_person, owner's control)"
    status: for the SAP full-scope re-sign (2026-10-22)
  - proposed: "v4: statutory thresholds and rates (cash accounting and flat-rate limits, the error-correction threshold, CIS rates, partial-exemption de minimis, Intrastat thresholds) are dated rows of the UK pack (tax_statutory), never constants in code"
    status: for the SAP full-scope re-sign (2026-10-22)
facets:
  domain: finance
  industries:
    - any
  customer_words:
    - VAT
    - the right tax on invoices
    - reverse charge
    - zero-rated exports
    - we're not VAT registered yet
    - the VAT rate changed
    - file our VAT return
    - Making Tax Digital
    - check a customer's VAT number
    - CIS deductions
    - bad debt relief
    - flat rate scheme
    - cash accounting
    - postponed import VAT
    - EC sales list
  replaces:
    - a VAT column typed by hand
    - the tax settings of the accounting package
    - Odoo taxes and fiscal positions
    - bridging software for MTD
    - a CIS spreadsheet
  pillars:
    - sql
  first_module_fit: foundation
  depends_on:
    - module: business-partner
      why: a customer's tax treatment and VAT number belong to the party, by bp_id
      required: recommended
    - module: product
      why: a line's tax category comes from its product
      required: recommended
    - module: gl
      why: the account each tax code posts to, and the sterling rate for a foreign-currency VAT total
      required: optional
    - module: payments
      why: the payment dates cash accounting taxes on, receipts after a bad debt claim, the CIS a contractor customer deducted (v4)
      required: optional
    - module: purchasing
      why: the CIS deduction on a subcontractor's payment, import entries, supplier payments under cash accounting (v4)
      required: optional
    - module: ar
      why: invoices written off for bad debt relief; issue and void ask whether a tax point is in a filed return (v4)
      required: optional
  feeds:
    - crm
    - sales-order
    - ar
    - purchasing
    - gl
    - payments
  owns_master_data:
    - tax_code
    - tax_category
  references_master_data:
    - business_partner
    - product
    - fx_rate
actors:
  - id: tax_admin
    name: Whoever is responsible for VAT (the owner, the bookkeeper, the accountant)
    does: records the VAT registration, keeps tax codes, rates, categories, treatments and the rules that join them
    sees: everything
    permissions:
      - tax:code:read
      - tax:code:write
      - tax:code:approve
      - tax:category:write
      - tax:registration:write
      - tax:party_tax:write
      - tax:document_tax:approve_override
      - tax:settings:write
      - tax:vat_return:read
      - tax:vat_return:prepare
      - tax:vat_return:submit
      - tax:vat_adjustment:write
      - tax:bad_debt:claim
      - tax:cis:write
      - tax:cis_return:submit
      - tax:trade_declaration:write
      - tax:import_vat:write
      - tax:partial_exemption:write
  - id: owner
    name: The owner or a finance controller
    does: sets the controls on whoever keeps VAT (whether a rate, rule or registration change waits for a second person, who approves an override that lowers tax, the business time zone)
    sees: everything
    permissions:
      - tax:code:read
      - tax:code:approve
      - tax:settings:controls
      - tax:hmrc:connect
      - tax:vat_return:read
      - tax:vat_return:submit
      - tax:cis_return:submit
    note: "v4: the owner also connects the business to HMRC (TAX-26) and may submit a VAT or CIS return; submitting is a legal declaration a person makes, never a service client"
  - id: biller
    name: Whoever raises orders and invoices
    does: sees the tax worked out on a document, records a customer's VAT number, overrides a line's code with a reason
    sees: tax codes, a document's tax
    permissions:
      - tax:code:read
      - tax:party_tax:write
      - tax:document_tax:override
  - id: system
    name: The system
    does: loads the country's codes, determines and computes tax for a document in its direction (sale or purchase), suggests a code where no rule covers a line, checks its contents, freezes it at issue, runs the one-off Odoo migration; v4 - reads HMRC obligations, liabilities and payments, checks VAT numbers, answers whether a tax point is filed, computes a CIS deduction and records one suffered, records import entries, finds bad debts eligible for relief
    sees: everything, through its own service account (one service client per calling brick, each with only its exact grants)
    permissions:
      - tax:code:read
      - tax:code:seed
      - tax:document_tax:compute
      - tax:document_tax:suggest
      - tax:history:import
      - tax:migration:read
      - tax:obligation:sync
      - tax:vat_number:check
      - tax:tax_point:read
      - tax:cis:deduct
      - tax:cis:record_suffered
      - tax:import_vat:record
      - tax:bad_debt:suggest
      - tax:cis:read
stories:
  - id: TAX-01
    kind: person
    actor: tax_admin
    story: As the person responsible for VAT, I want to record whether and from when we are VAT registered, so that we charge VAT exactly when we must and never before.
    given: a business not registered for VAT
    when: I record registration number GB123456789 from 2027-01-01
    then: 'documents with a tax point before 2027-01-01 charge no VAT and are not titled "VAT invoice"; from that date the rules apply and the number prints on every VAT invoice; registration with no number is refused, and so is one from today or earlier (documents already used "not registered" for those days): the readiness answers {gate: starts_after_today, met: false, reason: "a registration starts tomorrow at the earliest", fix: "Tax settings > Registration"}'
    screen: Tax settings
    path:
      process: tax.registration
      choices: {}
    reference: not built
  - id: TAX-02
    kind: person
    actor: tax_admin
    story: As the tax admin, I want the UK codes ready on day one, so that I am correcting a list rather than building one.
    given: a new installation for a UK business
    when: I open the tax codes
    then: "the UK pack is there: S standard 20%, R reduced 5%, Z zero 0%, E exempt, OS outside the scope, RC domestic reverse charge (VAT due 20%, charged 0%), NV no VAT (not registered); each with its treatment and its wording on the document; I can add, rename or retire a code, never delete one a document used"
    screen: Tax codes
    path:
      process: tax.tax_code
      choices: {}
    reference: not built
  - id: TAX-03
    kind: person
    actor: tax_admin
    story: As the tax admin, I want to schedule a rate change from a date, so that the change happens at midnight without anyone editing invoices.
    given: code S at 20% from 2011-01-04
    when: I add 21% from 2027-04-01
    then: a tax point on 2027-03-31 charges 20%, on 2027-04-01 21%; documents already issued are unchanged; a second rate for the same code and date is refused, and so is a rate from today or earlier; the 21% row may be withdrawn until 2027-04-01, after which a correction is a new row from tomorrow, never an edit; where the owner's control asks for it, the change waits for a second person's approval
    screen: Tax codes
    reference: not built
  - id: TAX-04
    kind: person
    actor: tax_admin
    story: As the tax admin, I want rules that pick the code from what is sold and who buys it, so that nobody chooses a rate on an invoice.
    given: "rules: (standard, uk_business) -> S; (standard, overseas_business, services) -> OS; (construction_service, uk_cis_contractor) -> RC; (reduced, any) -> R"
    when: a line of category standard is added for a UK business, and the same line for an overseas business buying services
    then: 'S at 20% for the first, OS with no VAT for the second, each line naming the rule that chose it; a pair no rule covers is refused with "no tax rule for (category, treatment)" rather than defaulting to 0%; a rule is a dated row: a new rule for a pair no rule covers yet may start today, a change to a covered pair starts after today'
    screen: Tax rules
    reference: not built
    customer_varies: which categories and treatments exist; most UK service businesses need four rules
  - id: TAX-05
    kind: person
    actor: biller
    story: As the biller, I want to record a customer's VAT treatment and number once, so that every document for them is taxed the same way.
    given: a customer with bp_id 7311 and no treatment
    when: I set treatment uk_business with VAT number GB987654321
    then: their documents are determined from the treatment valid on each tax point; the first treatment of a customer holds from the start (no document could issue without one); a change is a new row from tomorrow and applies to documents not yet issued with a tax point from then; treatments that need a VAT number (reverse charge, overseas business) refuse to save without one
    screen: Customer tax
    reference: not built
  - id: TAX-06
    kind: person
    actor: biller
    story: As the biller, I want to override a line's tax code with a reason, so that an unusual supply is handled without a new rule, and the override is visible.
    given: a draft invoice line determined as S
    when: I change it to Z with the reason "export of goods, proof of export held"
    then: the line shows Z, the reason and who changed it; where the override lowers the tax, it waits for approval by a holder of tax:document_tax:approve_override who is not me (unless the owner's control allows self-approval with a reason) before the document can issue
    screen: Document tax
    reference: not built
  - id: TAX-07
    kind: person
    actor: tax_admin
    story: As the tax admin, I want to choose how VAT is rounded, from the methods HMRC allows, so that our invoices match what we file.
    given: three lines of 10.03 at 20% (VAT 2.006 each, 6.018 in all)
    when: the invoice is computed under each method
    then: "per_invoice_round_down: VAT 6.01 (para 17.5); per_line_nearest: 2.01 x 3 = 6.03 (17.5.1); per_line_down_0_1p: 2.006 x 3 = 6.018, total rounded down to 6.01 (17.5.1); a retail setting refuses both round-down methods (17.6); net + VAT = total every time (30.09 + 6.01 = 36.10, or 30.09 + 6.03 = 36.12)"
    screen: Tax settings
    reference: not built
  - id: TAX-08
    kind: person
    actor: tax_admin
    story: As the tax admin, I want prices that include VAT to be handled, so that a consumer price of 12.00 is 10.00 plus 2.00 on the invoice.
    given: a price list with prices including VAT and a line at 12.00 under S
    when: the document's tax is computed
    then: net 10.00, VAT 2.00, total 12.00; the gross stays the price the customer was shown
    screen: Document tax
    reference: not built
  - id: TAX-09
    kind: person
    actor: biller
    story: As the biller, I want to accept or reject the code the AI suggests for a line no rule covers, so that an unusual line is taxed by a person's decision with the reason kept.
    given: a draft invoice line "on-site training, Dublin office" with no product, and ai_suggest_code in suggest mode
    when: the AI suggests OS with "services to an overseas business are outside the scope (VAT Notice 741A)" and I accept it
    then: the line takes OS, recorded as an override with the reason, the suggestion, its confidence, the model and me as the person who accepted; rejecting leaves the line refused until I choose a code; an accepted code that lowers tax below the category's standard code waits for approval as in TAX-06; nothing is applied without a person
    screen: Document tax
    reference: not built
  - id: TAX-14
    kind: person
    actor: owner
    story: As the owner, I want to set the controls on whoever keeps VAT, so that the person who changes a rate or lowers a line's tax cannot also waive the check on it.
    given: a tax admin who is also the biller
    when: I set tax_changes_need_second_person true and the business time zone Europe/London
    then: a rate, rule or registration change waits for a second holder of tax:code:approve; "today" is the date in Europe/London; a tax admin holding tax:settings:write is refused on these controls
    screen: Tax settings
    reference: not built
  - id: TAX-10
    kind: system
    actor: system
    trigger: when a document's lines, customer or tax point change (in the same request)
    story: The system determines each line's code and computes the document's tax, so that the tax is never typed.
    given: an order with lines in S and Z for a UK business, tax point 2026-11-20
    when: it is computed
    then: per line code, rate and VAT; a per-rate summary (one row per code, net and VAT, zero and exempt as separate totals, para 16.5); the total; computing twice gives the same answer
    reference: not built
  - id: TAX-11
    kind: system
    actor: system
    trigger: when the document issues
    story: The system freezes the tax on the document at issue, so that it is the tax the customer received forever.
    given: an invoice computed at 20%, and a rate change to 21% scheduled for the day after its tax point
    when: it issues, and is read after the rate change
    then: 'it still shows 20%; recomputing an issued document is refused ("issued: credit it instead")'
    reference: not built
  - id: TAX-12
    kind: system
    actor: system
    trigger: before a document issues
    story: The system checks the document carries everything a VAT invoice must show, so that an incomplete invoice never leaves.
    given: a VAT-registered business and a draft with no customer address
    when: issue is asked
    then: "refused with the unmet readiness gates, each {gate, met, reason, fix}, one per absent item from para 16.3.1 (here {gate: customer_address, met: false, reason: \"a VAT invoice shows the customer's address (VAT Notice 700 para 16.3.1)\", fix: \"the customer's address on the business partner\"}); a business that is not registered is checked for the opposite (no VAT number, not titled \"VAT invoice\")"
    reference: not built
  - id: TAX-13
    kind: system
    actor: system
    trigger: when a reverse-charge or overseas-business treatment is saved, and before such a document issues (v4; was deferred to M2)
    story: The system checks the customer's VAT number with HMRC, so that a reverse charge is not applied to someone who is not registered.
    given: treatment uk_cis_contractor with VAT number GB987654321, our own VRN 123456789
    when: the number is checked (HMRC Check a UK VAT number API v2.0, GET /organisations/vat/check-vat-number/lookup/987654321/123456789)
    then: "the result (valid, invalid, could_not_check), the name and address HMRC holds, HMRC's consultation number and the date are stored on the treatment row (checked_on, check_result, check_ref); \"invalid\" refuses the reverse charge with {gate: vat_number_valid, met: false, reason: \"HMRC has no registration for GB987654321\", fix: \"Customer tax: correct the number, or a consumer treatment\"}; \"could not check\" (HMRC down, a non-GB number) answers {gate: vat_number_valid, met: false} with fix \"a person confirms the number\" and a tax admin may confirm it with a reason; a check older than vat_number_check_days (default 90) is re-run before the next reverse-charge document issues; the AI name comparison (check_vat_number) flags a name that differs from the partner's, as a suggestion only"
    reference: not built
  - id: TAX-15
    kind: system
    actor: system
    trigger: once, at cutover from Odoo, after the customer has answered migration.odoo.door
    story: The system loads the customer's Odoo taxes, fiscal positions and customer VAT data as this module's first rows, so that the first invoice after cutover is taxed exactly as Odoo would have taxed it.
    given: an Odoo company with sale taxes 20% S, 0% Z, Exempt, a reverse-charge tax and the fiscal positions "UK", "EU B2B" and "Rest of world"
    when: the migration runs, and runs again
    then: tax codes, rates, treatments, rules and customer treatments exist as first rows with the dates the customer gave at the door, the purchase taxes (type_tax_use = purchase) as purchase codes and rules (v3); every row in migration.odoo.reconcile is equal or explained; the second run changes nothing; no issued document's tax is recomputed
    reference: not built
  - id: TAX-23
    kind: integration
    actor: system
    trigger: when purchasing records or changes a supplier bill or credit (v3)
    story: Purchasing asks this module for the input VAT on a bill, with the supplier's treatment and the purchase rules, so that VAT reclaimed is never typed.
    given: a UK VAT-registered supplier (treatment uk_business, its tax_party row); a bill dated 2026-11-20 with a standard-rated goods line of 1,000.00 and a business-entertainment line of 100.00
    when: "purchasing calls POST /documents/compute with direction: purchase"
    then: "the rules are read for (category, the SUPPLIER's treatment, supply, direction purchase): the goods line takes the input code at 20% with VAT 200.00 reclaimable; the entertainment line takes the blocked input code with VAT 20.00 non-reclaimable (it is a cost, not a reclaim); totals carry vat, vat_reclaimable 200.00 and vat_non_reclaimable 20.00; a sale-direction rule is never used for a purchase, and a pair with no purchase rule is refused (never 0%)"
    owner: tax
    reference: not built
  - id: TAX-24
    kind: integration
    actor: system
    trigger: when a supplier bill is about to be approved (v3)
    story: Purchasing asks this module whether a bill is a valid VAT invoice from the supplier, so that input VAT is reclaimed only on one.
    given: a bill from Acme Supplies Ltd with no VAT number on it, and our own name as the customer
    when: "purchasing calls POST /documents/{document_ref}/check-contents with direction: purchase"
    then: "the content gates check the SUPPLIER's name, address and VAT number (and the supplier's invoice number and date, contents.invoice_number and contents.issue_date) and our name as the customer (contents.customer_name; v6: the request carries all of them, purchasing PUR-28): supplier_vat_number is unmet (\"the bill shows no VAT number for Acme Supplies Ltd: input VAT cannot be reclaimed on it\"); with direction sale the gates still check OUR name and VAT number as v2"
    owner: tax
    reference: not built
  - id: TAX-25
    kind: integration
    actor: system
    trigger: when a purchase from an overseas supplier of services is computed (v3)
    story: A reverse-charged purchase is self-accounted both sides, so that the return shows the output and the input VAT and the business pays nothing net where it may reclaim.
    given: an overseas supplier (treatment overseas_business) billing consultancy services of 500.00
    when: "it is computed with direction: purchase"
    then: "the line takes the purchase reverse-charge code: charged 0.00, VAT due 100.00 accounted as output (its output reporting box) and 100.00 as input VAT reclaimable (its input box), so the net cost of VAT is 0.00; non-reclaimable where the code's reclaimable_pct is 0"
    owner: tax
    reference: not built
  - id: TAX-20
    kind: integration
    actor: system
    trigger: when a quote, order, invoice or credit note is priced
    story: Every selling document asks this module for its tax rather than computing its own.
    given: a sales order with three lines
    when: sales-order calls compute(lines, bp_id, tax_point, currency)
    then: it receives per line code, rate and VAT, the per-rate summary and the total, with the method that rounded them; it stores the answer as its own copy
    owner: tax
    reference: not built
  - id: TAX-21
    kind: integration
    actor: system
    trigger: when an invoice or credit note posts to the ledger
    story: The ledger finds the VAT account for each code from its account map, so that the VAT liability per code is in the books.
    given: an invoice with S 200.00 and RC 0.00 (VAT due 100.00 by the customer)
    when: invoicing posts
    then: output VAT 200.00 credits the S account; RC posts no VAT and is recorded for the return with its net; journal ids derived as the ledger requires
    owner: gl
    reference: not built
  - id: TAX-22
    kind: integration
    actor: system
    trigger: when an invoice is in a foreign currency
    story: The VAT total is also shown in sterling at the rate the business uses, as the VAT guide requires.
    given: an invoice in EUR with VAT 200.00 EUR and the ledger's rate for the tax point
    when: tax is computed
    then: the VAT total in GBP is computed at that rate and frozen with the document (para 16.4); without the ledger, the rate is entered on the document
    owner: gl
    reference: not built
  - id: TAX-26
    kind: person
    actor: owner
    story: As the owner, I want to connect our VAT registration to HMRC once, so that obligations are read and returns are filed from here without bridging software.
    given: registration GB123456789 recorded and no HMRC connection
    when: I choose Connect to HMRC and sign in to HMRC's Government Gateway as our business, granting read:vat and write:vat
    then: "the connection is recorded (vrn, scopes, authorised_by, authorised_at, expires_at: HMRC's grant lasts 18 months); the tokens are kept in the platform's secret store, never in a row or a log; until it exists every return transition answers {gate: hmrc_connected, met: false, reason: \"this business is not connected to HMRC\", fix: \"Tax settings > HMRC connection (the owner)\"}; 30 days before expiry the owner is told to reconnect; hmrc_environment (sandbox | production, an owner's control) decides which HMRC base URL is called"
    screen: Tax settings
    path:
      process: tax.vat_return
      choices: {}
    reference: not built
  - id: TAX-27
    kind: system
    actor: system
    trigger: daily, and when the VAT returns screen opens
    story: The system reads our VAT obligations from HMRC, so that the periods to file and their deadlines are HMRC's, never typed.
    given: a connection for VRN 123456789, quarterly stagger ending March, June, September, December
    when: GET /organisations/vat/123456789/obligations?from=2026-01-01&to=2027-12-31 runs, twice
    then: "one vat_obligation row per periodKey (e.g. \"26AD\": 2026-10-01 to 2026-12-31, due 2027-02-07, status O); a period HMRC reports as F (filed, even if filed elsewhere) is marked filed with its received date; the second run changes nothing; dates are HMRC's, never computed here; an HMRC error is recorded with its code and retried next day"
    reference: not built
  - id: TAX-28
    kind: person
    actor: tax_admin
    story: As the tax admin, I want the VAT return for an open period prepared from what we invoiced and were billed, so that every box is a sum of frozen document tax I can drill into.
    given: obligation 26AD (2026-10-01 to 2026-12-31); frozen sale documents with output VAT 41,200.00 on net 206,000.00 (of which RC construction sales net 12,000.00 with no VAT); purchase documents with reclaimable input VAT 9,850.00 on net 49,250.00, non-reclaimable 140.00; one supplier bill dated 2026-09-28 received late and not in any return; NI dispatches to the EU net 3,000.00
    when: I prepare the return
    then: "box 1 = 41,200.00 output VAT plus reverse-charge and postponed-import output VAT; box 2 = VAT on NI acquisitions of goods from the EU; box 3 = 1 + 2; box 4 = reclaimable input VAT (incl. reverse-charge and postponed-import input, bad debt relief claimed); box 5 = |3 - 4|; boxes 6-9 the net values in whole pounds (pence dropped, HMRC's rule): 6 sales incl. RC net and zero-rated, 7 purchases, 8 NI goods to the EU, 9 NI goods from the EU; each document's tax enters ONE return only (a vat_return_entry row keyed [document_ref, tax_code], claimed with a plain INSERT, so two concurrent preparations never count it twice); the late bill dated 2026-09-28 enters this return (input VAT is claimed in the period the VAT invoice is held); every box drills to its entries; preparing again replaces only this draft's entries; the return is draft until locked"
    screen: VAT returns
    reference: not built
  - id: TAX-29
    kind: person
    actor: tax_admin
    story: As the tax admin, I want to correct an error from an earlier period on this return when HMRC allows it, and be stopped when it must be notified instead, so that corrections follow VAT Notice 700/45.
    given: a draft return with box 6 of 400,000; an under-declared output VAT of 3,200.00 found for period 26AB
    when: I record the adjustment with the reason and the period it corrects, and then try one of 12,000.00
    then: 'the 3,200.00 adds to box 1 with its reason and period (net errors within 10,000.00, or within 50,000.00 and 1% of box 6, are corrected on the next return; the thresholds are dated tax_statutory rows); the 12,000.00 exceeds both (1% of 400,000 is 4,000) and is refused with {gate: within_error_threshold, met: false, reason: "net errors of 12,000.00 exceed what may be corrected on a return (Notice 700/45)", fix: "notify HMRC on form VAT652 and record the notice"}; a notice records the reference, the date sent and the periods; an error older than four years is refused (the four-year cap)'
    screen: VAT returns
    reference: not built
  - id: TAX-30
    kind: person
    actor: owner
    story: As the person who signs off VAT, I want to submit the locked return to HMRC with the legal declaration, so that it is filed digitally and the receipt is kept.
    given: return 26AD locked by the tax admin; vat_return_needs_second_person true; the HMRC connection valid
    when: I read the boxes, tick "When you submit this VAT information you are making a legal declaration that the information is true and complete. A false declaration can result in prosecution." and submit
    then: "POST /organisations/vat/123456789/returns with {periodKey, vatDueSales, vatDueAcquisitions, totalVatDue, vatReclaimedCurrPeriod, netVatDue, totalValueSalesExVAT, totalValuePurchasesExVAT, totalValueGoodsSuppliedExVAT, totalAcquisitionsExVAT, finalised: true} and the fraud-prevention headers (TAX-31); HMRC's receipt (processingDate, formBundleNumber, paymentIndicator, chargeRefNumber) is stored and the return is submitted and immutable; the person who locked it may not submit it while the control is on (the same identity by email OR sub is refused); submitting a return whose obligation HMRC already shows F is refused (HMRC's DUPLICATE_SUBMISSION is recorded, never retried); a timeout leaves it submitting, and a re-read of GET /returns/{periodKey} settles whether HMRC has it before any retry"
    screen: VAT returns
    reference: not built
  - id: TAX-31
    kind: system
    actor: system
    trigger: on every call to an HMRC API made for a person (submit, view a return, liabilities, payments)
    story: The system sends HMRC's fraud-prevention headers from the person's own session, so that the submission meets HMRC's terms of use.
    given: a submission from a browser session of the owner
    when: the call is built
    then: "connection method WEB_APP_VIA_SERVER with Gov-Client-Connection-Method, Gov-Client-Browser-JS-User-Agent, Gov-Client-Device-ID, Gov-Client-Multi-Factor, Gov-Client-Public-IP, Gov-Client-Public-IP-Timestamp, Gov-Client-Public-Port, Gov-Client-Screens, Gov-Client-Timezone, Gov-Client-User-IDs, Gov-Client-Window-Size, Gov-Vendor-Forwarded, Gov-Vendor-License-IDs, Gov-Vendor-Product-Name, Gov-Vendor-Public-IP, Gov-Vendor-Version; a header the session cannot supply refuses the submission with {gate: fraud_headers_complete, met: false, reason: \"HMRC requires <header>\", fix: \"submit from the web screen, not a script\"}; the headers sent are kept with the submission for audit; the set is validated against HMRC's Test Fraud Prevention Headers API in sandbox before production is switched on"
    reference: not built
  - id: TAX-32
    kind: person
    actor: tax_admin
    story: As the tax admin, I want to see what we owe HMRC per period and what HMRC says we have paid, and the books to agree, so that a VAT payment is never missed or posted twice.
    given: return 26AD submitted with box 5 = 31,350.00 to pay, due 2027-02-07
    when: I open the liability view after HMRC has taken the direct debit
    then: "per period: the return's net VAT, HMRC's liabilities (GET /liabilities) and payments (GET /payments) as HMRC holds them, the outstanding amount and the due date (one month and seven days after the period end); on submission the settle journal posts to the ledger (each tax code's VAT against vat_control, journal id derived from the return), once; the HMRC payment itself is the bank line payments reconciles to vat_control (PAY-21); a difference between our box 5 and HMRC's liability is shown, never hidden"
    screen: VAT returns
    reference: not built
  - id: TAX-33
    kind: integration
    actor: system
    trigger: when ar issues or voids a document, or approves a credit note (the gates tax_point_open and void_policy)
    story: Invoicing asks this module whether a tax point falls in a VAT return already locked or filed, so that an issued invoice in a filed period is never voided or back-dated into it.
    given: return 26AC (2026-07-01 to 2026-09-30) submitted, 26AD draft
    when: ar calls GET /vat-returns/tax-point-status?date=2026-09-15, then ?date=2026-11-20
    then: "{date: 2026-09-15, period_key: 26AC, status: submitted, filed: true, gate: {gate: tax_point_open, met: false, reason: \"2026-09-15 is in VAT return 26AC, submitted 2026-11-04\", fix: \"credit it instead, or issue with today's tax point\"}}; for 2026-11-20 {period_key: 26AD, status: draft, filed: false, gate: {met: true}}; a locked (not yet submitted) return answers filed false with met false (reason \"return 26AD is locked for submission\"); a date in no obligation answers period_key null, met true (the answer is the L2C leftover's missing callee)"
    owner: tax
    reference: not built
  - id: TAX-34
    kind: person
    actor: tax_admin
    story: As the tax admin, I want to claim back the VAT on invoices a customer never paid, once the law allows, so that we do not pay HMRC VAT we never received.
    given: invoice INV-2026-0107 (net 1,000.00, VAT 200.00, total 1,200.00), supplied 2026-03-10, due 2026-04-09, VAT accounted in submitted return 26AA; 480.00 received; written off by invoicing on 2026-10-30 (AR-09); today 2026-11-02
    when: the system lists it as eligible and I claim it on return 26AD
    then: "relief = the VAT fraction of the unpaid consideration: (1,200.00 - 480.00) x 200/1,200 = 120.00, added to box 4 with the invoice named (bad_debt_claim keyed invoice_id, one claim per invoice); eligibility is each gate {gate, met, reason, fix}: six_months_passed (six months from the later of the due date and the supply date: 2026-10-09 here), written_off (an approved ar write-off or the receivable written off in the books), vat_accounted (the invoice's tax is in a submitted return), within_time_limit (four years and six months from that date), not_claimed; a claim for an invoice still inside six months is refused with its date"
    screen: VAT returns
    reference: not built
  - id: TAX-35
    kind: system
    actor: system
    trigger: when a return is prepared
    story: The system repays bad debt relief when the customer pays after all, so that the relief and the receipt never both stand.
    given: the claim of 120.00 on INV-2026-0107 in return 26AD; a receipt of 360.00 allocated to it on 2027-02-20 (payments)
    when: return 27AA is prepared
    then: the repayment 360.00 x 200/1,200 = 60.00 adds to box 1, naming the claim and the allocation; it is derived from payments' allocations dated after the claim (GET /allocations?invoice_ids=&from=), never typed; the same allocation is repaid once (an entry keyed [claim, allocation]); an undo of that allocation (PAY-06) reverses the repayment on the next return
    reference: not built
  - id: TAX-36
    kind: person
    actor: tax_admin
    story: As the tax admin of a small business on cash accounting, I want the return to tax what we were paid and what we paid, so that we never pay VAT before the customer pays us.
    given: registration with accounting_basis cash from 2027-01-01 (expected taxable turnover 900,000, within the 1,350,000 joining limit); invoice INV-2027-0012 (VAT 200.00) issued 2027-01-15 and paid 2027-04-03; a supplier bill (input VAT 50.00) paid 2027-03-20
    when: return 27AA (Jan-Mar) and 27AB (Apr-Jun) are prepared
    then: the invoice's VAT is in 27AB (the receipt date is the tax point for the return), the bill's input VAT in 27AA (the payment date); a part payment taxes the VAT fraction of what was received; read from payments' cash-basis route (receipts allocated in the period, by invoice) and purchasing's supplier payments; documents excluded from the scheme (an invoice payable more than six months ahead, an import) stay on the invoice basis; leaving the scheme (turnover above 1,600,000) brings every outstanding VAT into the return for the leaving period; the basis changes only from the start of a VAT period after today
    screen: VAT returns
    reference: not built
  - id: TAX-37
    kind: person
    actor: tax_admin
    story: As the tax admin of a business on the flat rate scheme, I want the VAT due computed as our flat rate of gross turnover, so that I file the right figure without a side spreadsheet.
    given: flat_rate from 2027-01-01 at 14.5% (sector "computer and IT consultancy"), first year of VAT registration (1% discount until 2027-12-31); quarter turnover including VAT 60,000.00; goods costs 300.00 (below 2% of turnover, so the limited cost trader test is applied); a laptop bought for 2,400.00 including VAT
    when: return 27AA is prepared
    then: "the limited cost trader test is a gate answered first: goods 300.00 are below 2% of 60,000.00 (1,200.00), so the limited cost trader rate 16.5% replaces the sector's 14.5%, less the first-year 1%: box 1 = 60,000.00 x 15.5% = 9,300.00; box 6 = the flat-rate turnover including VAT; box 4 holds only capital goods costing 2,000.00 or more including VAT (the laptop's 400.00); the sector, its rate and the thresholds are dated rows (tax_statutory, registration); joining needs expected taxable turnover at most 150,000 excluding VAT; turnover above 230,000 including VAT in a year answers {gate: flat_rate_eligible, met: false} on the next return"
    screen: VAT returns
    reference: not built
  - id: TAX-48
    kind: person
    actor: tax_admin
    story: As the tax admin of a partly exempt business, I want residual input VAT recovered at our provisional percentage each return and adjusted at the year end, so that we reclaim exactly what VAT Notice 706 allows.
    given: purchase input VAT attributed to taxable supplies 6,000.00, to exempt supplies 900.00, residual 3,000.00; last year's recovery 71%; partial exemption year ending 31 March
    when: each return is prepared, and the annual adjustment is run after the year ends
    then: "each return reclaims 6,000.00 + 71% of 3,000.00 = 8,130.00; the 900.00 exempt input VAT is reclaimed in full while the de minimis test holds (exempt input tax at most 625.00 a month on average and at most half of all input tax: test 1/2/3 of Notice 706 answered as gates); the annual adjustment recomputes the year's percentage (taxable supplies / all supplies, rounded UP to a whole percent while residual input tax averages at most 400,000 a month) and puts the difference on the first return after the year end; attribution (taxable | exempt | residual) is a property of the purchase tax code, so purchasing's lines carry it without a new field"
    screen: VAT returns
    reference: not built
  - id: TAX-49
    kind: person
    actor: tax_admin
    story: As the tax admin of a partly exempt business, I want input VAT on a building or a large computer system adjusted each year as our taxable use changes, so that the Capital Goods Scheme is applied without a spreadsheet.
    given: "a building bought 2026-06-01 with input VAT 100,000.00 (an item of 250,000.00 or more: ten intervals), first-year recovery 80%; year-two recovery 70%"
    when: the annual adjustment for year two is run
    then: the item is recorded once (capital_goods_item keyed item_ref) with its VAT, intervals (10 for land and buildings, 5 for computers of 50,000.00 or more, both tax_statutory rows) and first-interval percentage; year two adjusts (100,000.00 / 10) x (70% - 80%) = -1,000.00 onto the first return after the year end, as an adjustment entry naming the item and interval; each interval is adjusted once; a sale of the item in its adjustment period answers a gate asking for the disposal adjustment
    screen: VAT returns
    reference: not built
  - id: TAX-38
    kind: person
    actor: tax_admin
    story: As the contractor's tax admin, I want each subcontractor verified with HMRC before we pay them, so that the deduction rate is HMRC's, not a guess.
    given: a new subcontractor bp_id 8801, Bright Sparks Ltd, UTR 1234567890, company number 01234567, not paid in this or the last two tax years
    when: I verify them
    then: "the verification (HMRC CIS online verification through the HMRC connection, or the result a person read from HMRC's CIS service, entered with the verification number) stores status gross | net | unmatched, the rate 0 | 20 | 30 (dated tax_statutory rows), the verification number (V1234567890 and a suffix for unmatched) and the date; a payment to a subcontractor with no verification answers {gate: cis_verified, met: false, reason: \"Bright Sparks Ltd has not been verified with HMRC\", fix: \"CIS > Subcontractors > Verify\"}; one already paid in this or the previous two tax years needs none; a re-verification is a new dated row, never an edit"
    screen: CIS
    path:
      process: tax.cis_return
      choices: {}
    reference: not built
  - id: TAX-39
    kind: integration
    actor: system
    trigger: when purchasing approves a payment to a subcontractor (a run or a manual payment)
    story: Purchasing asks this module for the CIS deduction on a subcontractor's payment, so that the deduction is HMRC's rate on the labour only.
    given: subcontractor 8801 verified net (20%); a bill of labour 4,000.00, materials 1,000.00, VAT reverse-charged (0.00 charged)
    when: purchasing calls POST /cis/deductions with the payment
    then: deduction = 20% x (4,000.00 + 1,000.00 - 1,000.00 materials) = 800.00; purchasing pays 4,200.00 and books the 800.00 to the CIS liability; the deduction row is keyed [payment_ref, bp_id] in the tax month (6th to 5th) of the payment date, so a retry adds nothing; materials above the bill's own figure are refused; an unmatched subcontractor is deducted at 30%; a gross one at 0% with the row still recorded for the return
    owner: tax
    reference: not built
  - id: TAX-40
    kind: person
    actor: tax_admin
    story: As the contractor's tax admin, I want the monthly CIS return prepared from the deductions and the statements sent to each subcontractor, so that the CIS300 is filed by the 19th.
    given: tax month 6 October to 5 November 2026 with three payments to two subcontractors
    when: I prepare the return, a person confirms the declarations (employment status, verification) and submits it
    then: a CIS300 per tax month with each subcontractor's name, UTR, verification number, gross paid (excl. VAT), materials and deduction; a nil month is a nil return unless a person records inactivity; submission goes through HMRC's CIS online filing over the HMRC connection, the submission receipt kept, by the 19th (overdue answers a gate with the penalty warning); a payment and deduction statement per subcontractor is produced and sent (due by the 19th); the deductions total is what the business pays HMRC by the 22nd with its PAYE, shown in the liability view
    screen: CIS
    reference: not built
  - id: TAX-41
    kind: integration
    actor: system
    trigger: when payments records a receipt from a contractor customer that deducted CIS (PAY-45)
    story: Payments tells this module what a contractor deducted from our invoice under CIS, so that the deduction suffered is claimed back and never lost.
    given: our invoice of labour 2,000.00 to contractor bp_id 7311 (reverse charge, no VAT charged); they pay 1,600.00 and send a payment and deduction statement showing 400.00 deducted for tax month ending 2026-12-05
    when: payments calls POST /cis/suffered
    then: a cis_suffered row keyed [contractor bp_id, statement_ref] with the tax month, gross, materials and deduction; the CIS view sums what was suffered per tax month and year, for the PAYE offset (a limited company's employer payment summary) or self assessment; a deduction above 30% of the labour named is refused; the same statement recorded twice adds nothing
    owner: tax
    reference: not built
  - id: TAX-42
    kind: person
    actor: tax_admin
    story: As the tax admin of a business moving goods from Northern Ireland to EU customers, I want the EC sales list prepared from our invoices, so that it matches box 8.
    given: "registration with ni_goods true (XI prefix); in November, invoices of goods to two EU VAT-registered customers: IE1234567T net 12,000.00 and FR12345678901 net 3,000.00, one credit note of 500.00"
    when: I prepare the November EC sales list and record it submitted
    then: one line per customer VAT number with the net value in whole pounds (IE 12,000; FR 2,500 after the credit) and indicator 0 (goods) or 2 (triangulation); the total ties to box 8 of the return for the months it covers (a difference is a gate, never silent); monthly, or quarterly while goods stay below 35,000 a quarter for the current and four previous quarters (dated tax_statutory row); the file is HMRC's bulk-upload CSV for the person to upload, and the person records the submission reference and date (HMRC offers no API for it); an amendment is a new version of the declaration
    screen: Trade declarations
    reference: not built
  - id: TAX-43
    kind: person
    actor: tax_admin
    story: As the tax admin of a Northern Ireland business above the Intrastat threshold, I want the monthly supplementary declaration built from our goods movements with the EU, so that it is filed without retyping.
    given: NI dispatches to the EU above 250,000 a year (dispatches threshold) and arrivals below 500,000 (arrivals threshold), both dated tax_statutory rows
    when: I prepare November's dispatches declaration
    then: "one line per (commodity code, partner country, nature of transaction, country of origin) with value in whole pounds, net mass in kg and supplementary units where the commodity needs them, partner VAT number; read from ar's issued invoice lines to EU customers with goods (net value, unit_code) and product's commodity code and net weight; a line whose product has no commodity code is a gate {gate: commodity_code, met: false, fix: \"Product > the product > Trade\"}; arrivals are only declared once the arrivals threshold is passed; the file is HMRC's upload format and the person records the submission"
    screen: Trade declarations
    reference: not built
  - id: TAX-44
    kind: integration
    actor: system
    trigger: when purchasing records an import (a customs entry on a supplier bill or a freight agent's invoice)
    story: Purchasing records each import entry here with how its import VAT was accounted, so that postponed import VAT is self-accounted on the return and import VAT paid is reclaimed only with evidence.
    given: an import from China, customs value 10,000.00, MRN 26GB12345678901234, postponed VAT accounting chosen; a second import where the freight agent paid 2,000.00 import VAT
    when: purchasing calls POST /imports
    then: "the first is an import_entry with code PVA (rate 20%, charged 0): output 2,000.00 in box 1, input 2,000.00 in box 4 (by the code's reclaimable_pct), value 10,000 in box 7; the second carries code IMPORT_PAID with its 2,000.00 reclaimable only once the monthly import VAT certificate (C79, or its CDS successor) lists the entry; an entry keyed by MRN is recorded once"
    owner: tax
    reference: not built
  - id: TAX-45
    kind: person
    actor: tax_admin
    story: As the tax admin, I want each month's postponed import VAT statement reconciled to our import entries, so that box 1 and box 4 carry exactly HMRC's figures.
    given: the November statement downloaded from the Customs Declaration Service with three entries (MRN, import VAT); our import entries hold two of them, one with a different amount
    when: I upload the statement
    then: "each statement line is matched by MRN: one matches, one differs (the difference shown with both amounts), one has no import entry; the statement is reconciled only when every line is matched or explained by a person with a reason; the return uses HMRC's figure for a line explained as HMRC's (an adjustment row naming the MRN); the statement file is kept as an object, read-only"
    screen: Import VAT
    reference: not built
  - id: TAX-46
    kind: person
    actor: tax_admin
    story: As the tax admin of a construction business, I want the reverse charge applied only where the customer is VAT- and CIS-registered and not an end user, and self-accounted when we buy such services, so that we never charge or omit VAT wrongly.
    given: customer 7400 (treatment uk_cis_contractor) gives written notice it is an end user; supplier 8801 (VAT- and CIS-registered) bills us specified construction services of 4,000.00
    when: I record the end-user notice on 7400 from tomorrow, and the supplier bill is computed with direction purchase
    then: "from that date 7400's construction lines take S at 20% (an end user or intermediary is outside the reverse charge), the notice kept with its date and reference; the purchase is self-accounted with code RC_PURCHASE: VAT 800.00 output (box 1) and input (box 4), net in box 7 and never in box 6; a supply whose reverse-charge services are 5% or less of its value may be taxed normally (the 5% disregard, a gate on the rule the tax admin confirms)"
    screen: Customer tax
    reference: not built
  - id: TAX-47
    kind: integration
    actor: system
    trigger: when ar or sales-order computes a line that reverses or deducts an earlier document (a deposit deduction, a credit-note correction, a settlement discount)
    story: A line pinned to an earlier frozen document takes that document's code and rate, so that a deduction or a correction carries the tax it reverses and tax accepts it.
    given: deposit invoice DEP-2026-0003 frozen with S 20% on 5,000.00; a final invoice deducting 2,000.00 of it on 2027-04-15, after S became 21%
    when: ar calls POST /documents/compute with a line {line_no 4, amount "-2000.00", pinned_from "<deposit invoice_id>", tax_code "S"}
    then: the line takes S at the deposit's frozen 20% (VAT -400.00), named "pinned to <invoice_id>"; it is never re-determined from category and treatment, so a deduction carries the deposit's category without the source sending one; a pinned code the earlier document does not carry is refused (gate pinned_code); the pinned amount may not exceed the earlier document's net for that code less what earlier pinned lines on issued documents already took (gate pinned_within_original, read from tax's own frozen rows)
    owner: tax
    reference: not built
  - id: TAX-50
    kind: integration
    actor: system
    trigger: when expenses checks a till receipt (EXP-18) or purchasing a small supplier invoice, before VAT is reclaimed on it
    story: A less detailed VAT invoice is accepted for what it is, so that VAT on a 9.60 GBP train-station coffee receipt is reclaimed without our company's name on it, and a receipt over the limit still needs a full invoice.
    given: a till receipt from a UK retailer for 9.60 GBP including VAT 1.60 at 20%, showing the retailer's name, address and VAT number, its receipt number, the date and a description; the setting simplified_invoice_threshold 250
    when: expenses calls POST /documents/exp:UK01-EXP-2026-00042:3/check-contents with direction purchase and no customer_name, then one with a 312.00 GBP receipt in the same form
    then: "the first is a less detailed invoice (VAT Notice 700 para 16.6.1; VAT Regulations 1995 reg. 16): the gates for the supplier's name, address and VAT number, the invoice number, the tax point, a description, the total including VAT and the rate per line are checked, customer_name and customer_address are not required, and ready is true with title less_detailed_invoice; the second (gross above 250.00) needs our name as the customer (gate customer_name unmet: \"a VAT invoice over 250.00 must show your company's name: ask the supplier for a full invoice\"); a sale-direction document is unchanged (its own simplified invoice rule); the threshold is in GBP and compared with the gross including VAT, in the document's currency converted at gl's rate on the tax point"
    owner: tax
    reference: not built
  - id: TAX-51
    kind: integration
    actor: system
    trigger: when a till or an order computes food and drink that is taxed by where it is consumed
    story: A line says whether it is eaten in or taken away, so that the rate is the one the law sets for that consumption and not a guess per product.
    given: "rules for DE: category food_hot with consumption eat_in 19% (DE-S) and takeaway 7% (DE-R) from 2026-01-01; category coffee with consumption any 19%; UK: hot food standard either way"
    when: pos computes receipt pos:R-7001 in Berlin with a currywurst eat_in, a currywurst takeaway and a coffee, sending each line's consumption
    then: "the eat-in line takes DE-S at 19%, the takeaway line DE-R at 7% and the coffee DE-S (a rule of consumption any covers both); a line of a category whose rules distinguish consumption and that sends none is refused (gate consumption_given: \"say whether it is eaten in or taken away\"), never defaulted; a line of a category with only any rules may omit it; consumption is part of the rule's key and of the frozen line"
    owner: tax
    reference: not built
  - id: TAX-52
    kind: integration
    actor: system
    trigger: when a register takes its offline snapshot (pos POS-30)
    story: A register reads the rates in force for the categories it sells, so that it can sell with the right VAT while offline and know when its snapshot goes stale.
    given: UK categories standard, zero, food_hot, food_cold; a rate change for food_hot scheduled for 2027-04-01
    when: pos calls GET /rates?country=GB&categories=standard,zero,food_hot,food_cold&on=2026-11-20
    then: one row per (category, consumption) with the tax_code, rate_pct and the rule's and the rate's validity in force on 2026-11-20 for the treatment of an anonymous buyer (walk_in_treatment_code, default uk_consumer); valid_until 2027-03-31 (the day before the next change of any answered row, or null), so the register refreshes before it; a category with no rule for the treatment is answered in missing and the register must not sell it offline; the receipt is still recomputed by POST /documents/compute at sync and the computed answer is the one kept
    owner: tax
    reference: not built
  - id: TAX-53
    kind: integration
    actor: system
    trigger: when the party on a document is not a business partner (a merchant on an expense receipt, an anonymous till sale)
    story: A document can be computed without a business partner when its treatment is named, so that a receipt from a merchant we will never buy from again is taxed by the same rules without creating a supplier.
    given: "an expense line: a hotel receipt from a UK VAT-registered merchant, treatment_code uk_business, no bp_id; a till sale with treatment_code uk_consumer, no bp_id"
    when: expenses and pos call POST /documents/compute without bp_id
    then: the rules are read for the named treatment exactly as for a party's (determine); the document records party null and the treatment used; without bp_id AND without treatment_code the call is refused (gate party_or_treatment, 422); with both, bp_id's treatment row wins and a different treatment_code is refused (gate treatment_matches_party)
    owner: tax
    reference: not built
processes:
  - key: tax_code
    pcf_id: 10929
    pcf_name: Maintain tax master data
    reference_names:
      - Tax master data
      - Taxes and fiscal positions
    brick: tax
  - key: document_tax
    pcf_id: 10766
    pcf_name: Process taxes
    reference_names:
      - Tax determination
    brick: tax
  - key: registration
    pcf_id: 10929
    pcf_name: Maintain tax master data
    reference_names:
      - VAT registration
    brick: tax
  - key: vat_return
    pcf_id: 10766
    pcf_name: Process taxes
    reference_names:
      - Advance return for tax on sales/purchases
      - Making Tax Digital VAT return
    brick: tax
  - key: cis_return
    pcf_id: 10766
    pcf_name: Process taxes
    reference_names:
      - Construction Industry Scheme
      - Withholding tax reporting
    brick: tax
  - key: trade_declaration
    pcf_id: 10766
    pcf_name: Process taxes
    reference_names:
      - EC sales list
      - Intrastat
    brick: tax
  - key: import_vat
    pcf_id: 10934
    pcf_name: Account for taxes
    reference_names:
      - Postponed import VAT
      - Import VAT
    brick: tax
workflows:
  - entity: registration
    states:
      - not_registered
      - registered
      - deregistered
    terminal:
      - deregistered
    transitions:
      - key: record_not_registered
        name: Record that we are not registered
        from: none
        to: not_registered
        by: tax_admin
        gate: "the first registration row (it may carry any date: nothing has used it)"
        effect: documents charge no VAT and are not titled VAT invoice
      - key: register
        name: Record our VAT registration
        from: not_registered
        to: registered
        by: tax_admin
        requires: vat_number
        gate: a VAT number in the GB format; effective_from after today; a second person's approval where tax_changes_need_second_person
        effect: tax points from that date charge VAT
      - key: record_registered
        name: Record an existing registration
        from: none
        to: registered
        by: tax_admin
        requires: vat_number
        gate: "the first registration row (a new installation or the migration): it carries the date HMRC registered us"
      - key: change_vat_scheme
        name: Change the accounting basis or the flat rate scheme (v4)
        from: registered
        to: registered
        by: tax_admin
        requires: scheme
        gate: "from the first day of a VAT period after today; eligibility from the dated tax_statutory limits (cash accounting: expected taxable turnover at most the joining limit; flat rate: at most its joining limit, a sector and its rate); a second person's approval where tax_changes_need_second_person"
        effect: "a new registration row: accounting_basis invoice | cash, flat_rate with sector, rate and first_year_until; returns of later periods compute under it (TAX-36, TAX-37)"
      - key: deregister
        name: Record deregistration
        from: registered
        to: deregistered
        by: tax_admin
        requires: effective_date
        approval: true
        gate: effective_date after today; the approver is not the author
        effect: tax points from that date charge no VAT
  - entity: tax_code
    states:
      - draft
      - active
      - retired
    terminal:
      - retired
    transitions:
      - key: load_pack
        name: Load the country's codes
        from: none
        to: draft
        by: system
        gate: a new installation with no codes, and no migration planned
        effect: "the UK pack: S, R, Z, E, OS, RC, NV, with their rates from their real dates"
      - key: add_code
        name: Add a tax code
        from: none
        to: draft
        by: tax_admin
        gate: the code is not in use
      - key: activate_code
        name: Activate the code
        from: draft
        to: active
        by: tax_admin
        gate: "a treatment, a first rate (any date: no document has used the code), and the document wording where the treatment needs one (reverse charge)"
      - key: schedule_rate
        name: Schedule a rate change
        from: active
        to: active
        by: tax_admin
        gate: valid_from after today; no other rate for the code on that date; a second person's approval where tax_changes_need_second_person
        effect: a dated rate row; issued documents unchanged
      - key: withdraw_rate
        name: Withdraw a rate not yet in effect
        from: active
        to: active
        by: tax_admin
        gate: its valid_from is after today
        effect: the row is marked withdrawn, with who and when; it never takes effect
      - key: retire_code
        name: Retire the code
        from: active
        to: retired
        by: tax_admin
        gate: no rule in effect today or later points at it
        effect: no new determinations; documents keep it
    note: a code's treatment and reporting_box are fixed once a document has used it (a different meaning is a new code); its description and wording may change, because each issued document keeps the wording it froze
  - entity: document_tax
    states:
      - computed
      - frozen
    terminal:
      - frozen
    transitions:
      - key: determine
        name: Determine each line's code
        from: none
        to: computed
        by: system
        gate: "a rule of the document's direction (sale | purchase) valid on the tax point covers every (category, treatment) pair, except a line pinned to an earlier frozen document (v4, TAX-47), which takes that document's code and rate; the party has a treatment: the customer's for a sale, the SUPPLIER's for a purchase (v6, TAX-53: or, with no bp_id, the treatment_code the document names; neither refuses with gate party_or_treatment); v6, TAX-51: a line's consumption (eat_in | takeaway) selects among rules that distinguish it"
        effect: code, rate, VAT per line; the per-rate summary; the total; for a purchase, VAT split into reclaimable and non-reclaimable by each code's reclaimable_pct
      - key: ai_suggest_code
        name: AI suggests a code for a line no rule covers (suggest)
        from: computed
        to: computed
        by: system
        gate: a line has no rule, or no product, and the step is on
        effect: a proposed code with its reason; nothing is applied
      - key: accept_tax_suggestion
        name: Accept or reject the suggestion
        from: computed
        to: computed
        by: biller
        gate: a suggestion is open on the line
        effect: "accepted: recorded as an override with the suggestion, the model and who accepted; rejected: the line stays refused until a person chooses"
      - key: override_line
        name: Override a line's code
        from: computed
        to: computed
        by: biller
        requires: reason
        gate: the biller disagrees with the rule's code
      - key: approve_override
        name: Approve an override that lowers tax
        from: computed
        to: computed
        by: tax_admin
        approval: true
        gate: an override lowers the tax; the approver is not the person who overrode, unless override_approval is self_with_reason
      - key: check_contents
        name: Check the invoice contents
        from: computed
        to: computed
        by: system
        gate: the document is about to issue (a sale) or be approved (a purchase)
        effect: "every para 16.3.1 gate as {gate, met, reason, fix}; for a purchase the supplier is the SUPPLIER (its name, address and VAT number on the bill) and we are the customer; v6, TAX-50: a purchase at or under simplified_invoice_threshold (gross including VAT) is a less detailed invoice (VAT Notice 700 para 16.6.1, VAT Regulations 1995 reg. 16): our name and address are not required and the title says so"
      - key: freeze
        name: Freeze the tax at issue
        from: computed
        to: frozen
        by: system
        gate: "every readiness gate met: contents complete, no open suggestion, no override waiting for approval"
        effect: never recomputed
    note: the document (an order, an invoice, a credit note) owns its own copy of the result; this lifecycle is the tax on it
  - entity: party_tax
    states:
      - recorded
    terminal: []
    transitions:
      - key: set_party_tax
        name: Record a customer's or supplier's treatment and VAT number
        from: none
        to: recorded
        by: biller
        gate: a treatment that needs a VAT number has one; the first row of a party holds from the start
        effect: the party's first tax row (TAX-05)
      - key: change_party_tax
        name: Change a party's treatment, number or end-user notice (v4)
        from: recorded
        to: recorded
        by: biller
        gate: valid_from after today; a construction end-user or intermediary notice carries its reference and date
        effect: a new dated row; documents not yet issued with a tax point from then use it (TAX-05, TAX-46)
      - key: check_party_vat_number
        name: Check the VAT number with HMRC (v4)
        from: recorded
        to: recorded
        by: system
        gate: a treatment that needs a VAT number was saved, or its last check is older than vat_number_check_days before a reverse-charge document issues
        effect: check_result valid | invalid | could_not_check, HMRC's name and address and consultation number stored on the row (TAX-13)
      - key: confirm_party_vat_number
        name: Confirm a number HMRC could not check (v4)
        from: recorded
        to: recorded
        by: tax_admin
        requires: reason
        gate: the last check is could_not_check (a non-GB number, or HMRC unavailable)
        effect: recorded as confirmed by a person, with the reason
    note: "v4: the party's tax rows were a table only; drawing them makes the VAT-number check and the end-user notice visible in the signed process"
  - entity: vat_return
    states:
      - open
      - draft
      - locked
      - submitted
    terminal:
      - submitted
    transitions:
      - key: sync_vat_obligations
        name: Read our obligations from HMRC
        from: none
        to: open
        by: system
        gate: an HMRC connection for the VRN
        effect: one vat_obligation per periodKey with HMRC's dates; a period HMRC shows filed is marked so (TAX-27)
        timer: daily
      - key: prepare_vat_return
        name: Prepare the return
        from: open
        to: draft
        by: tax_admin
        gate: the obligation is open at HMRC
        effect: "boxes 1-9 from frozen document tax not yet in a return (claimed per [document_ref, tax_code]), under the period's scheme: invoice or cash basis, flat rate, partial exemption, bad debt claims and repayments, PVA entries, adjustments (TAX-28, TAX-35..TAX-37, TAX-48)"
      - key: refresh_vat_return
        name: Prepare the draft again
        from: draft
        to: draft
        by: tax_admin
        effect: this draft's entries replaced; entries of other returns untouched
      - key: record_vat_adjustment
        name: Correct an earlier period's error on this return
        from: draft
        to: draft
        by: tax_admin
        requires: reason
        gate: net errors within the error-correction threshold and the error within four years
        effect: an adjustment row naming the period it corrects, in box 1 or 4 (TAX-29)
      - key: record_vat_error_notice
        name: Record an error notified to HMRC (VAT652)
        from: draft
        to: draft
        by: tax_admin
        requires: reference
        gate: an error above the threshold
        effect: the notice kept with its date, periods and amount; it is not on the return
      - key: ai_review_vat_return
        name: AI reviews the draft return (suggest)
        from: draft
        to: draft
        by: system
        gate: the step is on
        effect: findings (a box moving far from the last four periods, a document with an unusual code) listed for the tax admin; nothing changes
      - key: lock_vat_return
        name: Lock the return for submission
        from: draft
        to: locked
        by: tax_admin
        gate: the period has ended (its end before today in business_timezone); the period's postponed-import statements reconciled; flat-rate eligibility answered; no adjustment above the threshold
        effect: boxes and entries frozen; a new document with a tax point in the period is refused (tax_point_open)
      - key: reopen_vat_return
        name: Reopen a locked return
        from: locked
        to: draft
        by: tax_admin
        requires: reason
        gate: not submitted
      - key: submit_vat_return
        name: Submit to HMRC with the declaration
        from: locked
        to: submitted
        by: owner
        approval: true
        requires: declaration
        gate: the HMRC connection is valid; the person ticked the legal declaration; a second person where vat_return_needs_second_person (not the identity that locked it, by email or sub); every fraud-prevention header present; HMRC still shows the obligation open
        effect: HMRC's receipt stored; the return immutable; its tax points filed (TAX-30, TAX-31)
      - key: settle_vat_return
        name: Post the return's settlement to the ledger
        from: submitted
        to: submitted
        by: system
        gate: the ledger is installed
        effect: each tax code's VAT against vat_control, journal id derived from the return; once (TAX-32)
      - key: refresh_vat_liability
        name: Read HMRC's liabilities and payments
        from: submitted
        to: submitted
        by: system
        gate: an HMRC connection
        effect: liability, paid and outstanding per period as HMRC holds them (TAX-32)
        timer: daily
    note: a submission that times out is settled by GET /organisations/vat/{vrn}/returns/{periodKey} before any retry, so a return is never filed twice; a correction after submission is an adjustment on a later return or a VAT652 notice, never an edit
  - entity: bad_debt_claim
    states:
      - eligible
      - claimed
      - dismissed
    terminal:
      - claimed
      - dismissed
    transitions:
      - key: suggest_bad_debt_relief
        name: List invoices eligible for relief
        from: none
        to: eligible
        by: system
        gate: an invoice six months past the later of its due and supply dates, written off, its VAT in a submitted return
        effect: one eligible row per invoice
        timer: when a return is prepared
      - key: claim_bad_debt_relief
        name: Claim the relief on this return
        from: eligible
        to: claimed
        by: tax_admin
        gate: every eligibility gate met; within four years and six months
        effect: the VAT fraction of the unpaid amount in box 4 (TAX-34)
      - key: dismiss_bad_debt_relief
        name: Do not claim
        from: eligible
        to: dismissed
        by: tax_admin
        requires: reason
      - key: repay_bad_debt_relief
        name: Repay relief on a later receipt
        from: claimed
        to: claimed
        by: system
        gate: a receipt allocated to the invoice after the claim
        effect: its VAT fraction in box 1 of the next return, once per allocation (TAX-35)
  - entity: cis_subcontractor
    states:
      - unverified
      - verified
    terminal: []
    transitions:
      - key: add_cis_subcontractor
        name: Add a subcontractor
        from: none
        to: unverified
        by: tax_admin
        requires: utr
        gate: a business partner with a UTR (and a company number or NI number)
      - key: verify_cis_subcontractor
        name: Verify with HMRC
        from: unverified
        to: verified
        by: tax_admin
        gate: an HMRC connection, or a verification number a person read from HMRC
        effect: status gross | net | unmatched, rate and verification number from today (TAX-38)
      - key: reverify_cis_subcontractor
        name: Verify again
        from: verified
        to: verified
        by: tax_admin
        effect: a new dated row; deductions from then use it
  - entity: cis_return
    states:
      - open
      - prepared
      - submitted
    terminal:
      - submitted
    transitions:
      - key: compute_cis_deduction
        name: Compute the deduction on a subcontractor's payment
        from: open
        to: open
        by: system
        gate: the subcontractor is verified, or was paid in this or the last two tax years
        effect: a deduction row keyed [payment_ref, bp_id] in the payment's tax month (TAX-39)
      - key: reverse_cis_deduction
        name: Reverse a deduction when the payment is rejected (v4)
        from: open
        to: open
        by: system
        gate: the deduction's tax month is not submitted (cis_return_open); a repeat answers the same
        effect: a reversing deduction row keyed [payment_ref, bp_id]; the month's return and the subcontractor's statement no longer count it
      - key: prepare_cis_return
        name: Prepare the monthly CIS return
        from: open
        to: prepared
        by: tax_admin
        gate: the tax month (6th to 5th) has ended
        effect: the CIS300 lines per subcontractor, or a nil return
      - key: submit_cis_return
        name: Submit the CIS return
        from: prepared
        to: submitted
        by: tax_admin
        approval: true
        requires: declaration
        gate: the employment-status and verification declarations confirmed by a person; an HMRC connection
        effect: HMRC's receipt kept (TAX-40)
      - key: send_cis_statements
        name: Send each subcontractor its statement
        from: submitted
        to: submitted
        by: tax_admin
        effect: a payment and deduction statement per subcontractor, the send recorded
  - entity: trade_declaration
    states:
      - draft
      - filed
    terminal:
      - filed
    transitions:
      - key: prepare_trade_declaration
        name: Prepare the EC sales list or Intrastat declaration
        from: none
        to: draft
        by: tax_admin
        gate: ni_goods registered; for Intrastat, the flow's threshold passed
        effect: lines from ar's (and purchasing's) goods documents with EU partners; the upload file (TAX-42, TAX-43)
      - key: record_trade_declaration_filed
        name: Record that it was filed with HMRC
        from: draft
        to: filed
        by: tax_admin
        requires: submission_ref
        gate: the EC sales list ties to box 8 for its months; every Intrastat line has a commodity code
        effect: filed with the reference and date; an amendment is a new version
  - entity: pva_statement
    states:
      - imported
      - reconciled
    terminal:
      - reconciled
    transitions:
      - key: import_pva_statement
        name: Upload the month's postponed import VAT statement
        from: none
        to: imported
        by: tax_admin
        gate: one statement per month
        effect: statement lines kept, the file kept as an object
      - key: match_pva_statement
        name: Match statement lines to import entries
        from: imported
        to: imported
        by: system
        effect: each line matched by MRN, with any difference
      - key: explain_pva_difference
        name: Explain a difference
        from: imported
        to: imported
        by: tax_admin
        requires: reason
      - key: reconcile_pva_statement
        name: Reconcile the statement
        from: imported
        to: reconciled
        by: tax_admin
        gate: every line matched or explained
        effect: the return uses the reconciled figures (TAX-45)
readiness:
  shape: "{gate, met, reason, fix}"
  rule: "For every transition above with a gate, the brick answers each gate as {gate, met, reason, fix}: gate a stable id, met true or false, reason one sentence in the customer's words (citing the VAT guide where it applies), fix the screen or the record that satisfies it. A refused transition returns its unmet gates; a screen, the MCP tools and the selling bricks show them and never re-derive a rule. Issue in sales-order and ar asks document_tax for these gates before it issues."
  gates:
    - transition: register
      gate: vat_number
      reason: a VAT registration needs its number (GB and 9 or 12 digits)
      fix: Tax settings > Registration
    - transition:
        - register
        - deregister
        - schedule_rate
      gate: starts_after_today
      reason: a change starts tomorrow at the earliest, in business_timezone
      fix: pick a later date
    - transition:
        - register
        - schedule_rate
      gate: second_person
      reason: the owner asks a second person to approve tax changes
      fix: ask another holder of tax:code:approve
    - transition: activate_code
      gate: first_rate
      reason: a code needs a rate before it can be used
      fix: Tax codes > the code > Rates
    - transition: activate_code
      gate: wording
      reason: a reverse-charge code prints its legend on the invoice
      fix: Tax codes > the code > Wording
    - transition: retire_code
      gate: no_rule_points_here
      reason: a rule in effect still chooses this code
      fix: "Tax rules: end that rule first"
    - transition: determine
      gate: rule_covers_pair
      reason: no tax rule for (category, treatment) on the tax point
      fix: Tax rules, or override the line
    - transition: determine
      gate: customer_treatment
      reason: the customer has no tax treatment
      fix: Customer tax
    - transition: determine
      gate: supplier_treatment
      reason: the supplier has no tax treatment (a purchase)
      fix: "Customer tax: the supplier's row (the same party tax, keyed bp_id)"
    - transition: determine
      gate: purchase_rule_covers_pair
      reason: no purchase rule for (category, the supplier's treatment) on the tax point
      fix: Tax rules (direction purchase), or override the line
    - transition: freeze
      gate: supplier_vat_number
      reason: "a purchase bill without the supplier's VAT number is not a VAT invoice: its input VAT cannot be reclaimed"
      fix: ask the supplier for a valid VAT invoice
    - transition: freeze
      gate: contents_complete
      reason: one gate per absent item of VAT Notice 700 para 16.3.1
      fix: the record that holds the item
    - transition: freeze
      gate: no_open_suggestion
      reason: a person has not yet accepted or rejected the AI's code
      fix: Document tax > the line
    - transition: freeze
      gate: override_approved
      reason: an override that lowers tax waits for approval
      fix: ask a holder of tax:document_tax:approve_override
    - transition: freeze
      gate: vat_number_valid
      reason: HMRC has no registration for the customer's VAT number, or it could not be checked and no person confirmed it
      fix: "Customer tax: correct or confirm the number"
    - transition: determine
      gate: pinned_code
      reason: the pinned line names a code the earlier document does not carry
      fix: pin to the code the earlier document froze
    - transition: determine
      gate: pinned_within_original
      reason: the pinned lines take more than the earlier document's net for that code
      fix: lower the amount to what remains
    - transition: change_vat_scheme
      gate: period_start
      reason: a scheme or basis changes from the first day of a VAT period after today
      fix: pick the next period's start
    - transition: change_vat_scheme
      gate: scheme_eligible
      reason: expected taxable turnover is above the scheme's joining limit (tax_statutory)
      fix: stay on the invoice basis
    - transition:
        - sync_vat_obligations
        - submit_vat_return
        - refresh_vat_liability
        - submit_cis_return
      gate: hmrc_connected
      reason: this business is not connected to HMRC, or the grant expired
      fix: Tax settings > HMRC connection (the owner)
    - transition: prepare_vat_return
      gate: obligation_open
      reason: HMRC shows no open obligation for this period
      fix: "VAT returns: read obligations again"
    - transition: record_vat_adjustment
      gate: within_error_threshold
      reason: net errors above 10,000.00, or above 50,000.00 or 1% of box 6, are notified to HMRC (Notice 700/45)
      fix: record a VAT652 notice instead
    - transition: record_vat_adjustment
      gate: within_four_years
      reason: an error older than four years cannot be corrected
      fix: "none: the four-year cap"
    - transition: lock_vat_return
      gate: period_ended
      reason: the period ends on its end date; a return is locked after it
      fix: wait until the day after
    - transition: lock_vat_return
      gate: pva_reconciled
      reason: a postponed import VAT statement of the period is not reconciled
      fix: Import VAT > the statement
    - transition: lock_vat_return
      gate: flat_rate_eligible
      reason: flat-rate turnover passed the leaving limit; the scheme ends
      fix: record the change of scheme
    - transition: submit_vat_return
      gate: declaration_confirmed
      reason: submitting is a legal declaration a person makes
      fix: tick the declaration
    - transition: submit_vat_return
      gate: second_person
      reason: the owner asks someone other than the person who locked it to submit (same email or sub refused)
      fix: ask another holder of tax:vat_return:submit
    - transition: submit_vat_return
      gate: fraud_headers_complete
      reason: HMRC requires every fraud-prevention header for WEB_APP_VIA_SERVER
      fix: submit from the web screen
    - transition: submit_vat_return
      gate: obligation_still_open
      reason: HMRC already shows this period filed
      fix: "none: an error is corrected on a later return"
    - transition: claim_bad_debt_relief
      gate: six_months_passed
      reason: relief starts six months after the later of the due date and the supply date
      fix: claim on a later return
    - transition: claim_bad_debt_relief
      gate: written_off
      reason: the debt is not written off in the accounts
      fix: "Invoicing: write it off (AR-09)"
    - transition: claim_bad_debt_relief
      gate: vat_accounted
      reason: the invoice's VAT is not in a submitted return
      fix: "none: no relief on VAT never paid"
    - transition: claim_bad_debt_relief
      gate: within_time_limit
      reason: more than four years and six months have passed
      fix: "none: the time limit"
    - transition: claim_bad_debt_relief
      gate: not_claimed
      reason: relief on this invoice is already claimed
      fix: none
    - transition: compute_cis_deduction
      gate: cis_verified
      reason: the subcontractor has not been verified with HMRC
      fix: CIS > Subcontractors > Verify
    - transition: compute_cis_deduction
      gate: materials_within_bill
      reason: materials exceed the bill's own materials figure
      fix: use the bill's figure
    - transition: prepare_cis_return
      gate: tax_month_ended
      reason: the tax month runs 6th to 5th
      fix: prepare after the 5th
    - transition: submit_cis_return
      gate: declarations_confirmed
      reason: the employment-status and verification declarations are a person's
      fix: confirm both
    - transition: record_trade_declaration_filed
      gate: ties_to_box_8
      reason: the EC sales list total differs from box 8 for its months
      fix: find the document in one and not the other
    - transition: record_trade_declaration_filed
      gate: commodity_code
      reason: a goods line's product has no commodity code
      fix: Product > the product > Trade
    - transition: reconcile_pva_statement
      gate: lines_matched
      reason: a statement line is neither matched to an import entry nor explained
      fix: Import VAT > the line
    - transition: confirm_party_vat_number
      gate: could_not_check
      reason: only a number HMRC could not check is confirmed by a person
      fix: correct an invalid number instead
entities:
  - id: registration
    meaning: whether, and from when, this business is registered for VAT
    natural_key:
      - jurisdiction
      - effective_from
    key_attributes:
      - vat_number
      - status
      - scheme (standard | flat_rate | cash_accounting)
      - accounting_basis (invoice | cash, v4)
      - flat_rate (bool), flat_rate_sector, flat_rate_pct (percent), first_year_until (v4)
      - "ni_goods (bool: an XI registration trading goods with the EU, v4)"
      - partial_exemption_year_end (MM-DD, v4)
      - stagger
      - effective_to
    master_data: module-owned (configuration)
    reference_table: tax_registration
    note: "v4: cash accounting and the flat rate scheme are COMPUTED by the return (TAX-36, TAX-37); a scheme change starts at a VAT period's first day after today. Dated rows: a change is a new row from after today; only the first row may carry an earlier date"
  - id: tax_code
    meaning: a jurisdiction's code for one tax treatment (S standard, Z zero, RC reverse charge)
    natural_key: "tax_code: VARCHAR, the code the customer recognises (shared.yaml keys.tax_code)"
    key_attributes:
      - jurisdiction (ISO 3166-1 alpha-2)
      - treatment (standard | reduced | zero | exempt | outside_scope | reverse_charge | not_registered | postponed_import
      - v4)
      - direction (sale | purchase; every v2 code is sale)
      - description
      - document_wording
      - reporting_box
      - "input_reporting_box (purchase reverse charge: the input side)"
      - "value_box (6 | 7 | 8 | 9: where the net value is reported, v4)"
      - "reclaimable_pct (percent, purchase codes only: 100 reclaimable input VAT, 0 non-reclaimable, e.g. business entertainment)"
      - "attribution (taxable | exempt | residual: partial exemption, purchase codes only, v4)"
      - "eu_goods (bool: NI goods to or from the EU, feeds boxes 2, 8, 9 and the trade declarations, v4)"
      - lifecycle
    relationships:
      - 1..n tax_rate
    master_data: "SHARED: sole writer tax (moves from gl / invoicing, see shared.yaml)"
    reference_table: tax_code
  - id: tax_rate
    meaning: a code's percentage from a date
    natural_key:
      - tax_code
      - valid_from
    key_attributes:
      - rate_pct (percent)
      - charged_pct (percent: 0 for reverse charge)
      - withdrawn_by
      - withdrawn_at
    master_data: module-owned (configuration)
    reference_table: tax_rate
    note: rate_pct is what is due, charged_pct what the supplier charges; they differ only under reverse charge. A row in effect is never edited or deleted; one not yet in effect may be withdrawn
  - id: tax_category
    meaning: how a product is taxed, in the abstract (standard, reduced, zero, exempt, construction_service)
    natural_key: category_code (shared.yaml keys.tax_category)
    key_attributes:
      - description
    master_data: "SHARED: sole writer tax; product stores it on each product"
    reference_table: tax_category
  - id: treatment
    meaning: how a customer, or a supplier on a purchase (v3), is taxed (UK business, UK consumer, overseas business, overseas consumer, CIS contractor)
    natural_key: treatment_code
    key_attributes:
      - description
      - needs_vat_number
    master_data: module-owned (configuration)
    reference_table: tax_treatment
  - id: party_tax
    meaning: one customer's treatment and VAT number
    natural_key:
      - bp_id
      - valid_from
    key_attributes:
      - treatment_code
      - vat_number
      - checked_on
      - check_result (valid | invalid | could_not_check | confirmed, v4)
      - check_ref (HMRC consultation number, v4)
      - hmrc_name, hmrc_address (as HMRC holds them, v4)
      - "end_user_notice_ref, end_user_notice_on (construction: an end user or intermediary is outside the reverse charge, v4)"
      - cis_registered (bool, v4)
      - recorded_by
    relationships:
      - -> business_partner
    master_data: module-owned
    reference_table: tax_party
    note: "the business-partner master holds identity, not tax: the treatment lives here, keyed on bp_id; a supplier's row is the same table (v3: a purchase reads the SUPPLIER's). A customer's first row holds from the start (valid_from null); a change is a new row from after today"
  - id: tax_rule
    meaning: which code a (category, treatment, supply) combination gets, from a date
    natural_key:
      - category_code
      - treatment_code
      - supply
      - direction
      - consumption
      - valid_from
    key_attributes:
      - tax_code
      - priority
      - valid_to
      - withdrawn_by
      - withdrawn_at
    master_data: module-owned (configuration)
    reference_table: tax_rule
    note: "supply is goods | services | any; the place-of-supply distinction a fiscal position would make. direction is sale | purchase (v3; every v2 row is sale): a purchase is determined only by purchase rules. A rule for a pair no rule covers may start today; a change to a covered pair starts after today. v6: consumption is eat_in | takeaway | any (every earlier row is any); a category's rules either all say any or distinguish eat_in and takeaway (TAX-51)"
  - id: statutory_value
    meaning: "a figure the law sets and changes (v4): the cash-accounting and flat-rate limits, the flat rate per sector, the error-correction threshold, CIS rates, partial-exemption de minimis, Intrastat and EC-sales-list thresholds"
    natural_key:
      - key
      - valid_from
    key_attributes:
      - value
      - unit
      - source (the HMRC notice and paragraph)
      - set_by
    master_data: module-owned (configuration; seeded by the UK pack)
    reference_table: tax_statutory
    note: "dated rows like rates: a change from after today; the pack loads each with its real date; code reads the row in force on the date it applies to, never a constant"
  - id: hmrc_connection
    meaning: this business's grant to call HMRC's APIs for its VRN (v4)
    natural_key: vrn
    key_attributes:
      - scopes (read:vat
      - write:vat)
      - environment (sandbox | production)
      - authorised_by
      - authorised_at
      - expires_at
      - secret_ref (the platform secret holding the tokens)
      - status (connected | expired | revoked)
    master_data: module-owned (state)
    reference_table: tax_hmrc_connection
    note: "tokens are never stored in a row or logged: only the secret's reference"
  - id: vat_obligation
    meaning: a VAT period HMRC expects a return for (v4)
    natural_key:
      - vrn
      - period_key
    key_attributes:
      - period_start
      - period_end
      - due_date
      - status (O | F)
      - received_on
      - synced_at
    master_data: module-owned (a copy of HMRC's, refreshed)
    reference_table: tax_vat_obligation
  - id: vat_return
    meaning: "one VAT return: its nine boxes, how they were prepared and HMRC's receipt (v4)"
    natural_key:
      - vrn
      - period_key
    key_attributes:
      - lifecycle
      - accounting_basis
      - flat_rate_pct
      - box1_vat_due_sales
      - box2_vat_due_acquisitions
      - box3_total_vat_due
      - box4_vat_reclaimed
      - box5_net_vat_due
      - box6_total_sales_ex_vat
      - box7_total_purchases_ex_vat
      - box8_goods_supplied_ex_vat
      - box9_acquisitions_ex_vat
      - prepared_by
      - locked_by
      - locked_at
      - submitted_by
      - submitted_at
      - declaration_text
      - processing_date
      - form_bundle_number
      - payment_indicator
      - charge_ref_number
      - fraud_headers_json
      - settle_journal_id
    relationships:
      - 1..n vat_return_entry
      - 0..n vat_adjustment
    master_data: module-owned
    reference_table: tax_vat_return
    note: boxes 1-5 NUMERIC(18,2); boxes 6-9 whole pounds held as NUMERIC(18,2) with .00 (HMRC's rule); every box is SUM of its entries, re-derived, never typed; immutable once submitted
  - id: vat_return_entry
    meaning: "one document's tax by code in one return: the claim that it is counted once (v4)"
    natural_key:
      - document_ref
      - tax_code
      - entry_kind
    key_attributes:
      - vrn
      - period_key
      - direction
      - tax_point
      - net_amount
      - vat_amount
      - vat_reclaimable
      - box_vat
      - box_value
      - source (document | cash_basis | flat_rate | pva | bad_debt_claim | bad_debt_repayment | adjustment | partial_exemption)
    master_data: module-owned
    reference_table: tax_vat_return_entry
    note: entry_kind separates a document's invoice-basis entry from a cash-basis part payment ('cash:<payment_id>:<seq>'), a bad-debt repayment ('bdr:<allocation>') and so on; the primary key is the claim, taken with a plain INSERT so two preparations never count one document twice
  - id: vat_adjustment
    meaning: an earlier period's error corrected on this return (v4)
    natural_key:
      - vrn
      - period_key
      - adjustment_no
    key_attributes:
      - corrects_period_key
      - box (1 | 4)
      - amount
      - reason
      - recorded_by
      - recorded_at
    master_data: module-owned
    reference_table: tax_vat_adjustment
  - id: vat_error_notice
    meaning: an error above the threshold notified to HMRC on VAT652 (v4)
    natural_key:
      - vrn
      - notice_ref
    key_attributes:
      - periods
      - amount
      - sent_on
      - recorded_by
    master_data: module-owned
    reference_table: tax_vat_error_notice
  - id: vat_liability
    meaning: what HMRC says we owe and have paid per period (v4), a refreshed copy
    natural_key:
      - vrn
      - period_key
      - charge_type
    key_attributes:
      - original_amount
      - outstanding_amount
      - due_date
      - paid_amount
      - paid_on
      - synced_at
    master_data: module-owned (a copy of HMRC's)
    reference_table: tax_vat_liability
  - id: bad_debt_claim
    meaning: relief claimed on one unpaid invoice, and repayments when it is paid after all (v4)
    natural_key: invoice_id
    key_attributes:
      - lifecycle
      - bp_id
      - supply_date
      - due_date
      - eligible_from
      - gross
      - unpaid_at_claim
      - vat_fraction
      - relief_amount
      - claimed_in_period_key
      - claimed_by
      - dismissed_reason
    master_data: module-owned
    reference_table: tax_bad_debt_claim
  - id: cis_subcontractor
    meaning: a subcontractor's CIS verification, from a date (v4)
    natural_key:
      - bp_id
      - valid_from
    key_attributes:
      - utr
      - company_number
      - ni_number_masked
      - status (gross | net | unmatched)
      - rate_pct (percent)
      - verification_number
      - verified_by
      - verified_on
      - last_paid_tax_year
    master_data: module-owned
    reference_table: tax_cis_subcontractor
  - id: cis_deduction
    meaning: the CIS deducted from one payment to a subcontractor (v4)
    natural_key:
      - payment_ref
      - bp_id
    key_attributes:
      - tax_month (YYYY-MM
      - the month ending on the 5th)
      - paid_on
      - gross_ex_vat
      - materials
      - labour
      - rate_pct (percent)
      - deduction
      - cis_return_id
    master_data: module-owned
    reference_table: tax_cis_deduction
  - id: cis_return
    meaning: the monthly CIS300 (v4)
    natural_key: cis_return_id = "<contractor_utr>:<tax_month>"
    key_attributes:
      - lifecycle
      - nil_return
      - total_gross
      - total_materials
      - total_deduction
      - submitted_by
      - submitted_at
      - hmrc_ref
    master_data: module-owned
    reference_table: tax_cis_return
  - id: cis_suffered
    meaning: CIS a contractor customer deducted from what it paid us (v4)
    natural_key:
      - contractor_bp_id
      - statement_ref
    key_attributes:
      - tax_month
      - invoice_id
      - payment_id
      - gross
      - materials
      - deduction
      - recorded_at
    master_data: module-owned
    reference_table: tax_cis_suffered
  - id: trade_declaration
    meaning: an EC sales list or an Intrastat declaration for a period (NI goods, v4)
    natural_key:
      - kind (esl | intrastat_dispatches | intrastat_arrivals)
      - period
      - version
    key_attributes:
      - lifecycle
      - line_count
      - total_value
      - file_key
      - submission_ref
      - filed_on
      - filed_by
    relationships:
      - 1..n trade_declaration_line
    master_data: module-owned
    reference_table: tax_trade_declaration
  - id: trade_declaration_line
    meaning: one line of a trade declaration (v4)
    natural_key:
      - kind
      - period
      - version
      - line_no
    key_attributes:
      - partner_vat_number
      - partner_country
      - commodity_code
      - nature_of_transaction
      - country_of_origin
      - value
      - net_mass_kg
      - supplementary_units
      - indicator
      - source_refs
    master_data: module-owned
    reference_table: tax_trade_declaration_line
  - id: import_entry
    meaning: one customs import entry and how its import VAT is accounted (v4)
    natural_key: mrn
    key_attributes:
      - entry_date
      - bill_ref
      - bp_id
      - customs_value
      - import_vat
      - tax_code (PVA | IMPORT_PAID)
      - evidence (pva_statement | import_vat_certificate)
      - period_key
    master_data: module-owned
    reference_table: tax_import_entry
  - id: pva_statement
    meaning: the monthly postponed import VAT statement from CDS, and its lines (v4)
    natural_key:
      - vrn
      - statement_month
    key_attributes:
      - lifecycle
      - file_key
      - lines_json (mrn
      - import_vat
      - value)
      - matched_count
      - explained_json
    master_data: module-owned
    reference_table: tax_pva_statement
  - id: capital_goods_item
    meaning: an asset under the Capital Goods Scheme and its yearly adjustments (v4)
    natural_key: item_ref
    key_attributes:
      - kind (land_building | computer | ship_aircraft)
      - bought_on
      - input_vat
      - intervals
      - first_pct (percent)
      - adjustments_json (interval
      - pct
      - amount
      - period_key)
      - disposed_on
    master_data: module-owned
    reference_table: tax_capital_goods
  - id: partial_exemption_year
    meaning: "one partial-exemption year: its provisional and final recovery and the de minimis tests (v4)"
    natural_key:
      - vrn
      - year_end
    key_attributes:
      - provisional_pct (percent)
      - final_pct (percent)
      - taxable_supplies
      - exempt_supplies
      - exempt_input_vat
      - residual_input_vat
      - de_minimis_met
      - adjustment_amount
      - adjusted_in_period_key
    master_data: module-owned
    reference_table: tax_partial_exemption
  - id: settings
    meaning: how this business computes VAT, and the owner's controls
    natural_key:
      - key
      - valid_from
    key_attributes:
      - value
      - set_by
    master_data: module-owned (configuration)
    reference_table: tax_settings
master_data:
  owns:
    - tax_code
    - tax_rate
    - tax_category
    - tax_treatment
    - tax_party
    - tax_rule
    - tax_registration
    - tax_settings
    - tax_migration_map
    - tax_statutory
    - tax_hmrc_connection
    - tax_vat_obligation
    - tax_vat_return
    - tax_vat_return_entry
    - tax_vat_adjustment
    - tax_vat_error_notice
    - tax_vat_liability
    - tax_bad_debt_claim
    - tax_cis_subcontractor
    - tax_cis_deduction
    - tax_cis_return
    - tax_cis_suffered
    - tax_trade_declaration
    - tax_trade_declaration_line
    - tax_import_entry
    - tax_pva_statement
    - tax_partial_exemption
    - tax_capital_goods
  references:
    - entity: business_partner
      owner: business-partner
      how: tax_party.bp_id = business_partner.bp_id
      if_absent: the treatment is chosen on each document; nothing remembers a customer's VAT number
    - entity: product
      owner: product
      how: the document line carries product.tax_category
      if_absent: every line chooses its category by hand
    - entity: fx_rate
      owner: gl
      how: the sterling VAT total of a foreign-currency document
      if_absent: the rate is entered on the document
    - entity: allocation
      owner: payments
      how: cash-basis receipts and bad-debt repayments are read through payments' routes (v4)
      if_absent: "cash accounting and the bad-debt repayment are not computed: the return refuses the cash basis (gate) and lists claims for a person to check"
    - entity: commodity_code
      owner: product
      how: Intrastat lines read the product's commodity code and net weight (v4)
      if_absent: the Intrastat line is a gate until a person enters the code
  warning: "Tax codes kept in invoicing AND in the ledger AND in purchasing is how the VAT return stops matching the invoices. One writer: this module. The ledger maps each code to an account; it does not own the code."
jobs:
  - story: TAX-10
    trigger: in the same request
    runs: determine + compute
    where_options:
      - in the same request
    idempotent: a pure function of (lines, treatment, tax point, rules, rates, method)
  - story: TAX-11
    trigger: when the document issues
    runs: freeze
    where_options:
      - in the same request
    idempotent: keyed on the document id; freezing twice is a no-op
  - story: TAX-12
    trigger: before issue
    runs: the content check
    where_options:
      - in the same request
    idempotent: a read
  - story: TAX-15
    trigger: once, at cutover
    runs: the Odoo migration (migration.odoo)
    where_options:
      - a one-off job run by the system's service client
    idempotent: "keyed on (odoo model, odoo id) in tax_migration_map: a re-run matches the same natural keys and writes nothing new"
  - story: TAX-27
    trigger: daily, and on opening VAT returns
    runs: sync_vat_obligations (GET obligations from HMRC)
    where_options:
      - the composition's clock worker calling the brick's sync route (--reserved 1 --max-replicas 1)
      - external scheduler
    idempotent: "keyed [vrn, period_key]: a re-read rewrites nothing that did not change"
  - story: TAX-13
    trigger: when a treatment that needs a VAT number is saved, and before a reverse-charge document issues when the check is stale
    runs: check_party_vat_number (HMRC Check a UK VAT number)
    where_options:
      - in the same request
      - after the row commits
    idempotent: "keyed on the party_tax row: a re-check updates checked_on and the result, never adds a row"
  - story: TAX-32
    trigger: daily while a submitted return has an outstanding liability
    runs: refresh_vat_liability (GET liabilities and payments)
    where_options:
      - the same clock worker
    idempotent: keyed [vrn, period_key, charge_type]
  - story: TAX-34
    trigger: when a return is prepared
    runs: suggest_bad_debt_relief
    where_options:
      - in the prepare request
    idempotent: "keyed invoice_id: an invoice is eligible, claimed or dismissed once"
  - story: TAX-35
    trigger: when a return is prepared
    runs: repay_bad_debt_relief
    where_options:
      - in the prepare request
    idempotent: an entry keyed [claim, allocation] is claimed once
  - story: TAX-39
    trigger: when purchasing approves a subcontractor payment
    runs: compute_cis_deduction
    where_options:
      - in the same request
    idempotent: "keyed [payment_ref, bp_id]: a retry returns the same deduction"
seams:
  - story: TAX-20
    with: sales-order
    owner: tax
    rule: sales-order, ar and quote call compute(); they store its answer and never apply a rate themselves
  - story: TAX-21
    with: gl
    owner: gl
    rule: the ledger's account map holds (purpose tax, tax_code) -> account_id; this module never writes the ledger
  - story: TAX-22
    with: gl
    owner: gl
    rule: the sterling rate is read from the ledger's fx_rate for the tax point; the result is frozen on the document
  - story: TAX-23
    with: purchasing
    owner: tax
    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"
    rule: "built (erp-brick-tax compute_tax: lines, tax_point, bp_id, currency, document_ref, treatment_code, prices_include_tax, fx_rate); v4 adds direction, pinned lines, ship_to_country and self_billed; purchasing sends direction purchase (and self_billed for an ERS invoice, PUR-51); it stores the answer as its copy and never applies a rate"
    status: aligned 2026-10-22 with purchasing PUR-28
  - story: TAX-24
    with: purchasing
    owner: tax
    route: POST /documents/{document_ref}/check-contents
    permission: tax:document_tax:compute
    request: "{direction: \"purchase\", contents: {invoice_number (the supplier's), issue_date (v6: the supplier's invoice date, YYYY-MM-DD), supplier_name, supplier_address (v6: the address shape, shared.yaml conventions.address), supplier_vat_number (absent when the bill shows none), customer_name (us: our company's name)}}"
    request_schema:
      - field: document_ref
        type: string
        required: true
        in: path
      - field: direction
        type: string
        required: true
        values:
          - purchase
      - field: contents
        type: object
        required: true
        items:
          - field: invoice_number
            type: string
            required: true
          - field: issue_date
            type: date
            required: true
          - field: supplier_name
            type: string
            required: true
          - field: supplier_address
            type: object
            required: true
          - field: supplier_vat_number
            type: string
            required: false
          - field: customer_name
            type: string
            required: false
    response: "{document_ref, status, ready, title, gates: [{gate, met, reason, fix}]}"
    rule: "with direction purchase the gates check the SUPPLIER's name, address and VAT number, the supplier's invoice number and date, and our name as the customer (customer_name is optional only on a less detailed invoice, TAX-50); purchasing's approve_bill gate tax_content is this answer. v6: supplier_address is the address object; a string is accepted until tax's next major as one address line (shared.yaml conventions.address legacy)"
    status: aligned 2026-10-22 with purchasing PUR-28
  - story: TAX-15
    with: gl
    owner: tax
    route: GET /migration-map/{db}/{model}?ids=
    permission: tax:migration:read
    request: path db, model account.tax | account.fiscal.position; query ids=<comma-separated Odoo ids>
    response: "[{odoo_model, odoo_id, ours}]; an id not migrated is omitted"
    rule: the one map route (shared.yaml conventions.odoo_migration.map_route), read from tax_migration_map by gl, ar and purchasing; sale and purchase taxes alike
    status: aligned 2026-10-22 with gl GL-34
  - story: TAX-33
    with: ar
    owner: tax
    route: GET /vat-returns/tax-point-status?date=
    permission: tax:tax_point:read
    request: query date=YYYY-MM-DD (the document's tax point)
    response: "200 {date, period_key | null, status: none | open | draft | locked | submitted, filed: bool, gate: {gate: tax_point_open, met, reason, fix}}"
    rule: "ar's issue gate tax_point_open and its void_policy (never_sent: not in a filed return) read this answer; locked counts as closed for a new tax point; ar never reads tax_ tables (the L2C leftover's missing callee)"
    status: aligned 2026-10-22 with ar AR-14
  - story: TAX-34
    with: ar
    owner: ar
    route: GET /writeoffs?status=approved&approved_from=
    permission: ar:invoice:read
    request: query status, approved_from
    response: "200 {writeoffs: [{writeoff_id, invoice_id, bp_id, amount, currency, approved_at, invoice_issue_date, tax_point_date, due_date, total}]}"
    rule: "eligibility reads approved write-offs; the unpaid amount comes from payments' settlement; tax never reads ar_ tables; this call: query status=approved, approved_from=YYYY-MM-DD"
    status: aligned 2026-10-22 with ar AR-09
  - story: TAX-34
    with: payments
    owner: payments
    route: GET /settlement
    permission: pay:receipt:read
    request: query invoice_ids=<comma-separated, at most 200>, as_at=YYYY-MM-DD (optional; today)
    response: "200 {as_at, invoices: [{invoice_id, currency, total, outstanding, state, ...}], unknown: [ids]}"
    rule: the unpaid consideration at the claim is outstanding as at the claim date; relief = unpaid x VAT / gross of the frozen document tax
    status: "aligned 2026-10-22 with payments PAY-40 (built: erp-brick-payments use_cases.settlement)"
  - story: TAX-35
    with: payments
    owner: payments
    route: GET /allocations?invoice_ids=&from=
    permission: pay:receipt:read
    request: query invoice_ids=<comma-separated, at most 200>, from=YYYY-MM-DD (optional)
    response: "200 {allocations: [{source_kind, source_id, invoice_id, seq, amount, currency, allocated_on, received_on, reverses_seq}]}"
    rule: repayment = each receipt allocation after the claim x the claim's VAT fraction; a reversing row reverses the repayment; tax never reads pay_ tables
    status: aligned 2026-10-22 with payments PAY-46
  - story: TAX-36
    with: payments
    owner: payments
    route: GET /cash-basis?from=&to=
    permission: pay:receipt:read
    request: query from, to
    response: "200 {allocations: [{payment_id, invoice_id, seq, amount, currency, received_on, allocated_on, source_kind}]}"
    rule: "receipt allocations (source_kind receipt) dated by the receipt's received_on; one allocated after its period's return was locked enters the next open return; the VAT is the allocation x the invoice's frozen VAT / gross, per code; this call: query from, to (the VAT period)"
    status: aligned 2026-10-22 with payments PAY-46
  - story: TAX-36
    with: purchasing
    owner: purchasing
    route: GET /supplier-payments?bank_account_id=&status=&from=&to=
    permission: purchasing:payment:read
    request: query from, to (paid_on, YYYY-MM-DD; confirmed payments only)
    response: "200 {payments: [{payment_id, run_id, bp_id, bank_account_id, amount, currency, reference, status: sent | confirmed | rejected, paid_on, bills: [{bill_id, amount}]}]}"
    rule: "the input side of cash accounting: supplier payments confirmed by the bank, with the bills each paid"
    status: aligned 2026-10-22 with purchasing PUR-66
  - story: TAX-39
    with: purchasing
    owner: tax
    route: POST /cis/deductions
    permission: tax:cis:deduct
    request: "{payment_ref, bp_id (the subcontractor), paid_on, bill_ids, gross_ex_vat, materials}"
    response: "200 {payment_ref, bp_id, tax_month, status: gross | net | unmatched, rate_pct, labour, deduction, gates: [{gate, met, reason, fix}]}; 422 when a gate is unmet"
    rule: purchasing pays gross less the deduction and books the deduction to the CIS liability; it never computes a rate; the call is idempotent on [payment_ref, bp_id]
    status: "aligned 2026-10-22 with purchasing PUR-61; tax's body wins: this module computes the deduction, purchasing never applies a rate"
  - story: TAX-41
    with: payments
    owner: tax
    route: POST /cis/suffered
    permission: tax:cis:record_suffered
    request: "{contractor_bp_id, statement_ref, tax_month, invoice_id, payment_id, gross, materials, deduction}"
    response: "201 {recorded: true}; 200 {replay: true} for the same statement; 422 {gate: within_cis_rate, reason, fix}"
    rule: payments records the receipt net and allocates the deduction (source_kind cis_deduction, PAY-45); this module keeps what was suffered per tax month
    status: aligned 2026-10-22 with payments PAY-45
  - story: TAX-44
    with: purchasing
    owner: tax
    route: POST /imports
    permission: tax:import_vat:record
    request: "{mrn, entry_date, bill_ref, bp_id, customs_value, import_vat, method: postponed | paid}"
    response: "201 {mrn, tax_code: PVA | IMPORT_PAID, box_vat_output, box_vat_input, box_value}; 200 replay for the same mrn"
    rule: purchasing calls it for an import on a supplier bill or a freight agent's invoice (PUR-62); keyed by MRN
    status: aligned 2026-10-22 with purchasing PUR-62
  - story: TAX-43
    with: ar
    owner: ar
    route: GET /invoices/{invoice_id}
    permission: ar:invoice:read
    request: path invoice_id
    response: "200 {invoice_id, bp_id, company_code, currency, issue_date, tax_point_date, status, lines: [{line_no, product_id, description, quantity, unit_code, net_amount, tax_code}], tax, totals}"
    rule: "Intrastat dispatches read the goods lines; tax never reads ar_ tables; this call: path invoice_id (a frozen sale document with goods lines to an EU partner)"
    status: built; aligned 2026-10-22 with ar AR-17
  - story: TAX-43
    with: product
    owner: product
    route: GET /products/{product_id}?on=
    permission: product:product:read
    request: "path product_id; query on (default today: the date the measures and roles are read for)"
    response: "{product_id, name, description, kind, product_type_code, stocked_default, valuation_class, tax_category, commodity_code (v3), country_of_origin (v3), base_unit_code, roles {sales, purchase, issue, production, warehouse, delivery}, units: [{unit_code, numerator, denominator, quantity_decimals, gtins: [{gtin, kind}], measures: {gross_weight, net_weight, weight_unit_code, volume, volume_unit_code, length, width, height, dimension_unit_code, valid_from} | null}], lifecycle, version}"
    rule: Intrastat dispatches and arrivals read commodity_code, country_of_origin and the unit's net weight (product v3); tax never reads product tables
    status: built; aligned 2026-10-22 with product PRD-28
  - story: TAX-32
    with: gl
    owner: gl
    route: POST /journal-entry/journals
    permission: gl:journal:post
    request: '{source_module: "tax", source_document: "vat_return:<vrn>:<period_key>", event: settle, journal_date: the submission date, currency: GBP, lines: [{purpose: tax, tax_code, debit | credit}, ..., {purpose: vat_control, debit | credit}]}'
    response: "201 {journal_id, entry_no, period_id, status: posted}; 200 replay; 409 / 422 gates"
    rule: gl's GL-30 tax seam as reserved; the journal id is derived by gl from (source_document, event), so it posts once
    status: aligned 2026-10-22 with gl GL-30
  - story: TAX-20
    with: ar
    owner: tax
    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"
    rule: "built (erp-brick-tax compute_tax: lines, tax_point, bp_id, currency, document_ref, treatment_code, prices_include_tax, fx_rate); v4 adds direction, pinned lines, ship_to_country and self_billed; ar sends document_ref invoice_id; a deposit deduction, a settlement-discount credit and a correcting credit note send pinned lines (TAX-47); invoicing never applies a rate"
    status: aligned 2026-10-22 with ar AR-15
  - story: TAX-20
    with: sales-order
    owner: tax
    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"
    rule: "built (erp-brick-tax compute_tax: lines, tax_point, bp_id, currency, document_ref, treatment_code, prices_include_tax, fx_rate); v4 adds direction, pinned lines, ship_to_country and self_billed; 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"
    status: aligned 2026-10-22 with sales-order SO-40
  - story: TAX-23
    with: payments
    owner: tax
    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"
    rule: "built (erp-brick-tax compute_tax: lines, tax_point, bp_id, currency, document_ref, treatment_code, prices_include_tax, fx_rate); v4 adds direction, pinned lines, ship_to_country and self_billed; payments sends document_ref pay_cash:<cash_journal_id>:<day>:<seq> | pay_line:<line_id> with direction purchase; reclaimable only with the receipt image kept"
    status: aligned 2026-10-22 with payments PAY-26
  - story: TAX-11
    with: purchasing
    owner: tax
    route: POST /documents/{document_ref}/freeze
    permission: tax:document_tax:compute
    request: "{contents (optional): {invoice_number, supplier_name, supplier_address, supplier_vat_number, customer_name}}"
    response: "200 the document view, status frozen (a second freeze answers the same); 409 {gates: [{gate, met, reason, fix}]} unless every gate is met"
    rule: "built (erp-brick-tax freeze_document_tax, idempotent): purchasing freezes a bill's tax at approve_bill"
    status: aligned 2026-10-22 with purchasing PUR-28
  - story: TAX-23
    with: purchasing
    owner: tax
    route: GET /parties/{bp_id}
    permission: tax:code:read
    request: path bp_id
    response: "200 {bp_id, current: {treatment_code, vat_number, valid_from} | null, rows: [{treatment_code, vat_number, valid_from}]}"
    rule: "built (erp-brick-tax get_party_tax): the supplier's treatment and VAT number on file, shown on the bill"
    status: aligned 2026-10-22 with purchasing PUR-28
  - story: TAX-39
    with: purchasing
    owner: tax
    route: GET /cis/subcontractors/{bp_id}
    permission: tax:cis:read
    request: path bp_id; query on (the pay date)
    response: "200 {bp_id, utr, verification_number, status (gross | net | unmatched), rate_pct (0 | 20 | 30), verified_on, readiness: [{gate, met, reason, fix}]}; 404 when not a CIS subcontractor"
    rule: purchasing's cis_verified gate at propose_run and the rate it proposes on the labour share; the deduction itself is computed here at POST /cis/deductions
    status: aligned 2026-10-22 with purchasing PUR-61
  - story: TAX-39
    with: purchasing
    owner: tax
    route: POST /cis/deductions/{payment_ref}/reverse
    permission: tax:cis:deduct
    request: "{bp_id, reason, reversed_on}"
    response: "200 {payment_ref, bp_id, status: reversed, tax_month}; 200 the same when already reversed; 409 {gate: cis_return_open, reason, fix} once the month is submitted"
    rule: transition reverse_cis_deduction, called at purchasing's reject_payment; a reversal in a submitted month is refused and corrected in the next return
    status: aligned 2026-10-22 with purchasing PUR-61
  - story: TAX-32
    with: payments
    owner: tax
    route: GET /vat-returns/liabilities
    permission: tax:vat_return:read
    request: none
    response: "200 {liabilities: [{period_key, charge_type, outstanding_amount, due_date}], cis_due: [{tax_month, amount, due_date}]}"
    rule: "TAX-32's liability view as data: the VAT and CIS payments due; payments matches an HMRC debit on the statement to the liability it pays (PAY-21) and forecasts them (PAY-29)"
    status: aligned 2026-10-22 with payments PAY-21, PAY-29
  - story: TAX-11
    with: ar
    owner: tax
    route: POST /documents/{document_ref}/check-contents
    permission: tax:document_tax:compute
    request: "{contents: {title, invoice_number, issue_date, supplier_name, supplier_address, customer_name, customer_address} (each optional; ar sends what it has, never the supplier VAT number: tax holds it)}; direction is optional (default sale)"
    request_schema:
      - field: document_ref
        type: string
        required: true
        in: path
      - field: contents
        type: object
        required: false
      - field: direction
        type: string
        required: false
        values:
          - sale
          - purchase
    response: "{document_ref, status, ready, title, gates: [{gate, met, reason, fix}]}"
    rule: "ar asks before it claims an invoice number: before issue its own number_series gate answers for the number, so tax's invoice_number gate is left out of what ar shows; document_ref = the invoice_id"
    status: added 2026-10-23, seam-gap PR
  - story: TAX-11
    with: ar
    owner: tax
    route: POST /documents/{document_ref}/freeze
    permission: tax:document_tax:compute
    request: "{contents (optional): {title, invoice_number, issue_date, supplier_name, supplier_address, customer_name, customer_address}}"
    request_schema:
      - field: document_ref
        type: string
        required: true
        in: path
      - field: contents
        type: object
        required: false
    response: "200 the document view, status frozen (a second freeze answers the same); 409 {gates: [{gate, met, reason, fix}]} unless every gate is met"
    rule: ar freezes the tax at issue, with the invoice number it just claimed; idempotent, so a retried issue freezes once
    status: added 2026-10-23, seam-gap PR
  - story: TAX-05
    with: ar
    owner: tax
    route: GET /parties/{bp_id}
    permission: tax:code:read
    request: path bp_id
    request_schema:
      - field: bp_id
        type: bp_id
        required: true
        in: path
    response: "200 {bp_id, current: {treatment_code, vat_number, valid_from} | null, rows: [{treatment_code, vat_number, valid_from}]}; 404 when no treatment is recorded for the customer"
    rule: ar reads only current.treatment_code (None when unknown) to default a draft invoice's treatment
    status: added 2026-10-23, seam-gap PR
  - story: TAX-15
    with: ar
    owner: tax
    route: GET /migration-map/{db}/{model}?ids=
    permission: tax:code:read
    request: path db (the Odoo database), model account.tax; 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:
          - account.tax
      - field: ids
        type: array
        required: true
        in: query
        items:
          - integer
    response: "200 [{odoo_model, odoo_id, ours: tax_code}]; an id not migrated is omitted, never a 404"
    rule: the one map route (shared.yaml conventions.odoo_migration.map_route); ar resolves each Odoo account.tax on a carried invoice line to a tax_code through it, so tax's migration runs before ar's
    status: added 2026-10-23, seam-gap PR
  - story: TAX-53
    with: pos
    owner: tax
    direction: inbound
    route: POST /documents/compute
    permission: tax:document_tax:compute
    request: "{document_ref: \"pos:<receipt_id>\", direction: sale, tax_point (the business date), currency, treatment_code (uk_consumer, or the account customer's with bp_id), bp_id (optional: an account or invoiced customer), prices_include_tax: true, ship_to_country (the shop's country), lines: [{line_no, description, category_code, supply: goods | services, consumption (eat_in | takeaway; v6, TAX-51), amount, quantity, unit_price, pinned_from (a refund: \"pos:<original receipt_id>\"), tax_code (with pinned_from)}]}"
    request_schema:
      - field: document_ref
        type: string
        required: true
      - field: direction
        type: string
        required: true
        values:
          - sale
      - field: tax_point
        type: date
        required: true
      - field: currency
        type: currency
        required: true
      - field: treatment_code
        type: string
        required: false
      - field: bp_id
        type: bp_id
        required: false
      - field: prices_include_tax
        type: boolean
        required: true
      - field: ship_to_country
        type: string
        required: true
      - field: lines
        type: array
        required: true
        items:
          - field: line_no
            type: integer
            required: true
          - field: description
            type: string
            required: false
          - field: category_code
            type: tax_category
            required: true
          - field: supply
            type: string
            required: true
            values:
              - goods
              - services
          - field: consumption
            type: string
            required: false
            values:
              - eat_in
              - takeaway
          - field: amount
            type: decimal
            required: true
          - field: quantity
            type: decimal
            required: true
          - field: unit_price
            type: decimal
            required: true
          - field: pinned_from
            type: string
            required: false
          - field: tax_code
            type: tax_code
            required: false
    response: "{document_ref, status, lines: [{line_no, tax_code, rate_pct, consumption, net, vat, gross}], summary: [{tax_code, rate_pct, net, vat, gross}], totals: {net, vat, gross, method}, gates: [{gate, met, reason, fix}], version}"
    rule: "TAX-53: no bp_id for an anonymous sale, the treatment named instead; TAX-51: consumption decides the rate where the rules distinguish it; a refund pins the original's code and rate; pos stores the answer as its copy"
    status: added 2026-10-25 (v6) for pos v1 POS-28, POS-08
  - story: TAX-52
    with: pos
    owner: tax
    direction: inbound
    route: GET /rates?country=&categories=&on=&consumption=&treatment_code=
    permission: tax:code:read
    request: "query country (ISO 3166-1 alpha-2), categories (comma-separated tax categories, at most 200), on (YYYY-MM-DD, the business date), consumption (eat_in | takeaway, optional: both when absent), treatment_code (optional: walk_in_treatment_code)"
    request_schema:
      - field: country
        type: string
        required: true
        in: query
      - field: categories
        type: array
        required: true
        in: query
        items:
          - tax_category
      - field: on
        type: date
        required: true
        in: query
      - field: consumption
        type: string
        required: false
        in: query
        values:
          - eat_in
          - takeaway
      - field: treatment_code
        type: string
        required: false
        in: query
    response: "200 {country, on, treatment_code, valid_until (YYYY-MM-DD or null), rates: [{category_code, supply, consumption (eat_in | takeaway | any), tax_code, rate_pct (string, percent), rule_valid_from, rate_valid_from}], missing: [category_code]}"
    rule: "TAX-52: derived from tax_rule and tax_rate in force on `on`, sale direction; a snapshot for selling offline only, never a frozen answer: the receipt is recomputed at sync (POST /documents/compute)"
    status: added 2026-10-25 (v6) for pos v1 POS-30
  - story: TAX-53
    with: expenses
    owner: tax
    direction: inbound
    route: POST /documents/compute
    permission: tax:document_tax:compute
    request: "{document_ref: \"exp:<report_id>:<line_no>\", direction: purchase, tax_point (the expense date), currency (the receipt's), treatment_code (the merchant's: uk_business unless the receipt shows otherwise), prices_include_tax: true, fx_rate (optional: the line's frozen rate), lines: [{line_no: 1, description, category_code (the expense category's tax category), supply, amount, quantity: \"1\", unit_price}]}"
    request_schema:
      - field: document_ref
        type: string
        required: true
      - field: direction
        type: string
        required: true
        values:
          - purchase
      - field: tax_point
        type: date
        required: true
      - field: currency
        type: currency
        required: true
      - field: treatment_code
        type: string
        required: true
      - field: prices_include_tax
        type: boolean
        required: true
      - field: fx_rate
        type: decimal
        required: false
      - field: lines
        type: array
        required: true
        items:
          - field: line_no
            type: integer
            required: true
          - field: description
            type: string
            required: false
          - field: category_code
            type: tax_category
            required: true
          - field: supply
            type: string
            required: true
            values:
              - goods
              - services
          - field: amount
            type: decimal
            required: true
          - field: quantity
            type: decimal
            required: true
          - field: unit_price
            type: decimal
            required: true
    response: "{document_ref, status, lines: [{line_no, tax_code, rate_pct, net, vat, gross, vat_reclaimable, vat_non_reclaimable}], totals: {net, vat, gross, vat_reclaimable, vat_non_reclaimable}, gates: [{gate, met, reason, fix}], version}"
    rule: "TAX-53: a merchant is not a business partner, so bp_id is absent and the treatment named; the purchase rules apply as for a supplier bill (TAX-23); expenses stores the answer"
    status: added 2026-10-25 (v6) for expenses v1 EXP-18
  - story: TAX-50
    with: expenses
    owner: tax
    direction: inbound
    route: POST /documents/{document_ref}/check-contents
    permission: tax:document_tax:compute
    request: "{direction: purchase, contents: {invoice_number (the receipt's), issue_date, supplier_name, supplier_address (the address shape), supplier_vat_number, customer_name (optional on a less detailed invoice)}}"
    request_schema:
      - field: document_ref
        type: string
        required: true
        in: path
      - field: direction
        type: string
        required: true
        values:
          - purchase
      - field: contents
        type: object
        required: true
        items:
          - field: invoice_number
            type: string
            required: true
          - field: issue_date
            type: date
            required: true
          - field: supplier_name
            type: string
            required: true
          - field: supplier_address
            type: object
            required: true
          - field: supplier_vat_number
            type: string
            required: false
          - field: customer_name
            type: string
            required: false
    response: "{document_ref, status, ready, title (full_invoice | less_detailed_invoice), gates: [{gate, met, reason, fix}]}"
    rule: "TAX-50: at or under simplified_invoice_threshold (gross including VAT) the less detailed invoice's particulars suffice; above it, customer_name is required; a receipt failing a gate has its VAT made non-reclaimable by expenses (EXP-11)"
    status: added 2026-10-25 (v6) for expenses v1 EXP-18
external_services:
  - service: HMRC VAT (MTD) API v1.0
    base: "https://api.service.hmrc.gov.uk (sandbox https://test-api.service.hmrc.gov.uk), Accept: application/vnd.hmrc.1.0+json, OAuth 2.0 user-restricted, scopes read:vat write:vat"
    calls:
      - GET /organisations/vat/{vrn}/obligations?from=&to=&status=
      - POST /organisations/vat/{vrn}/returns
      - GET /organisations/vat/{vrn}/returns/{periodKey}
      - GET /organisations/vat/{vrn}/liabilities?from=&to=
      - GET /organisations/vat/{vrn}/payments?from=&to=
    stories:
      - TAX-26
      - TAX-27
      - TAX-30
      - TAX-31
      - TAX-32
    rule: every call carries the fraud-prevention headers (TAX-31); the tokens live in the platform's secret store
  - service: HMRC Check a UK VAT number API v2.0
    calls:
      - GET /organisations/vat/check-vat-number/lookup/{targetVrn}/{requesterVrn}
    stories:
      - TAX-13
  - service: HMRC CIS online (verification and the CIS300 monthly return)
    calls:
      - verification request and CIS300 submission over HMRC's CIS online filing
    stories:
      - TAX-38
      - TAX-40
    rule: the same HMRC connection; where the business has no online filing credential, a person verifies on HMRC's CIS service and enters the verification number
  - service: HMRC EC sales list and Intrastat online services
    calls:
      - "none: HMRC offers upload screens, no API; the brick produces the file and a person records the submission"
    stories:
      - TAX-42
      - TAX-43
tool_names:
  - tool: accept_tax_suggestion
    route: POST /documents/{document_ref}/lines/{line_no}/accept-suggestion
    was: accept_suggestion
  - tool: reconcile_tax_migration
    route: POST /migration/odoo/reconcile
    was: reconcile_odoo
screens:
  - id: tax_codes
    name: Tax codes
    stories:
      - TAX-02
      - TAX-03
    actors:
      - tax_admin
  - id: tax_rules
    name: Tax rules
    stories:
      - TAX-04
    actors:
      - tax_admin
  - id: customer_tax
    name: Customer tax
    stories:
      - TAX-05
      - TAX-46
    actors:
      - biller
      - tax_admin
    note: "v4: HMRC's check result and the name HMRC holds; the construction end-user notice; CIS registration"
  - id: document_tax
    name: Document tax
    stories:
      - TAX-06
      - TAX-08
      - TAX-09
    actors:
      - biller
      - tax_admin
    note: each line's code, the rule or person that chose it, an open AI suggestion with accept / reject, and the readiness gates {gate, met, reason, fix}
  - id: vat_returns
    name: VAT returns
    stories:
      - TAX-28
      - TAX-29
      - TAX-30
      - TAX-32
      - TAX-34
      - TAX-36
      - TAX-37
      - TAX-48
      - TAX-49
    actors:
      - tax_admin
      - owner
    note: "v4: obligations with their due dates; a return's nine boxes, each drilling to its entries; adjustments and VAT652 notices; bad debt claims; the declaration and submit button with readiness; HMRC's receipt; liabilities and payments"
  - id: cis
    name: CIS
    stories:
      - TAX-38
      - TAX-40
    actors:
      - tax_admin
      - owner
    note: "v4: subcontractors and their verification; deductions per tax month; the CIS300 and the statements; CIS suffered as a subcontractor"
  - id: trade_declarations
    name: Trade declarations
    stories:
      - TAX-42
      - TAX-43
    actors:
      - tax_admin
  - id: import_vat
    name: Import VAT
    stories:
      - TAX-45
    actors:
      - tax_admin
    note: "v4: import entries by MRN; the monthly postponed import VAT statement with each line matched or explained"
  - id: settings
    name: Tax settings
    stories:
      - TAX-01
      - TAX-07
      - TAX-14
      - TAX-26
    actors:
      - tax_admin
      - owner
    note: "every config_row below: registration, rounding method, prices-include-VAT default, document wording, AI step modes; the controls section is shown to the owner only"
permissions:
  namespace: tax
  catalog:
    - tax:code:read
    - tax:code:write
    - tax:category:write
    - tax:registration:write
    - tax:party_tax:write
    - tax:document_tax:override
    - tax:document_tax:approve_override
    - tax:settings:write
    - tax:settings:controls
    - tax:code:approve
    - tax:code:seed
    - tax:document_tax:compute
    - tax:document_tax:suggest
    - tax:history:import
    - tax:migration:read
    - tax:cis:read
    - tax:hmrc:connect
    - tax:vat_return:read
    - tax:vat_return:prepare
    - tax:vat_return:submit
    - tax:vat_adjustment:write
    - tax:bad_debt:claim
    - tax:cis:write
    - tax:cis_return:submit
    - tax:trade_declaration:write
    - tax:import_vat:write
    - tax:partial_exemption:write
    - tax:obligation:sync
    - tax:vat_number:check
    - tax:tax_point:read
    - tax:cis:deduct
    - tax:cis:record_suffered
    - tax:import_vat:record
    - tax:bad_debt:suggest
  machine:
    - tax:code:seed
    - tax:document_tax:compute
    - tax:document_tax:suggest
    - tax:history:import
    - tax:migration:read
    - tax:obligation:sync
    - tax:vat_number:check
    - tax:tax_point:read
    - tax:cis:deduct
    - tax:cis:record_suffered
    - tax:import_vat:record
    - tax:bad_debt:suggest
  composition_roles: ar's service client holds tax:document_tax:compute and tax:tax_point:read; purchasing's holds tax:document_tax:compute, tax:cis:deduct and tax:import_vat:record; payments' holds tax:cis:record_suffered; tax's own service client holds pay:receipt:read, ar:invoice:read, purchasing:bill:read, product:product:read and gl:journal:post / gl:fx:read (v4)
  decided_by: "permissions only, never a role's name: a composition maps its own roles to these"
  row_visibility:
    rule: everyone who can see a document sees its tax; configuration is the tax admin's
    enforced: in the use cases; a document's tax is read through the document's own module
    not_found_not_forbidden: true
config_rows:
  - table: tax_registration
    changes: whether and from when we are VAT registered, the VAT number, the scheme
  - table: tax_code
    changes: the codes, their names and the wording printed on the document (the reverse-charge legend)
  - table: tax_rate
    changes: rates from a date
  - table: tax_category
    changes: how products are taxed (the categories a product may carry)
  - table: tax_treatment
    changes: how customers are taxed, and which treatments need a VAT number
  - table: tax_rule
    changes: which code a (category, treatment, goods or services, sale or purchase) combination gets
  - table: tax_statutory
    changes: "v4: the figures the law sets, from a date: cash accounting join 1,350,000 / leave 1,600,000; flat rate join 150,000 / leave 230,000 and the rate per sector; limited cost trader 16.5%, 2% / 1,000 a year; error correction 10,000 / 50,000 / 1%; CIS rates 0 / 20 / 30; partial exemption de minimis 625 a month; EC sales list quarterly limit 35,000; Intrastat NI arrivals 500,000, dispatches 250,000"
  - table: tax_cis_subcontractor
    changes: "v4: each subcontractor's verification from a date"
  - table: tax_settings
    changes: how this business computes VAT
    settings:
      - key: rounding_method
        type: str
        default: per_line_nearest
        changes: "how VAT is rounded: per_line_nearest (para 17.5.1, the default), per_line_down_0_1p (17.5.1), per_invoice_round_down (17.5)"
      - key: prices_include_tax
        type: bool
        default: false
        changes: whether a new price list's prices include VAT (each list can say otherwise)
      - key: retailer
        type: bool
        default: false
        changes: "whether we are a retailer: the round-down methods are then refused (para 17.6)"
      - key: simplified_invoice_threshold
        type: int
        default: 250
        changes: the GBP total at or below which a simplified invoice is allowed, with the customer's agreement (para 16.6.1)
      - key: walk_in_treatment_code
        type: str
        default: uk_consumer
        changes: "v6: the treatment of an anonymous buyer (a till sale with no partner, TAX-52, TAX-53)"
      - key: ai.suggest_code.mode
        type: str
        default: suggest
        changes: "the AI code suggestion: off | suggest (ai_steps)"
      - key: tax_changes_need_second_person
        type: bool
        default: false
        changes: whether a rate, rule or registration change waits for a second holder of tax:code:approve (TAX-14); tax:settings:controls
      - key: override_approval
        type: str
        default: second_person
        changes: "who approves an override that lowers tax: second_person, or self_with_reason for a firm of one (TAX-06); tax:settings:controls"
      - key: vat_return_needs_second_person
        type: bool
        default: true
        changes: "v4: whether the person who locked a VAT return may not submit it (identity by email AND sub); a firm of one sets false; tax:settings:controls"
      - key: hmrc_environment
        type: str
        default: sandbox
        changes: "v4: sandbox | production: which HMRC base URL is called; production only after the fraud-header test passed; tax:settings:controls"
      - key: vat_number_check_days
        type: int
        default: 90
        changes: "v4: a VAT-number check older than this is re-run before the next reverse-charge or overseas document issues"
      - key: ai.review_vat_return.mode
        type: str
        default: suggest
        changes: "v4: the AI review of a draft return: off | suggest"
      - key: ai.check_vat_number.mode
        type: str
        default: suggest
        changes: "v4: the AI name comparison on a checked VAT number: off | suggest"
      - key: cis_contractor_utr
        type: str
        default: ""
        changes: "v4: our UTR and accounts office reference as a CIS contractor; empty = we are not a contractor"
in_code_not_rows:
  - "the rounding methods themselves (para 17.5 / 17.5.1 / 17.5.2 / 17.6): a row chooses one, code implements each, and net + VAT = total under all of them"
  - that tax is frozen at issue and an issued document is never recomputed
  - that a dated row in effect is never edited or deleted, and a change starts after today in business_timezone; only a key's first row may carry an earlier date
  - that a pair no rule covers is refused, never defaulted to zero
  - that a business not registered charges no VAT and its document is not titled VAT invoice
  - that reverse charge charges nothing and prints its legend; that it needs a VAT number
  - the invoice-content checklist (para 16.3.1)
  - "v4: the nine boxes and which code feeds which box; that a box is a SUM of entries and a document's tax enters one return once"
  - "v4: that a submitted return is immutable and a correction is an adjustment on a later return or a VAT652 notice"
  - "v4: the fraud-prevention header set; that submitting is a person's declaration"
  - "v4: the bad debt relief conditions and the VAT-fraction arithmetic; the cash-basis and flat-rate computations; the partial-exemption tests and rounding"
  - "v4: the CIS deduction on labour only, the tax month 6th to 5th, gross / net / unmatched"
  - "v4: that the figures the law sets are dated tax_statutory rows read on the date they apply to"
ai_steps:
  - key: ai_suggest_code
    benefit: a free-text line or a new kind of supply gets a reasoned code instead of a guess; the reason is kept for the accountant
    mode: suggest
    modes_allowed:
      - off
      - suggest
    safe_for_auto: false
    inputs:
      - the line description
      - the customer's treatment
      - the codes and their descriptions
      - the rules
    output: a tax code, a confidence, and the reason in one sentence citing the rule or the VAT guide section
    fallback: the line is refused until a person chooses a code
    accepted_by: the biller, on Document tax (TAX-09); an accepted code that lowers tax waits for approval as any override
    consent: off until the tax admin turns it on (ai.suggest_code.mode); the line text and the customer's treatment go to a sovereign model, no other customer data
    audit: each suggestion kept with its inputs, the model, the output, the reason and who accepted or rejected it, and when
    eval: lines with an accountant's code; accuracy, and zero tolerance for suggesting a lower rate than the label
  - key: check_vat_number
    benefit: a reverse charge on a customer who is not registered is a VAT debt for the supplier; checking costs nothing
    mode: suggest
    modes_allowed:
      - off
      - suggest
    consent: "v4 (un-deferred, for the re-sign): the HMRC check runs regardless; the AI comparison of HMRC's name and address with the partner's is on in suggest mode, flagged for the biller, never changes the treatment"
    accepted_by: "the biller or tax admin on Customer tax: a flagged mismatch is confirmed or the number corrected"
    safe_for_auto: false
    inputs:
      - the VAT number
      - the HMRC check result
      - the customer's name and address
    output: valid / invalid / could not check, and a name mismatch flag explained in a sentence
    fallback: a person confirms the number
    eval: numbers with known status and name matches; mismatch-flag precision
    note: the check itself is a service call, not AI; the AI part is the name-and-address comparison
  - key: ai_review_vat_return
    benefit: a box that moved far from the last four periods, a document with an unusual code or a large one-off is looked at before HMRC sees it
    mode: suggest
    modes_allowed:
      - off
      - suggest
    safe_for_auto: false
    inputs:
      - the draft boxes
      - the last four returns
      - the entries above a size
      - their codes
    output: a short list of findings, each with the evidence (e.g. 'box 4 up 2.6x on the last four quarters; three bills from one supplier make 70%')
    fallback: the tax admin reviews without findings
    accepted_by: the tax admin dismisses or acts on each; locking never waits on a finding
    consent: ai.review_vat_return.mode; the figures go to a sovereign model, no customer names
    audit: "each finding kept with the return: model, inputs digest, evidence, decision, who, when"
    eval: past returns with seeded errors (a doubled bill, a wrong code); recall, false findings per return
tests:
  acceptance: one per story id above, named for it
  access:
    - a biller reads codes and a document's tax, overrides with a reason, and cannot approve an override that lowers tax
    - only the tax admin writes codes, rates, rules, registration and settings
    - only tax:settings:controls changes tax_changes_need_second_person or override_approval; tax:settings:write is refused on them
    - the machine permissions are held only by the system's service client; a wildcard grant does not reach them
    - "v4: only tax:vat_return:submit submits, only tax:hmrc:connect connects; a service client holding tax:vat_return:submit is refused (a declaration is a person's)"
    - "v4: tax:tax_point:read, tax:cis:deduct, tax:cis:record_suffered and tax:import_vat:record are exact grants to the calling brick's client"
  invariants:
    - net + VAT = total, and the per-rate summary sums to the VAT total, under every rounding method and rate mix
    - a document's tax on an issued document never changes after a rate change
    - the rate charged is the rate valid on the tax point date
    - a (category, treatment) with no rule is refused, never 0%
    - reverse charge charges 0, records the VAT due, and prints the legend
    - a business not registered on the tax point date charges no VAT
    - "compute() is deterministic: the same inputs give the same bytes"
    - "'today' is the date in business_timezone; a rate, rule, treatment, registration or setting change dated today or earlier is refused, except a key's first row"
    - a dated row in effect is never edited or deleted; a withdrawn row never takes effect
    - "direction defaults to sale: every v2 call gives the same bytes under v3"
    - a purchase is determined only by purchase rules and the SUPPLIER's treatment; a sale only by sale rules and the customer's; a pair with no rule of the direction is refused, never 0%
    - on a purchase, vat_reclaimable + vat_non_reclaimable = vat per line and in total, split by the code's reclaimable_pct (100 or 0), exact to the penny
    - a purchase reverse charge charges 0 and records the same VAT due as output and as input (reclaimable per reclaimable_pct), so a fully reclaimable one nets to 0.00
    - check-contents with direction purchase checks the supplier's name, address and VAT number and refuses supplier_vat_number when it is absent; with direction sale it checks ours, as v2
    - the Odoo migration carries type_tax_use = purchase taxes as purchase codes and rules, and GET /migration-map/{db}/{model}?ids= answers [{odoo_model, odoo_id, ours}], omitting an id not migrated
    - every refused transition returns its unmet gates as {gate, met, reason, fix}
    - no AI suggestion reaches a document without a person's acceptance
    - "v4: box 3 = box 1 + box 2 and box 5 = |box 3 - box 4| exactly; boxes 6-9 are whole pounds; every box equals the SUM of its entries"
    - "v4: a document's tax enters exactly one VAT return per tax code, even under two concurrent preparations (vat_return_entry primary key, plain INSERT claim)"
    - "v4: a submitted return never changes; HMRC is never sent the same periodKey twice (a timeout is settled by a read first)"
    - "v4: submit is refused to the identity that locked the return when vat_return_needs_second_person, matched by email AND by sub (a second login of the same person is refused)"
    - "v4: tax-point-status answers filed true for every date in a submitted return and met false for a locked one"
    - "v4: bad debt relief is claimed once per invoice, never before six months, and every later receipt repays its VAT fraction once"
    - "v4: under cash accounting, sum of VAT taxed over all periods = the invoices' VAT x the fraction received, exact to the penny"
    - "v4: a CIS deduction is rate x (gross ex VAT - materials), on [payment_ref, bp_id] once; the CIS300 total equals the sum of the month's deductions"
    - "v4: postponed import VAT nets to 0.00 for a fully taxable business (box 1 and box 4 equal), and its value is in box 7 never box 6"
    - "v4: a pinned line takes the earlier document's frozen rate, and pinned lines never exceed the earlier document's net per code"
    - "v4: 'today' in business_timezone decides every 'after today' and 'period ended' gate; an obligation's dates are HMRC's"
    - "v4: a statutory figure is read from the tax_statutory row in force on the date it applies to"
    - "v4: amounts in a return out of NUMERIC(18,2) range are refused 422, never truncated"
    - the Odoo migration run twice writes nothing the second time, and never changes an issued document's tax
    - "v4: a CIS deduction is keyed [payment_ref, bp_id]; its reversal is one row, refused once the tax month is submitted; ship_to_country, when sent, decides the place of supply of goods lines and self_billed marks a purchase document we issued (content gates read OUR self-billing series)"
  scenarios:
    - id: SC-TAX-01
      name: the rounding methods agree with net + VAT = total
      stories:
        - TAX-07
        - TAX-10
      given: three lines of 10.03 at 20%
      when: computed under each method
      then: VAT 6.01, 6.03 and 6.01; totals 36.10, 36.12 and 36.10; the retail flag refuses the two round-down methods
    - id: SC-TAX-02
      name: a rate change between two invoices
      stories:
        - TAX-03
        - TAX-11
      given: S 20% to 2027-03-31, 21% from 2027-04-01
      when: one invoice has tax point 2027-03-31 and one 2027-04-01, and both are re-read after the change
      then: 20% and 21%; neither changes later
    - id: SC-TAX-03
      name: reverse charge for a construction contractor
      stories:
        - TAX-04
        - TAX-05
        - TAX-12
      given: category construction_service, customer treatment uk_cis_contractor with the VAT number the biller recorded
      when: an invoice of 1,000.00 is computed and issued
      then: code RC, VAT charged 0.00, VAT due 200.00 recorded, the legend printed; the treatment refuses to save without a VAT number (the HMRC check is M2)
    - id: SC-TAX-04
      name: not registered yet
      stories:
        - TAX-01
        - TAX-12
      given: registration from 2027-01-01
      when: invoices with tax points 2026-12-31 and 2027-01-01 are issued
      then: the first charges no VAT and is not titled VAT invoice; the second charges VAT and shows the number
    - id: SC-TAX-05
      name: mixed rates on one invoice
      stories:
        - TAX-10
      given: lines at S, Z and E
      when: computed
      then: one summary row per code; Z and E show no VAT and separate totals (para 16.5)
    - id: SC-TAX-06
      name: no back-dating
      stories:
        - TAX-03
        - TAX-04
        - TAX-05
        - TAX-14
      given: S at 20%, customer 7311 as uk_business, business_timezone Europe/London, today 2026-11-02
      when: a 21% rate from 2026-11-02, a rule change from 2026-11-01 and a treatment change for 7311 from today are tried; then the same from 2026-11-03
      then: "the first three are refused with {gate: starts_after_today, met: false}; the second three are saved; an invoice with tax point 2026-11-02 still charges 20% as uk_business"
    - id: SC-TAX-07
      name: an AI suggestion is a person's decision
      stories:
        - TAX-09
        - TAX-12
      given: a line no rule covers, ai.suggest_code.mode suggest
      when: the AI suggests a code and issue is asked before anyone accepts it
      then: "issue is refused with {gate: no_open_suggestion, met: false}; after the biller accepts, the line carries the code, the reason and who accepted, and issue proceeds"
    - id: SC-TAX-09
      name: a quarter prepared, locked and submitted
      stories:
        - TAX-27
        - TAX-28
        - TAX-30
        - TAX-31
        - TAX-33
      given: obligation 26AD open; sale and purchase documents frozen in the quarter; a late bill of the previous quarter; HMRC sandbox
      when: the return is prepared twice concurrently, locked, submitted by the same person, then by a second person; then ar asks the status of a tax point in the quarter
      then: each document counted once; the same person's submit is refused (second_person), the second person's is accepted with HMRC's receipt; tax-point-status answers filed true
    - id: SC-TAX-10
      name: error correction within and above the threshold
      stories:
        - TAX-29
      given: box 6 of 400,000
      when: adjustments of 3,200.00 and 12,000.00 are recorded
      then: the first is on the return; the second is refused and recorded as a VAT652 notice
    - id: SC-TAX-11
      name: bad debt relief and repayment
      stories:
        - TAX-34
        - TAX-35
      given: an unpaid invoice written off, six months passed, VAT accounted
      when: relief is claimed, then a part receipt arrives and the next return is prepared
      then: 120.00 in box 4, then 60.00 in box 1; a second claim on the invoice is refused
    - id: SC-TAX-12
      name: cash accounting and flat rate
      stories:
        - TAX-36
        - TAX-37
      given: cash basis from a period start; a flat-rate business in its first year with goods below 2% of turnover
      when: the returns are prepared
      then: VAT follows the receipts; the flat rate is 15.5% (16.5% less 1%) of gross turnover with the capital item in box 4
    - id: SC-TAX-13
      name: CIS on both sides
      stories:
        - TAX-38
        - TAX-39
        - TAX-40
        - TAX-41
      given: a verified net subcontractor and a contractor customer
      when: a subcontractor payment of 5,000.00 with 1,000.00 materials is made and a customer pays our 2,000.00 invoice net of 400.00
      then: 800.00 deducted and on the CIS300; 400.00 suffered recorded; an unverified subcontractor's payment is refused its deduction until verified
    - id: SC-TAX-14
      name: imports by postponed accounting
      stories:
        - TAX-44
        - TAX-45
      given: two import entries and a monthly statement with three lines
      when: the statement is reconciled
      then: lock is refused until the third line is explained; box 1 and box 4 carry 2,000.00 each, box 7 the value
    - id: SC-TAX-15
      name: a deposit deducted after a rate change
      stories:
        - TAX-47
      given: a deposit frozen at 20%, S at 21% from a later date
      when: a final invoice deducts 2,000.00, and another tries to deduct more than remains
      then: the deduction carries 20%; the second is refused pinned_within_original
    - id: SC-TAX-08
      name: the Odoo migration reconciles and re-runs clean
      stories:
        - TAX-15
      given: an Odoo company with the UK sale taxes and three fiscal positions, the door answered
      when: the migration runs twice
      then: every migration.odoo.reconcile check is equal or explained; the second run writes nothing
scale:
  reads: "compute() reads the rules, the rates and the customer's treatment: three small reads per document, cacheable per request"
  hot_paths:
    - compute() on every line edit of a quote, order or invoice
  workers: none
  volumes: rules and codes are dozens of rows; there is no volume concern
customer_varies:
  - question: "v6: Do you sell food or drink that is eaten in or taken away, in a country whose rate depends on it (DE, FR, AT)?"
    changes: tax rules with consumption (TAX-51), the till's eat-in / takeaway choice (pos POS-08)
    default: no distinction (consumption any) until a country pack or the tax admin adds the eat_in and takeaway rules; a line of a category that distinguishes them and says neither is refused, never defaulted (chosen 2026-10-25)
  - question: "v6: Do you reclaim VAT on small receipts without your company's name on them?"
    changes: simplified_invoice_threshold, TAX-50
    default: yes, up to 250.00 GBP including VAT (VAT Notice 700 para 16.6.1), the UK standard default
  - question: Are you VAT registered, and from when?
    changes: tax_registration; before the date, no VAT and no "VAT invoice" title
    standard: HMRC VAT Notice 700 para 16.3.1 (what a VAT invoice shows) applies only once registered
  - question: What do you sell, and to whom (UK businesses, consumers, overseas)?
    changes: tax_category, tax_treatment and the rules that join them
    typical:
      uk_b2b_services: four rules (standard to UK, outside the scope to overseas businesses, standard to overseas consumers, exempt where it applies)
      construction_subcontractor: the domestic reverse charge for CIS-registered contractors who are not end users
      exporter_of_goods: zero-rated exports with proof of export held
  - question: How do you want VAT rounded on invoices?
    changes: tax_settings.rounding_method
    standard: "HMRC VAT Notice 700 para 17.5: total VAT may be rounded down to a whole penny; 17.5.1 per line, down to 0.1p or to the nearest 1p / 0.5p, consistently; 17.6 retailers must not round down"
    typical:
      reference_default: per line, to the nearest penny (17.5.1), decided 2026-10-18
      invoice_traders: per invoice, rounded down (the 17.5 concession), by setting
      retailers: per line, to the nearest penny
      warning: changing the method mid-year makes invoices disagree with earlier ones; change it at a period start
  - question: Do your prices include VAT?
    changes: tax_settings default and each price list's prices_include_tax
  - question: Do you use the flat rate scheme or cash accounting?
    changes: "tax_registration accounting_basis and flat_rate (v4: computed by the return, TAX-36, TAX-37)"
    standard: VAT Notice 731 (cash accounting), 733 (flat rate scheme); limits in tax_statutory
  - question: Who prepares the VAT return, and who submits it to HMRC?
    changes: tax:vat_return:prepare and tax:vat_return:submit; vat_return_needs_second_person
    typical:
      firm_with_a_bookkeeper: the bookkeeper prepares and locks, the owner submits
      firm_of_one: one person, vat_return_needs_second_person false
      with_an_agent: the accountant submits as the owner's nominee (the HMRC grant is the business's)
  - question: Are you a contractor or a subcontractor under CIS?
    changes: cis_contractor_utr; tax_cis_subcontractor; payments' cis_deduction allocations (v4)
    standard: HMRC CIS 340
  - question: Do you move goods between Northern Ireland and the EU, or import goods?
    changes: registration ni_goods; trade declarations; import entries and postponed accounting (v4)
  - question: Do you make exempt supplies as well as taxable ones?
    changes: registration partial_exemption_year_end; purchase codes' attribution (v4, TAX-48)
    standard: VAT Notice 706
variation_points:
  - node: Task_ai_suggest_code
    op: on_off
    default: on, suggest
    depth: 1
    guideline: warn - without it, an uncovered line waits for a person (which is still correct)
  - node: Task_approve_override
    op: re_lane
    default: "the tax admin approves an override that lowers tax, never its author (override_approval: second_person)"
    depth: 1
    guideline: "warn - a lowered rate is the error HMRC assesses; typical: a second person in any firm with a bookkeeper"
  - node: Task_submit_vat_return
    op: narrow
    default: a person makes HMRC's declaration; a second person where vat_return_needs_second_person
    depth: 1
    requirement: refuse - a return is a legal declaration by a person; a service client never submits
  - node: Task_ai_review_vat_return
    op: on_off
    default: on, suggest
    depth: 1
    guideline: warn - without it a doubled bill reaches HMRC unless someone spots it
  - node: Task_check_party_vat_number
    op: on_off
    default: on
    depth: 1
    guideline: warn - a reverse charge on an unregistered customer is the supplier's VAT debt
  - node: Task_freeze
    op: narrow
    default: frozen at issue
    depth: 1
    requirement: refuse - an issued VAT invoice is never recomputed; corrections are credit notes
migration:
  odoo:
    order_note: "payment terms (resolved 2026-10-22, shared.yaml conventions.odoo_migration.payment_terms): sales-order writes ar's own key odoo:<payment_term id>; there is no ar.terms slice, and this slice reads terms only through ar's key"
    reads:
      - model: res.company
        fields:
          - vat
          - country_id
          - account_fiscal_country_id
          - tax_calculation_rounding_method
        filter: the company being migrated
        why: the registration's number and the rounding method; Odoo holds no registration date
      - model: account.tax
        fields:
          - id
          - name
          - description
          - invoice_label
          - amount
          - amount_type
          - type_tax_use
          - tax_scope
          - price_include
          - include_base_amount
          - tax_exigibility
          - tax_group_id
          - country_id
          - active
          - company_id
        filter: company_id = the company AND type_tax_use in ('sale', 'purchase') AND (active OR used on a posted move)
        why: the codes and their rates; archived taxes that a posted invoice used
      - model: account.tax.repartition.line
        fields:
          - tax_id
          - document_type
          - repartition_type
          - factor_percent
          - tag_ids
        filter: tax_id in the taxes read
        why: a +100 / -100 pair of tax lines is a reverse charge (rate due, nothing charged); the tags give the reporting box
      - model: account.account.tag
        fields:
          - id
          - name
          - applicability
          - country_id
        filter: applicability = 'taxes'
        why: the VAT return box each code reports to (reporting_box)
      - model: account.tax.group
        fields:
          - id
          - name
        filter: used by the taxes read
        why: the label on the per-rate summary, for the door's code mapping
      - model: account.fiscal.position
        fields:
          - id
          - name
          - country_id
          - country_group_id
          - vat_required
          - auto_apply
          - active
        filter: company_id = the company
        why: each position is a customer tax treatment
      - model: account.fiscal.position.tax
        fields:
          - position_id
          - tax_src_id
          - tax_dest_id
        filter: position_id in the positions read
        why: the (category, treatment) -> code rules
      - model: product.template
        fields:
          - id
          - taxes_id
          - type
        filter: sale_ok
        why: a product's default sale tax becomes its tax category (product writes it on the product; this module owns the category list)
      - model: res.partner
        fields:
          - id
          - vat
          - country_id
          - is_company
          - property_account_position_id
        filter: customer_rank > 0 OR used on a posted out_invoice / out_refund
        why: each customer's treatment and VAT number
      - model: account.move.line
        fields:
          - move_id
          - date
          - tax_ids
          - tax_line_id
          - tax_tag_ids
          - balance
          - tax_base_amount
        filter: move_type in (out_invoice, out_refund), state = 'posted', the reconcile window
        why: "read-only, for reconcile: history is never recomputed"
      - model: l10n_uk.vat.obligation
        fields:
          - period_key
          - date_start
          - date_end
          - date_due
          - status
        filter: the company (Odoo Enterprise l10n_uk_reports, where installed)
        why: "v4: which periods Odoo filed; the first sync from HMRC is the truth, these only explain a difference"
    maps:
      - from: res.company.vat
        to: registration.vat_number
        rule: "status registered from the date the customer gives at the door; no vat: not_registered as the first row"
      - from: res.company.tax_calculation_rounding_method
        to: settings.rounding_method
        rule: "round_per_line -> per_line_nearest; round_globally has no exact HMRC method (Odoo rounds the total half-up): the door picks one"
      - from: account.tax.type_tax_use
        to: tax_code.direction, tax_rule.direction
        rule: "sale -> sale; purchase -> purchase (v3); reclaimable_pct 100 unless the door names the purchase tax non-reclaimable (Odoo models that in its repartition lines, differently by version: read, then confirmed at the door)"
      - from: account.tax.id
        to: tax_code.tax_code
        rule: the customer's code per tax, proposed from the l10n_uk external id (ST11 -> S, ST2 -> Z ...) and confirmed at the door; kept in tax_migration_map
      - from: account.tax.description|invoice_label
        to: tax_code.description, tax_code.document_wording
        rule: copied; the reverse-charge legend checked at the door
      - from: account.tax.amount
        to: tax_rate.rate_pct
        rule: percent taxes only; charged_pct = rate_pct, or 0 where the repartition lines are a +100 / -100 reverse-charge pair; valid_from = the date given at the door (a first row)
      - from: account.tax.repartition.line.tag_ids
        to: tax_code.reporting_box
        rule: the invoice-side tax tag (+1, +6 ...) names the box
      - from: account.tax.active = false
        to: tax_code lifecycle retired
        rule: an archived tax a posted invoice used is a retired code, so migrated history names a real code
      - from: account.fiscal.position
        to: treatment
        rule: treatment_code from the name, confirmed at the door; needs_vat_number = vat_required; the company default (no position) is uk_business or uk_consumer by partner.is_company
      - from: account.fiscal.position.tax
        to: tax_rule
        rule: (category of tax_src, the position's treatment, supply from tax.tax_scope) -> tax_dest's code; the unmapped default is (category, default treatment) -> the category's own code; first rows, valid_from at the door's date
      - from: product.template.taxes_id
        to: tax_category
        rule: one category per distinct default sale tax (20% S -> standard, 5% R -> reduced, 0% Z -> zero, exempt -> exempt, RC -> construction_service); handed to product's migration for the product rows
      - from: res.partner.vat, property_account_position_id
        to: party_tax
        rule: bp_id from business-partner's migration map; treatment from the position (or the default); the vat as recorded; a first row (valid_from null)
      - from: account.tax.price_include
        to: price list prices_include_tax
        rule: handed to product's price-list migration; tax_settings.prices_include_tax follows the company's sale default
    door:
      - "the date our registration row starts from (Odoo stores none): the HMRC effective date of registration"
      - the code for each Odoo purchase tax, and which purchase codes are non-reclaimable (v3)
      - the code for each Odoo sale tax, and whether archived taxes become retired codes (recommended) or earlier rates of a live code
      - the treatment code for each fiscal position, and the treatment of customers with no position
      - the rounding method from cutover where Odoo used round_globally
      - "the cutover date: the first tax point this module taxes; every migrated rate and rule starts from its real date or that date"
      - "v4: the first VAT period this module files: the obligation after the last one Odoo (or the accountant) submitted; documents with tax points in earlier periods are recorded as entries of an 'odoo' return so they are never counted again"
      - "v4: the scheme and basis in force (cash accounting, flat rate and its sector) from the cutover"
      - "v4: CIS: the subcontractors' current verification (re-verified here or entered from the last CIS300), and the tax month the first CIS return here covers"
      - "what to do with customers whose position needs a VAT number but who have none: record the number, or move them to a consumer treatment"
      - "taxes this module cannot carry (fixed, division, group, python code, include_base_amount): replaced by a percent code, or the migration stops"
    reconcile:
      - check: active sale taxes
        odoo: count account.tax where type_tax_use = sale, active, company
        ours: count tax_code active, via tax_migration_map
        must: equal
      - check: active purchase taxes
        odoo: count account.tax where type_tax_use = purchase, active, company
        ours: count tax_code active with direction purchase, via tax_migration_map
        must: equal
      - check: rate per code
        odoo: account.tax.amount per tax
        ours: tax_rate.rate_pct and charged_pct valid on the cutover date per mapped code
        must: equal
      - check: reporting box per code
        odoo: the invoice-side tax tag per tax
        ours: tax_code.reporting_box
        must: equal
      - check: customers with a VAT number
        odoo: count res.partner with vat, in the migrated set
        ours: count tax_party with vat_number
        must: equal
      - check: treatment per customer
        odoo: property_account_position_id per partner (none = the default)
        ours: tax_party.treatment_code per bp_id, through the treatment map
        must: equal
      - check: determination parity
        odoo: tax_ids on each posted out_invoice line in the last 12 months, by (product, partner)
        ours: determine(category, treatment, supply) for the same pairs
        must: "explained: a difference is a hand-edited line in Odoo, listed by move and line"
      - check: VAT by code, last 12 months
        odoo: SUM(balance) of account.move.line by tax_line_id, posted out_invoice and out_refund
        ours: SUM of the frozen document tax by code on the invoices ar migrated
        must: equal
      - check: VAT return boxes, last filed period
        odoo: the UK tax report boxes 1 and 6 for the period
        ours: SUM by reporting_box over the migrated frozen tax
        must: equal, or explained by a filed adjustment
    not_carried:
      - "purchase bills and their tax: purchasing carries them as recorded, with the tax Odoo froze (this slice carries the purchase taxes themselves, v3)"
      - "fiscal position account mappings and the repartition lines' accounts: the ledger's account map (gl's slice)"
      - "issued invoices and their tax: ar carries them as issued, with the tax Odoo froze; this module never recomputes history"
      - "taxes of amount_type fixed, division, group or code, and include_base_amount (tax on tax): not modelled (known_gaps); the door replaces or stops"
      - "tax groups as records: a label only"
      - "Odoo's VIES check results: v4 re-checks every reverse-charge customer with HMRC after cutover (TAX-13) rather than trusting an old result"
      - "v4: Odoo's submitted VAT returns as documents: the boxes of the last filed period are a reconcile check; HMRC's obligations are re-read"
      - "v4: CIS history (Odoo has no standard CIS): the last CIS300s stay with whoever filed them"
      - "cash-basis exigibility (tax_exigibility on_payment): v4 computes cash accounting from payments' allocations; Odoo's cash-basis moves are not carried"
      - "other companies and other countries' taxes (OSS): one company, the UK pack"
    idempotent_on: "(odoo model, odoo id) -> our natural key, in tax_migration_map: tax_code; [tax_code, valid_from]; treatment_code; [category_code, treatment_code, supply, direction, valid_from]; [bp_id, valid_from]; v4: the 'odoo' return entries on [document_ref, tax_code, entry_kind 'odoo'], so a re-run claims nothing new"
reference:
  repos:
    - name: erp-brick-tax
      role: brick
      https: https://git.dodil.io/dodil/erp-brick-tax.git
      ssh: git@git.dodil.io:dodil/erp-brick-tax.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-tax.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:
    - v4 designs the MTD return, the VAT-number check, the schemes, reliefs, CIS, NI declarations and import VAT; none is built in erp-brick-tax yet (it implements v3)
    - "HMRC production access needs HMRC's production-approval checklist for the software (fraud headers tested, terms of use): an operational step, not code"
    - "EU OSS, US sales tax, GST and other jurisdictions: a jurisdiction pack each, not built; the model (code, rate, rule) is jurisdiction-neutral"
    - compound taxes (a tax on a tax) and withholding taxes are not modelled
    - "partial exemption special methods (sector-based, use-based, agreed with HMRC) are not computed: the standard method only (TAX-48); a special method is a fixed percentage row the tax admin enters"
    - the AI-step marker in the BPMN is a task name until erp-platform draws dodil:ai / dodil:mode (M0 AI-step contract)
sap_parity:
  - sap: Tax codes per country (FTXP, T007A) with validity-dated rates
    ours: covered
    where: TAX-02, TAX-03, tax_code, tax_rate
  - sap: Tax calculation procedure (TAXGB, condition types MWAS/MWVS)
    ours: different
    where: tax_code, tax_rate, TAX-10
    why: "no procedure layer: a code carries its rate directly; compound tax-on-tax procedures are not modelled (known_gaps)"
  - sap: Tax determination by condition technique (tax classification of material and customer, MWST)
    ours: covered
    where: TAX-04, tax_rule, tax_category, treatment
  - sap: Customer/vendor tax classification and VAT registration number (KNVI, STCEG)
    ours: covered
    where: TAX-05, party_tax
  - sap: Own VAT registration per company code and date (T001N)
    ours: covered
    where: TAX-01, registration
  - sap: Output tax on billing and FI documents (BSET), frozen at posting
    ours: covered
    where: TAX-10, TAX-11, TAX-20
  - sap: Input tax on supplier invoices (V-codes)
    ours: covered
    where: TAX-23, TAX-24, tax_rule (direction purchase)
  - sap: Non-deductible input tax (NAV/NVV condition types)
    ours: covered
    where: TAX-23
    why: a line is reclaimable 100 or 0; no partial percentage per code
  - sap: Partial exemption / input tax apportionment (pro-rata)
    ours: covered
    where: TAX-48, partial_exemption_year, tax_code (attribution)
    why: the standard method with the de minimis tests and the annual adjustment; a special method is a fixed percentage row (known_gaps)
  - sap: Reverse charge self-assessment, both sides (ESA/ESE pairs; UK domestic reverse charge for construction)
    ours: covered
    where: TAX-25, TAX-46, tax_rate (rate_pct vs charged_pct), RC, RC_PURCHASE
    why: v4 adds the end-user / intermediary notice and the 5% disregard
  - sap: Tax account determination (OB40, transaction keys MWS/VST)
    ours: covered
    where: TAX-21
    why: the ledger's account map per tax_code, not a transaction key table
  - sap: Tax-inclusive (gross) pricing and tax rounding rules (OBCO)
    ours: covered
    where: TAX-07, TAX-08, settings
  - sap: Manual tax entry or override on a document line
    ours: covered
    where: TAX-06, TAX-09
    why: an override needs a reason and is visible; an AI suggestion is a person's decision
  - sap: Tax reporting date / tax point (VATDATE)
    ours: covered
    where: TAX-10, TAX-11, TAX-33
    why: the tax point date drives rate, treatment and registration, and which return a document enters
  - sap: Tax amounts translated to local currency at the tax rate (KURSF / tax exchange rate)
    ours: covered
    where: TAX-22
  - sap: Plausibility and completeness checks on a tax invoice
    ours: covered
    where: TAX-12, TAX-24
  - sap: Tax on reversals and corrections at the original rate (reference to the original document)
    ours: covered
    where: TAX-47 (pinned lines)
    why: a deduction, a credit-note correction or a settlement discount takes the earlier document's frozen code and rate
  - sap: VAT registration number validation (VIES / HMRC check)
    ours: covered
    where: TAX-13, party_tax workflow (check_party_vat_number), ai_steps check_vat_number
    why: un-deferred in v4 for the re-sign; HMRC's Check a UK VAT number API
  - sap: Advance VAT return (RFUMSV00 / Advanced Compliance Reporting) with electronic filing (UK MTD)
    ours: covered
    where: TAX-26..TAX-32, vat_return workflow, vat_return_entry
    why: boxes 1-9 from frozen document tax, HMRC's VAT (MTD) API with fraud-prevention headers
  - sap: Tax payable posting / transfer to the tax payable account (FB41, RFUMSV00 posting)
    ours: covered
    where: TAX-32 (settle_vat_return), gl GL-30 tax seam
  - sap: Tax liability and payment status with the authority
    ours: covered
    where: TAX-32, vat_liability
    why: HMRC's liabilities and payments read back; the payment itself is a bank line payments reconciles
  - sap: Correction of earlier returns (amended return / error correction)
    ours: covered
    where: TAX-29, vat_adjustment, vat_error_notice
    why: within HMRC's threshold on the next return, else a VAT652 notice
  - sap: Deferred tax / cash-basis tax exigibility (tax on payment, RFUMSV50 transfer)
    ours: covered
    where: TAX-36, registration (accounting_basis), payments GET /cash-basis
    why: UK cash accounting computed from payments' receipt allocations
  - sap: Flat rate scheme for small businesses (country-specific)
    ours: covered
    where: TAX-37, registration, tax_statutory
  - sap: Bad debt VAT relief on written-off receivables
    ours: covered
    where: TAX-34, TAX-35, bad_debt_claim
    why: claim after six months on a written-off invoice; repaid on a later receipt from payments' allocations
  - sap: Import VAT (postponed VAT accounting, PVA)
    ours: covered
    where: TAX-44, TAX-45, import_entry, pva_statement
    why: PVA self-accounted both sides; import VAT paid reclaimed on the certificate; the monthly statement reconciled
  - sap: Tax jurisdictions and other country packs (TXJCD, US sales tax, EU OSS, GST)
    ours: deferred
    milestone: M7
    where: tax_code, tax_rule, tax_statutory
    why: the model is jurisdiction-neutral and every pack is rows plus that authority's filing; each needs its own law read and its own filing API, and no reference customer files outside the UK yet; the first non-UK customer's pack is M7
  - sap: EC sales list (RFASLM00)
    ours: covered
    where: TAX-42, trade_declaration
    why: for Northern Ireland goods to EU customers, the only UK businesses that still file one; HMRC's upload file
  - sap: Intrastat / INTRASTAT declarations (statistical, from SD/MM)
    ours: covered
    where: TAX-43, trade_declaration
    why: Northern Ireland movements with the EU above the thresholds (GB arrivals ended 2022); commodity codes from product
  - sap: Withholding tax (extended, FI-WT) incl. UK CIS deductions
    ours: covered
    where: TAX-38..TAX-41, cis_subcontractor, cis_deduction, cis_return, cis_suffered
    why: "CIS is the UK's withholding regime: verification, deduction, CIS300, statements, and deductions suffered; other countries' withholding comes with their packs (M7)"
  - sap: Capital goods adjustment (input tax correction over an adjustment period)
    ours: covered
    where: TAX-49, capital_goods_item
    why: the UK Capital Goods Scheme over the partial-exemption percentage
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
