# invoicd Operator Guide

> invoicd operator guide: the LF-side INVOIC plausibility check over ten inbound billing PIDs, with § 147 AO receipts and the answer back through makod.

Source: https://hupe1980.github.io/mako/docs/services/invoicd/

`invoicd` is the **INVOIC plausibility-check daemon** on the receiving side: it
checks the invoices other market partners send this operator. Issuing invoices
is [billingd](https://hupe1980.github.io/mako/docs/services/billingd/) and
[netzbilanzd](https://hupe1980.github.io/mako/docs/services/netzbilanzd/). Terms (INVOIC, REMADV, PID, the
Marktrollen) are in the [domain model](https://hupe1980.github.io/mako/docs/architecture/domain-model/#party-roles-marktrollen)
and the [PID reference](https://hupe1980.github.io/mako/docs/regulatory/pid-reference/).

For each inbound INVOIC it:

1. Routes the PID through `src/routing.rs` (check, price sheet, answer commands).
2. Fetches that PID's reference data from `marktd` and runs `invoic-checker`.
3. **Persists the receipt** — a received INVOIC is a Buchungsbeleg (§ 147 AO /
   § 14b UStG, 8 years). A failed write aborts the dispatch.
4. Answers the counterparty through `makod` — accept or dispute.
5. Notifies the ERP with `de.mako.invoic.receipt.*`, durable at-least-once.

Every PID of 31001–31011 is either routed or **refused** into `invoic_dlq` with
its reason (`routing::INVOIC_PIDS`, `REFUSED`); none is answered with a default
command, and an event that cannot become a receipt lands there too.

```mermaid
graph TB
    marktd["marktd :8180<br/>fan-out"]
    invoicd["invoicd :8280<br/>(this service)"]
    makod["makod :8080"]
    pg["PostgreSQL<br/>invoic_receipts<br/>(§ 147 AO / GoBD, 8y)"]

    marktd -->|"de.mako.engine.process.initiated<br/>(INVOIC 31001–31011)<br/>HMAC POST /webhook"| invoicd
    invoicd -->|"price sheets + MMM reference prices"| marktd
    invoicd -->|"persist receipt BEFORE dispatch<br/>(§ 147 AO / GoBD)"| pg
    invoicd -->|"accept / reject, per the answering PID"| makod
    invoicd -->|"de.mako.invoic.receipt.settled/disputed<br/>durable at-least-once<br/>(event_outbox → webhook endpoints)"| erp["ERP webhook"]
```

---

## Routes and authorization

`/webhook` is HMAC-authenticated (`marktd`, with timestamp replay protection);
marktd delivers to it through the endpoint its own configuration names for
invoicd, so invoicd registers nothing at startup. Configure the signing secret
on that endpoint and the matching `webhook.inbound_secret` on invoicd. Invoice
events require a signature even when development API authentication is disabled.

The CloudEvent’s RFC 3339 `time` records the original transport receipt.
invoicd uses its Berlin calendar date and keeps the instant when a held invoice
is checked again. A missing or malformed occurrence returns HTTP 400 with
`invoice_receipt_time_invalid`. The Standard Webhooks signature timestamp
authenticates this delivery attempt.

Every `/api/v1/*` route needs a JWT and a Cedar action (paths under `/api/v1`):

| Routes | Action | Granted to |
|---|---|---|
| `GET /receipts`, `/receipts/{id}`, `/receipts/{id}/rechnung` (BO4E), `/zahlungsstatus/{malo_id}` | `read-receipt` | any caller in the tenant |
| `GET /disputes` | `read-disputes` | any caller in the tenant |
| `GET /overdue-remadv` | `read-overdue-remadv` | any caller in the tenant |
| `POST /receipts/{id}/confirm-payment`, `/dispatch-answer`, `/resolve-dispute` | `write-receipt` | **LF role** |
| `POST /receipts/{id}/feststellungen`, `POST /leistungsnachweise` | `record-feststellung` | **ESA, LF or NB role** — the recipients of a 31009 |
| `POST /mcp` | `use-mcp` | any caller in the tenant (OIDC or `[mcp]` key) |
| `GET /api/v1/policy`, `GET /admin/einrichtung` | `read-policy`, `read-config` | any caller in the tenant |
| `/api/v1/webhooks/**`, `GET /api/v1/events` | `manage-subscription`, `read-events` | **ADMIN** — see [Webhooks](#webhooks) |

`/webhook` answers `204` once an event is finished with — answered,
deliberately unanswered or dead-lettered — and `503` when the reference data
(Preisblatt, Mehr-/Mindermengenpreise, ESA-Angebot) could not be read from
`marktd`, so the sender redelivers. The receipt is persisted before the answer
is sent; an event that cannot become a receipt goes to `invoic_dlq` with its
reason.

The runner adds `/health/live`, `/health/ready` and `/metrics`; invoicd's own
gauges are at `GET /invoicd/metrics`. `GET /api/v1/openapi.json` serves the
OpenAPI document of every `/api/v1` route; `services/invoicd/openapi.json` is
its committed copy. `tests/it/cedar_actions.rs` holds the
actions in code and policy to each other in both directions.

### `POST /api/v1/receipts/{id}/dispatch-answer`

Sends the answer for a receipt whose automatic dispatch failed
(`dispatched_at IS NULL`) — exactly the answer recorded at the check, with its
Antwortcode, Entscheidungsbaum and German Ablehnungsgrund, which makod writes
as the REMADV's `SG7 FTX+ABO`. `409` when already dispatched, `422` without a
message reference or a recorded answer.

### Deciding a held invoice

A Prüfschritt no INVOIC answers is answered by what a person records, and the
invoice walks again in place — to a REMADV and a `de.mako.invoic.receipt.*` event
like any automatic verdict, or still `Offen` with what remains:

- **`POST /api/v1/leistungsnachweise`** — `{rechnungssteller_mp_id,
  bestellung_ref, artikel_id, von, bis, erbracht, nachweis}`: the MSB performed
  (or did not perform) the ordered Leistung over the period. It answers
  Prüfschritt 310 for every position of that MSB's invoices on that order
  (`SG1 RFF+ACE`) whose period it covers — held ones walk again at once, a
  later invoice reads it on arrival. Covering statements that disagree answer
  neither way.
- **`POST /api/v1/receipts/{id}/feststellungen`** — `{feststellungen:
  {leistung_erbracht, preis_wie_angebot, steuersatz_korrekt} per
  Positionsnummer, preisblatt_version_gueltig}, begruendung}` on a held receipt
  (`409` otherwise): Prüfschritte 310, 320 (where no offer on record prices the
  Artikel-ID), 330 (where the INVOIC does not settle it) and 80, and in the
  second round `einwaende_entkraeftet` (Prüfschritt 1). Recorded with
  the caller and the Begründung; a later statement for a step replaces the
  earlier one, and it wins over a Leistungsnachweis for that position.

**The second round.** When the MSB answers our refusal with a COMDIS 29001
(„Die Rechnung wird als korrekt angesehen", `E_0265` Prüfschritt 10), makod
resumes the invoice's process by the Rechnungsnummer the COMDIS names (`DOC`
DE 1004) and announces it as a `process.initiated` with PID 29001 for that
process. invoicd keeps round one's answer and dispatch time
(`erste_runde_*`), records the `comdis_ref`, and walks the invoice again under
`E_0266`/`E_0276`/`E_0277` (EBD 4.3 Kap. 8.27.3, S. 634). Its Prüfschritt 1 —
„Konnte der MSB alle Einwände des Rechnungsempfängers entkräften?" — is a
judgement of the COMDIS, so the walk holds there until
`feststellungen.einwaende_entkraeftet` is stated on the receipt: `false`
refuses with `A25` (`AC1` for Preisblatt B), `true` walks every later step
again on the facts as they now stand. A COMDIS for an invoice whose answer
was no refusal that went out is dead-lettered.

MCP `list_held_receipts` lists the held invoices with each open Prüfschritt
(`offen`: Ebene, Positionsnummer, the missing fact) and the `bestellung_ref` a
Leistungsnachweis names.

---

## Reading the inbound Rechnung

The BO4E payload crosses the gate on its
[**received-document** setting](https://hupe1980.github.io/mako/docs/architecture/domain-model/#the-bo4e-gate):
a document that will not **type** (wrong `_typ`, out-of-schema `rechnungstyp`) is
dead-lettered; one that types but breaks a BO4E rule (a `gesamtbrutto` that is
not net plus tax) is **disputable** and answered by a REMADV from check stage 7.

The announcement names the invoice's receiver (`receiver_gln`, the INVOIC's
NAD+MR): it decides the Sparte the invoice is checked under and, on PID 31009,
the ESA whose accepted offer is looked up. An announcement without it is
dead-lettered — the tenant is an isolation key and never stands in for it.

---

## Handled PIDs

| PID | Description | Direction | Sparte | Status |
|-----|-------------|-----------|--------|--------|
| 31001 | Abschlagsrechnung Netznutzung (NB → LF) | Inbound | ⚡🔥 | ✅ |
| 31002 | NN-Rechnung — Netznutzungsabrechnung (NB → LF) | Inbound | ⚡🔥 | ✅ |
| 31003 | WiM-Rechnung — Abrechnung von Dienstleistungen im Messwesen (MSBA → NB · MSBA → MSBN) | Inbound | ⚡🔥 | ✅ |
| 31004 | Stornorechnung — universal Storno (GPKE/MMM/WiM/Kapazität/AWH/GeLi) | Inbound | **Strom + Gas** | ✅ arithmetic-only (`check_storno`) |
| 31005 | MMM-Rechnung Mehr-/Mindermengensaldo | Inbound | Strom | ✅ |
| 31006 | MMM Mehrmenge, selbst ausgestellt (NB → LF) | Inbound | Strom | ✅ |
| 31007 | GaBi Gas Aggreg. MMM-Rechnung (NB → MGV) | Inbound | Gas | ✅ + MMM-Preisprüfung |
| 31008 | GaBi Gas selbst ausgest. Aggreg. MMM-Rechnung | Inbound | Gas | ✅ + MMM-Preisprüfung |
| 31009 | MSB-Rechnung (MSB → **NB / LF / ESA**, WiM) | Inbound | Strom | ✅ `PreisblattMessung` — or the accepted **Angebot** toward an ESA |
| 31010 | Kapazitätsrechnung (NB → KN) | Inbound | Gas | ⛔ refused into `invoic_dlq` |
| 31011 | Rechnung sonstige Leistung (NB → LF) — in practice the Sperr-/Entsperrkosten | Inbound | **Strom + Gas** | ✅ |

**PID 31010 is refused into `invoic_dlq`.** INVOIC AHB 1.0b Kap. 3.1.4 states
the Kommunikation as „NB an KN" (the Kapazitätsnutzer), a role no answer command
permits; `BGM` DE1004 names the PDF Kapazitätsrechnung that is the actual
document (Änd-ID 26872). It is settled by hand.

Each route answers through one command family, from `mako_markt::commands`:
`gpke.abrechnung.*` (31001, 31002, 31005, 31006), `wim.rechnung.*` (31003,
31009), `invoic.stornorechnung.*` (31004), `gabi.rechnung.*` (31007, 31008)
and `invoic.sonstige-leistung.*` (31011). A PID with no route is never answered
with a default command. `cargo xtask check-answer-commands`
holds the table to `makod`'s registry.

**PID 31009** prices metering service and is checked against
`PreisblattMessung`; when the Rechnung is not in the process payload, `invoicd`
asks `makod` for it.

**Toward an ESA the price basis is the accepted Angebot.** 31009 goes to the NB,
LF or ESA (WiM Teil 1 Kap. 6.2 / Teil 2 Kap. 4.5); a Kapitel-4.6 Messprodukt has
no published Preisblatt because §35 MsbG leaves its Entgelt to be agreed.
`makod` files the accepted QUOTES 15003 at `marktd` on the ORDRSP 19011
(`esa_messprodukt_preise`), and `invoicd` joins exactly on Artikel-ID
(`SG27 PIA+Z02` ↔ `SG26 LIN` DE 7143 `Z09`).

The Use-Case is on the wire: `IMD+7081` = `KON` (Universalbestellprozess, the
ESA billing of WiM Teil 2 Kap. 4.5), `MSB` (Messstellenbetrieb toward NB or LF),
`TEC` (Änderung der Technik). An accepted offer on record is the fallback when
the qualifier is missing. `SG1 RFF+ACE` (Muss) names the order — ORDERS on
`KON` (hint `[501]`), QUOTES on `MSB` (`[508]`) — and is what `E_0264`
Prüfschritt 40 checks; both ride the process, as BO4E has no field for them.

| Finding | Meaning |
|---|---|
| `AngebotDeviation` | a position billed away from the agreed price — dispute |
| `AngebotPositionUnknown` | an Artikel-ID the offer never priced — a charge nobody agreed to; dispute |
| `TariffNotFound` | no accepted offer on record — **warn and skip**, never dispute |

### The answer names the tree the Use-Case publishes

A REMADV Abweisung carries `SG7 AJT`: DE 4465 the code, DE 1082 the
Entscheidungsbaum. Every invoice Use-Case has its own quartet:

| PID | Empfänger | Rechnung | Nicht-Zahlungsavis | erneut | Storno |
|---|---|---|---|---|---|
| 31001/31002/31005/31006 | LF | `E_0406` | `E_0452` | `E_0407` | `E_0459` |
| 31009 | **ESA** (`IMD+7081` = `KON`) | `E_0264` | `E_0265` | `E_0266` | `E_0267` |
| 31009 | NB, Messstellenbetrieb (`MSB`) | `E_0566` | `E_0567` | `E_0568` | `E_0569` |
| 31009 | NB, **Preisblatt B** (`TEC`) | `E_0273` | `E_0274` | `E_0277` | `E_0275` |
| 31009 | LF, Messstellenbetrieb (`MSB`) | `E_0210` | `E_0211` | — | `E_0243` |
| 31009 | LF, **Preisblatt B** (`TEC`) | `E_0270` | `E_0271` | `E_0276` | `E_0272` |
| 31003 | NB / MSBN | `E_0259` | `E_0260` | — | `E_0261` |

`mako_pruefung::codes::rechnungspruefung(pid, empfaenger, gegenstand)` is that
table. The recipient's Marktrolle (`[identity] marktrolle`, configuration — not
inferred) narrows 31009's five Use-Cases to two, and `IMD+7081` decides: `TEC`
is the MSB's **Preisblatt B** (AWH „Änderung der Technik an Lokationen", priced
from PRICAT 27002), `MSB` / `KON` the Messstellenbetrieb and the ESA. An
unlabelled invoice is read as Messstellenbetrieb, because `E_0270`/`E_0273`
refuse with `A04` where no Bestellung exists. A walked ESA answer outranks the
setting.

The answer's shape picks the REMADV PID (REMADV AHB 1.0a): one code rides 33002
(Kap. 3.1.1), a set rides 33003 (Kopf/Summe) or 33004 (Position) (Kap. 3.1.2).

| Family | Walk |
|---|---|
| ESA (`E_0264`) and both Preisblatt-B (`E_0270`, `E_0273`) | walked in full by `mako_pruefung::rechnung`, codes emitted with Ebene and Positionsnummer |
| Messstellenbetrieb (`E_0566`, `E_0210`) | trees and Codelisten resolve, so inbound REMADVs read correctly; no walk — the dispute carries **no** code and is logged for an operator |

`E_0264` has three levels with disjoint codes: Kopf 10–90 (`A01`–`A07`, `A90`),
Position 300–430 (`A09`–`A15`, `A20`, `A99`), Summe 500–550 (`A21`–`A24`, `A96`).
A Kopf refusal ends the walk; settlement is „ganz oder gar nicht" (WiM Teil 2 UC
4.5.1).

The invoice answers two Prüfschritte about itself: 10 (and the
Storno's 17) checks that every § 14 Abs. 4 UStG Pflichtangabe is stated —
`NAD+MS`/`NAD+MR` name and Anschrift, `SG3 RFF+FC`/`VA`, `DTM+137`, the `BGM`
number, each position's Artikel-ID and `QTY`, the period, `SG52 TAX` with
`MOA+125`/`MOA+161` — and an `A01` names each one missing; 330 holds a position
of Steuerkategorie `S` to the § 12 Abs. 1 UStG rate of its period (16 % in the
second half of 2020).

Five need facts no INVOIC carries (50, 310, 370,
`E_0266` 1, and on Preisblatt B 80), and 330 does too for an `O` or `AE`
position or one whose period crosses a change of the rate. A step the walk
reaches with no answer — those facts, or a missing Leistungszeitraum,
Zahlungsziel or Angebot — is neither passed nor refused: the walk ends open, the
receipt is recorded with outcome `Offen`, no REMADV is sent, no
`de.mako.invoic.receipt.*` event is enqueued, and `dispatch-answer` refuses it; a
Leistungsnachweis or a statement on the receipt decides it (see *Deciding a
held invoice*).

A walk that refuses disputes the invoice even where the
plausibility report is clean: the REMADV carries the tree's codes. A
`marktd` outage on the order lookup (Prüfschritt 40) answers `503`, so the
sender redelivers once marktd answers.

**PID 31004** is the universal, Sparte-neutral Storno (INVOIC AHB Kap. 3.1.2): the
Sparte comes from `Rechnung.sparte`, the check is arithmetic only, and the
answer is `invoic.stornorechnung.{annehmen,ablehnen}`. Any Rechnung flagged
`ist_storno` takes the same arithmetic-only check.

**MMM reference prices.** Strom is one nationwide monthly BDEW series (§ 13
Abs. 3 StromNZV bis 31.12.2025; GPKE Teil 1 Kap. 8.4 ab 01.01.2026), keyed on the month
alone; Gas prices are per Marktgebiet (Trading Hub Europe).

---

## invoic-checker — checks

| # | Stage | Finding | Outcome |
|---|---|---|---|
| 1 | **Storno reference** — `ist_storno=true` must name `original_rechnungsnummer` | `StorniertWithoutReference` | `Dispute` |
| 2 | **Billing period validity** — boundaries present and consistent | `PeriodInvalid` | `Dispute` |
| 3 | **Zahlungsziel** — not before `rechnungsdatum`; ≥ 10 WT after receipt (31001–31003, 31009; GPKE Teil 2 Kap. 3.3.2 Nr. 1; `A10`); ≥ 10 WT after the Rechnungsdatum (31005, 31007, Gas 31001–31003; INVOIC AHB 1.0b `[24]`); ≤ 10 WT on a Rückerstattung (31001, 31002, 31005, Gas 31003) and on 31006/31008 (`[25]`, `E_0406` Prüfschritt 34; `A11`); the operator's `max_zahlungsziel_days` if set | `ZahlungszielInvalid` · `ZahlungszielUnterschritten` · `ZahlungszielUeberschritten` · `ZahlungszielExceeded` | `Dispute` · `Dispute` · `Dispute` · `Warn` |

The recipient's Sparte — which the Gas-only rows depend on (INVOIC AHB `[493]`) — is read off the
`NAD+MR` MP-ID: a DVGW-Codenummer (`98…`) is Gas, a BDEW-Codenummer (`99…`) Strom (BDEW-AWH
Identifikatoren V1.2, Kap. 2.2). A GS1 GLN names no Sparte, and those rows are then not applied.
| 3a | **WiM 31003 send window** — Strom equipment rental uses the original Berlin receipt and the inclusive period end (WiM Teil 1 ch. 3.7.2 no. 1, pp. 80–81; INVOIC AHB 1.0b ch. 3.1.1, pp. 8–9, condition [2]). Gas and other service triggers require separate evidence (AWH WiM Gas 2.0 ch. 4.7.2, pp. 68–70) | `RechnungZuSpaet` / `DienstleistungsfristUngeklaert` | `Warn` |
| 4 | **Currency agreement** — every monetary field on one currency | `WaehrungMismatch` | `Dispute` |
| 5 | **Position arithmetic** — quantity × unit price = line net | `ArithmeticError` | `Dispute` |
| 6 | **Document total** — Σ line nets = `gesamtnetto` | `TotalMismatch` | `Warn` |
| 7 | **Umsatzsteuer** — the § 14 Abs. 4 Nr. 8 UStG block: a rate and an amount, `gesamtbrutto = gesamtnetto + gesamtsteuer`, and no tax stated on a reverse-charge invoice | `SteuerMissing` · `SteuerMismatch` · `ReverseChargeStatesTax` | `Dispute` |
| 8 | **Tariff / Angebot** — the unit price against the published Preisblatt, or against the accepted ESA offer | `TariffDeviation` · `TariffNotFound` · `AngebotDeviation` · `AngebotPositionUnknown` | `Warn` or `Dispute` |

Stage 3's ceiling runs only when `max_zahlungsziel_days` is set; stage 3a runs only on PID
31003; stage 8 is skipped for a Stornorechnung. Stage 4 runs before the
arithmetic so a `CHF` amount is never read as EUR. `RechnungZuSpaet` is never
escalated by `auto_dispute_threshold_eur`: no REMADV tree publishes a code for
lateness.

Which price basis stage 8 uses is the routing table's decision, not the stage's:

| Route | Basis | PIDs |
|---|---|---|
| `Netznutzung` | `PreisblattNetznutzung` of the sending NB | 31001, 31002, 31011 |
| `NetznutzungMitMmmStrom` / `…Gas` | the same sheet, **plus** a Mehr-/Mindermengen settlement-price check against the BDEW Strom series resp. the Gas MGV's | 31005, 31006 / 31007, 31008 |
| `Messung` | `PreisblattMessung`, plus every negative position matched to a contracted `AufAbschlag` name (WiM PRICAT 27001–27003) | 31003, 31009 |
| `ArithmetikNur` | none — stages 1–6 only | 31004, and any `ist_storno` document |

Stage 8 matches an INVOIC position's text against the Preisblatt's
`zeitvariablePreispositionen` band codes (`zaehlzeitregister`) first, then the
flat `preisstaffeln`. The `Messung` and ESA paths run stages 2–7 and their own
price basis; stages 3 and 7 apply to 31003/31009 as to every invoice (the AHB
makes `SG8 DTM+265` and the `TAX`/`MOA` block Muss there too). A § 13b invoice
stating 0,00 EUR with an `RCV` Steuerbetrag is not `SteuerMissing`.

The MMM check is skipped when the month's prices are not yet published; an
unreachable `marktd` aborts the check with `ReferenceDataUnavailable`. `Warn`
outcomes auto-approve unless the invoice net exceeds `auto_dispute_threshold_eur`
(`0` = always approve, the default). For Gas, energy = m³ ×
`brennwert_kwh_per_m3` × `zustandszahl`, both from `edmd` via PID 13007.

Every finding carries a German sentence written for the Rechnungssteller —
what deviates, the stated and the expected figure, decimal comma — and a
German name for its kind (`bezeichnung`). A refusal's `ablehnungsgrund` joins
the disputing findings' sentences within one REMADV `SG7 FTX+ABO` DE 4440
(`an..512`, REMADV MIG): it ends on a whole finding and says how many more did
not fit; every finding stays on the receipt (`get_check_result`).

### Outcomes

| Outcome | Meaning |
|---|---|
| `Ok` | accepted |
| `AcceptedPartial` | Storno accepted on the reduced check |
| `Warn` | warnings, auto-approved up to `auto_dispute_threshold_eur` |
| `Offen` | held: a walked Entscheidungsbaum reached a Prüfschritt no record answers; nothing is sent or announced |
| `Dispute` | rejected; the answer carries the disputing findings as `ablehnungsgrund` |
| `Resolved` | dispute closed by an operator |

---

## Payment CloudEvents

`invoicd` notifies the ERP (`[erp] webhook_url`) after every checked INVOIC:

| CloudEvents `type` | Trigger |
|---|---|
| `de.mako.invoic.receipt.settled` | Outcome `Ok`, `AcceptedPartial`, or `Warn` |
| `de.mako.invoic.receipt.disputed` | Outcome `Dispute` |
| `de.mako.invoic.payment.overdue` | Zahlungsziel passed without `confirm-payment` |

`dispatched` in the payload says whether the market answer actually went out.

```json
{
  "specversion": "1.0",
  "type": "de.mako.invoic.receipt.settled",
  "source": "urn:mako:invoicd:tenant:9900357000004",
  "subject": "<process_id>",
  "data": {
    "process_id": "...",
    "pid": 31001,
    "sender_mp_id": "9904234560001",
    "outcome": "Ok",
    "pay_by": "2026-10-15",
    "findings_count": 0,
    "dispatched": true
  }
}
```

The `payment_overdue` worker (every 6 h) emits `de.mako.invoic.payment.overdue`
**once** per accepted, dispatched receipt whose `pay_by` passed without
`payment_confirmed_at` (`overdue_notified_at` stamps it); disputed invoices are
never overdue.

```json
{
  "specversion": "1.0",
  "type": "de.mako.invoic.payment.overdue",
  "source": "urn:mako:invoicd:tenant:9900357000004",
  "subject": "<receipt_id>",
  "data": {
    "receipt_id": "550e8400-...",
    "process_id": "...",
    "pid": 31001,
    "sender_mp_id": "9904234560001",
    "pay_by": "2026-10-15T00:00:00Z",
    "tenant": "9900357000004"
  }
}
```

### Delivery guarantee — durable at-least-once

The `de.mako.invoic.receipt.*` event is enqueued in `event_outbox` in the
transaction that stamps the answer's `dispatched_at`; the
`de.mako.invoic.payment.overdue` event in the transaction that stamps
`overdue_notified_at`. If that transaction fails, invoicd answers `500` and
makod redelivers the invoice. The market answer never waits on the ERP.

### Webhooks

`[erp] webhook_url` is the webhook endpoint `default`, signed with
`[erp] hmac_secret` (Standard Webhooks); further endpoints are registered
under `/api/v1/webhooks/endpoints` (Cedar `manage-subscription`, ADMIN), and
`GET /api/v1/events` (`read-events`) reads the emitted events as a feed. The
routes, signatures, ordering, replay and retention
(`[subscriptions] retention_days`) are the shared module's:
[Webhook subscriptions](https://hupe1980.github.io/mako/docs/architecture/erp-integration/#webhook-subscriptions).
The MCP tools `list_webhook_endpoints` and `list_webhook_deliveries` read the
same. Without `[erp] webhook_url` the service warns at startup.

---

## Idempotency and § 147 AO / GoBD

Each receipt is written **before** any command goes to `makod`; `UNIQUE
(process_id)` makes a redelivered event a no-op. Retention is 8 years (§ 147
Abs. 3 AO / § 14b UStG), driven by `received_at`. An inbound receipt without
`invoice_ref` (BGM 1004, what `makod` routes the answer by) is refused by the
schema.

---

## Payment Lifecycle & Zahlungsstatus

Payment happens outside EDIFACT. The ERP closes the trail with
`POST /api/v1/receipts/{id}/confirm-payment` (body `{}`): `204` sets
`payment_confirmed_at`, `404` when unknown or already confirmed, `403` without
`write-receipt`.

### `GET /api/v1/zahlungsstatus/{malo_id}`

All receipts of one MaLo, with overdue / pending / settled counts:

```bash
curl -s http://invoicd:8280/api/v1/zahlungsstatus/10001234558 \
  -H "Authorization: Bearer <token>" | jq .
```

```json
{
  "malo_id": "10001234558",
  "overdue_count": 1,
  "pending_count": 2,
  "settled_count": 14,
  "items": [
    {
      "id": "550e8400-...",
      "pid": 31001,
      "zahlungsstatus": "overdue",
      "pay_by": "2026-10-15T00:00:00Z",
      "dispatched_at": "2026-10-01T09:12:00Z",
      "payment_confirmed_at": null,
      "received_at": "2026-10-01T08:00:00Z"
    }
  ]
}
```

**`zahlungsstatus` values:**

| Value | Condition |
|---|---|
| `settled` | `payment_confirmed_at IS NOT NULL` |
| `overdue` | `dispatched_at IS NOT NULL` AND `pay_by < now()` AND `payment_confirmed_at IS NULL` |
| `pending` | `dispatched_at IS NOT NULL` AND `pay_by >= now()` AND `payment_confirmed_at IS NULL` |
| `undispatched` | `dispatched_at IS NULL` |

### Payment lifecycle state machine

```mermaid
stateDiagram-v2
    [*] --> Received : invoicd persists receipt (atomic)
    Received --> Dispatched : REMADV 33001 Zahlungsavis sent
    Received --> Disputed : REMADV 33002 / 33003 / 33004 sent (Dispute outcome)
    Received --> Held : a walked Prüfschritt unanswered (Offen outcome), nothing sent
    Dispatched --> Settled : POST /confirm-payment (ERP ack)
    Dispatched --> Overdue : pay_by passes without confirmation
    Overdue --> Settled : POST /confirm-payment (late ERP ack)
    Disputed --> Resolved : POST /resolve-dispute (operator closes after NB agreement, recorded with the decider)
    Resolved --> [*] : § 147 AO / GoBD audit trail complete
    Settled --> [*] : § 147 AO / GoBD audit trail complete
```

---

## Configuration reference

`invoicd` reads `INVOICD_CONFIG` (default `invoicd.toml`); `"env:VAR"` values
defer secrets, `INVOICD_<SECTION>__<KEY>` overrides any key, unknown keys are
refused, and `--check` probes `/health/ready` for the container HEALTHCHECK.

### Full `invoicd.toml` reference

```toml
[http]
addr = "0.0.0.0:8280"          # default

[database]
# Required for § 147 AO / § 14b UStG receipt retention (Buchungsbelege, 8 years).
url       = "env:DATABASE_URL"   # required; use env: for secrets
pool_size = 10                   # default

[identity]
tenant     = "stadtwerke-musterstadt"  # required — data-isolation key, never an MP-ID
marktrolle = "lieferant"               # lieferant (default) | netzbetreiber | esa

[makod]
url     = "http://makod:8080"          # required
api_key = "env:INVOICD_MAKOD_API_KEY" # optional

[marktd]
url     = "http://marktd:8180"            # required
api_key = "env:INVOICD_MARKTD_API_KEY"   # required

[webhook]
inbound_secret = "env:INVOICD_INBOUND_SECRET"  # required unless allow_insecure_no_auth

[check]
# Relative tolerances for invoic-checker plausibility pipeline.
arithmetic_tolerance       = 0.01   # 1 % — qty × price = line net
total_tolerance            = 0.01   # 1 % — Σ line nets = Gesamtnetto
tariff_tolerance           = 0.03   # 3 % — PRICAT unit price vs INVOIC
require_tariff             = false  # true → missing tariff escalates to Dispute
auto_dispute_threshold_eur = "0.00"    # EUR as a string; "0.00" → Warn always auto-approved
# max_zahlungsziel_days    = 60     # optional ceiling in days, an operator choice — no
                                    # Festlegung publishes one; unset = none, 0 is refused

[erp]
# The webhook endpoint `default` — required for ERP accounts-payable automation.
webhook_url = "https://erp.example.com/webhooks/invoicd"
# Optional: sign outbound requests (Standard Webhooks).
# The ERP verifies via webhook-signature: v1,<base64>.
hmac_secret = "env:INVOICD_ERP_HMAC_SECRET"

[subscriptions]
retention_days = 30        # how long emitted events stay replayable
# allow_loopback = true    # `just dev` only: admit http and loopback endpoints

# Required unless allow_insecure_no_auth = true.
[oidc]
# issuer   = "https://login.microsoftonline.com/{tenant-id}/v2.0"
# audience = "api://mako-invoicd"
# jwks_refresh_secs = 300

# [mcp]           # MCP authentication: an API key beside the OIDC verifier
#                 # above, for agent clients that mint no token
# api_key = "env:INVOICD_MCP_API_KEY"

```

---

## MCP tools

| Tool | Description |
|------|-------------|
| `get_policy` | The operator policy and posture, as `GET /api/v1/policy` serves it |
| `get_receipt` | Get a single INVOIC receipt by process UUID |
| `list_disputes` | Receipts with outcome `Dispute`, typed (`Disput`); `frist` is the end of the Zahlungsziel's Berlin day, `rechnungsnummer`, `abgesendet` whether the refusal (REMADV) went out, `befunde` the disputing checker findings, each with its German `bezeichnung` beside the `art` identifier |
| `get_check_result` | Get the full invoic-checker findings for a process |
| `list_overdue_remadv` | Receipts approaching Zahlungsziel without dispatched REMADV |
| `get_zahlungsstatus` | Payment status per MaLo-ID (settled / pending / overdue counts) |
| `summarize_billing_month` | Monthly billing volume + dispute rate per NB counterparty |
| `list_exceptions` | The two operator queues: undispatched answers, and INVOICs that could not be processed at all |
| `list_held_receipts` | Receipts held `Offen`, typed (`GehalteneRechnung`), with each open Prüfschritt and the `bestellung_ref` |

## MCP prompts

| Prompt | Description |
|--------|-------------|
| `resolve-dispute` | Guided dispute investigation (check classification + resolution steps) |
| `check-overdue-remadv` | Monitor and action overdue REMADV dispatches |
| `monthly-billing-review` | § 147 AO / GoBD monthly reconciliation checklist |
| `detect-systematic-errors` | Find NB counterparties with systematic billing errors |

`agentd`'s `invoice-reconciliation-agent` subscribes to
`de.mako.invoic.payment.overdue` and `de.mako.invoic.receipt.*`.

---

## Monitoring

| Query / metric | Target |
|----------------|--------|
| `outcome IN ('Ok','AcceptedPartial','Warn')` rate | > 95 % |
| `outcome = 'Dispute'` count | < 1 % of volume |
| `pay_by < now() + INTERVAL '3 days' AND dispatched_at IS NULL` | 0 |
| `pay_by < now() AND payment_confirmed_at IS NULL AND dispatched_at IS NOT NULL` | 0 (trigger dunning) |
| `invoic_dlq WHERE resolved_at IS NULL` | 0 — an unprocessed Buchungsbeleg |

A receipt nearing `pay_by` without `dispatched_at` is re-sent with
`POST /api/v1/receipts/{id}/dispatch-answer`.

### Prometheus metrics (`/invoicd/metrics`)

Tenant-scoped gauges:

| Metric | Alert when |
|--------|------------|
| `invoicd_receipts_total` | — |
| `invoicd_disputes_total` | rising against a single counterparty |
| `invoicd_overdue_remadv_total` | `> 0` — an unanswered invoice past its Zahlungsziel |
| `invoicd_dlq_open_total` | `> 0` — an unprocessed Buchungsbeleg |
| `invoicd_receipts_by_pid_outcome{pid, outcome}` | — |
