# accountingd Operator Guide

> Operator guide for accountingd, the LF Massenkontokorrent: a tamper-evident double-entry ledger, SEPA and camt payment flows, Mahnwesen and Jahresabschluss.

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

`accountingd` is the **FI-CA equivalent** for the retail billing stack, on port
**`:9380`**: the customer Kontokorrent behind
[billingd](https://hupe1980.github.io/mako/docs/services/billingd/)'s invoices — Offene Posten, dunning, the
§§ 41f/41g EnWG Sperr-Sequenz, SEPA collection and payout, bank-statement import,
the Jahresabschluss and period sealing.

Vocabulary: an account is keyed on a **Marktlokation** ([MaLo vs
MeLo](https://hupe1980.github.io/mako/docs/architecture/domain-model/#malo-vs-melo-the-critical-distinction));
**LF** is the supplier whose books these are. An **Abschlag** is a monthly
advance, the **Jahresabschluss** the annual settlement, **Mahnwesen** dunning
(Mahnstufe 1–3, each with a Mahngebühr), a **Sperrung** the regulated
disconnection of a defaulting customer, **Festschreibung** the irreversible
closing of a period.

SEPA messages: **pain.008** direct debit, **pain.001** credit transfer,
**pain.007** creditor reversal, **pain.002** bank status, **camt.052/053/054**
account reports, **camt.055/029** recall and its answer.

```mermaid
graph TB
    billingd["billingd :9280"]
    einsd["einsd :9180"]
    invoicd["invoicd :8280"]
    accountingd["accountingd :9380"]
    erp["ERP webhook"]
    makod["makod"]
    outputd["outputd :9880"]
    vertragd["vertragd :9780"]
    portald["portald :9480"]
    bank["Bank adapter"]

    billingd -->|"de.mako.billing.rechnung.erstellt → RECHNUNG / STORNO"| accountingd
    einsd -->|"de.mako.eeg.verguetung.berechnet → EEG_GUTSCHRIFT + pain.001"| accountingd
    einsd -->|"de.mako.eeg.marktpraemie.berechnet → EEG_MARKTPRAEMIE + pain.001"| accountingd
    vertragd -->|"recipient of a Mahnung"| accountingd
    accountingd -->|"MAHNUNG document"| outputd
    accountingd -->|"paid Abschläge"| billingd
    accountingd -->|"de.mako.accounting.*"| erp
    accountingd -->|"ORDERS 17115 / 17117"| makod
    accountingd -->|"pain.001"| bank
    bank -->|"pain.002, camt"| accountingd
    accountingd -->|"GET /kontoauszug"| portald
```

---

## Ledger

accountingd opens a `doubleentry/3` ledger in its database's `ledger` schema. An incompatible header stops startup and preserves the journal. The [`doubleentry` crate](https://github.com/hupe1980/doubleentry) provides balanced entries, an append-only RFC 6962 SHA-256 Merkle log with `O(log n)`
proofs, monthly periods from 2015-01 sealed in order, open-item clearing, and
triggers that refuse every change to the log. accountingd owns the chart of
accounts
([`ledger::Chart`](https://github.com/hupe1980/mako/blob/main/services/accountingd/src/ledger.rs));
doubleentry owns the invariants.

Every booking carries an idempotency key; the entry id is derived from it, an
identical replay returns the original entry, and the same key with other
content is refused (`ledger.200`). The entry's kind is its Buchungsart; the
Kontokorrent posting carries the dimensions `korrelation` and `akteur`.

### Booking drafts

The ledger owns its pool and joins no external transaction, so every booking is
a **draft** first: the whole entry is written to `booking_drafts` in the same
transaction as the business change that causes it (a dunning case and its
Mahngebühr, a bank row and its `bank_import_log` entry and event, a Jahresabschluss
and its refund), then recorded right after the commit. A crash between the two
leaves the draft `offen`, and a recovery worker books it within a minute,
exactly once.

| Ledger answer | Draft |
|---|---|
| recorded, or replayed | `gebucht`, with the entry id |
| transient failure | stays `offen`, retried |
| refusal — `301` sealed month, `300` no period, `304` account not open, `200` key conflict | `geparkt` with the code; a person decides |

A parked booking is listed by the MCP tool `list_parked_bookings` and shown in
the Lieferant's Heute in the Desk, with what to do and, for a sealed month, the
first open date. It is resolved by `POST /api/v1/bookings/{key}/rebook`
`{ "buchungsdatum" }` (booked anew under a derived key) or
`POST /api/v1/bookings/{key}/discard` `{ "grund" }`; both record who.
`cargo xtask check-ledger-drafts` refuses a ledger write outside a draft.

Each Buchungsart is one entry with two legs: the customer's **Kontokorrent**
(`Kontokorrent:<lf_mp>:<malo>`, the SKR 1400 Debitoren subledger) and a GL
contra account. Money is `i64` cents throughout; no `f64` touches it.

| `entry_type` | Kontokorrent | GL contra | Raised by |
|---|---|---|---|
| `RECHNUNG` | Debit | Erlöse (SKR 4000) | `de.mako.billing.rechnung.erstellt`, `is_correction=false` |
| `STORNO` | by sign | Erlöse | the same event, `is_correction=true` (a Gutschrift is a negated Rechnung) |
| `GUTSCHRIFT` | Credit | Erlöse | operator `POST /buchen` only |
| `KORREKTUR` | by sign | Erlöse | operator `POST /buchen` |
| `ABSCHLAG` | Debit | Erhaltene Anzahlungen (SKR 03 1718 / SKR 04 3272) | the Abschlagslauf — a demand, not a receipt |
| `ABSCHLAG_VERRECHNUNG` | Credit | Erhaltene Anzahlungen | the settling invoice discharges the advances it deducted |
| `ZAHLUNG` | Credit | Bank (SKR 1200) | camt import |
| `BANKRUECKLAST` | Debit | Bank | a returned direct debit |
| `SEPA_STORNO` | Debit | Bank | a pain.007 reversal |
| `MAHNGEBUEHR` | Debit | Mahnerlöse (SKR 4003) | dunning fee per Mahnstufe |
| `VERZUGSZINSEN` | Debit | Zinserträge (SKR 2650) | § 288 BGB interest |
| `VERZUGSPAUSCHALE` | by sign | Verzugspauschalen | the § 288 Abs. 5 BGB Pauschale (debit) and its Satz-3 Anrechnung (credit) |
| `EEG_GUTSCHRIFT` | by sign | EEG-Aufwand | `de.mako.eeg.verguetung.berechnet` — what the receipt changes its chain by |
| `EEG_MARKTPRAEMIE` | by sign | EEG-Aufwand | `de.mako.eeg.marktpraemie.berechnet` — the same |
| `EEG_AUSZAHLUNG` | Debit | Bank | an EEG payout the bank settled (pain.002 `ACSC`) |
| `EEG_RUECKZAHLUNG` | Credit | Bank | a plant operator's repayment of an overpayment |
| `JAHRESABSCHLUSS` | Debit (Erstattung) | Erstattungen | the annual settlement |

`ledger::ENTRY_TYPES` is the single list: `Chart::contra` maps it and
`POST /buchen` refuses anything outside it.

**Balance** is the signed Kontokorrent net — positive is debt, negative a credit
balance. `accounts.balance_ct` is a read cache, set absolutely from the ledger
after every post.

### The Abschlag pair

An Abschlag is a demand for a part-payment on a supply not yet billed (§ 40
Abs. 1 EnWG, § 14 Abs. 5 UStG), booked against Erhaltene Anzahlungen, never
against Bank:

```
Abschlagslauf   ABSCHLAG              Dr Kontokorrent  / Cr Erhaltene Anzahlungen
money arrives   ZAHLUNG               Cr Kontokorrent  / Dr Bank
Endrechnung     RECHNUNG (gross)      Dr Kontokorrent  / Cr Erlöse
   …the same    ABSCHLAG_VERRECHNUNG  Cr Kontokorrent  / Dr Erhaltene Anzahlungen
```

So an **unpaid advance is an open receivable** that reaches `verzug_ct` and the
Mahnwesen; the **payment is booked once**, on the camt receipt; and the
Endrechnung is booked **gross**, with the deduction it states
(`gesamtbrutto − zuZahlen`) as the matching credit.

`abschlag_forderungen` records what a posting cannot: the **USt rate** each
advance was raised at (§ 14 Abs. 5 Satz 2 UStG) and **which invoice absorbed
it**. Whether it was received is the residual of its ledger entry after FIFO
clearing. `GET /api/v1/accounts/{malo_id}/abschlaege` lists the received,
unabsorbed advances a settling invoice may deduct, oldest first, with their rate.

### Guthaben aus Schlussrechnung (§ 40c Abs. 3 EnWG)

The webhook verifies a Standard Webhooks `whsec_` secret using its decoded key. Invoice ingestion requires the local billingd deployment in `source` and the invoice issuer in `data.lf_mp_id`. A different deployment returns `403 invoice_source_mismatch`. A blank or missing CloudEvent ID returns 400. A blank or missing account reference returns `422 invalid_invoice_account`. An absent or invalid issuer returns `422 invalid_invoice_issuer`. The webhook returns `422 invalid_invoice_amount` for a missing gross amount, an unreadable amount, or a deduction outside the ledger’s cent range. An ordinary invoice can omit `zuZahlen`. A zero-gross invoice can still settle advances. These checks precede booking.

A `de.mako.billing.rechnung.erstellt` with `schlussrechnung: true` whose `zuZahlen` is
negative owes the customer a Guthaben, paid out „binnen zwei Wochen". accountingd
raises one `credit_payouts` row for it, keyed on (tenant, Rechnungsnummer) so a
redelivered event raises none, due by `mako_fristen::vorlauf::guthaben_faellig`
of the Rechnungsdatum. A Schlussrechnung with a Guthaben and no readable
Rechnungsdatum is refused `422 credit_without_due_date` before anything is
booked. The invoice's Storno (`is_correction`, `originalRechnungsnummer`)
cancels an open item. `POST /api/v1/credit-payouts/{payout_id}/paid` books the
transfer as a `ZAHLUNG` debit of the Guthaben (key `credit-payout:{payout_id}`)
and closes the item in one transaction; a second payout is `409`. An open item
past `due_on` is `overdue` in `GET /api/v1/credit-payouts` and MCP
`list_credit_payouts` — the Desk's Heute source.

### Idempotency keys

| Key | Written by |
|---|---|
| CloudEvent id | every inbound event |
| `ABSCHLAG-{malo}-{YYYY}-{MM}` | the Abschlagslauf |
| `mahngebuehr:{case_id}:{stufe}` | the dunning fee, per case |
| `verzugspauschale:{entry_id}` | the § 288 Abs. 5 BGB Pauschale, per Entgeltforderung |
| `verzugspauschale-anrechnung:{case_id}` | its Satz-3 Anrechnung, per dunning step |
| `interest:{malo}:{from}:{to}` | a § 288 BGB charge |
| `bank:{txn}` | every bank import, and the assignment of an unmatched line |
| `credit-payout:{payout_id}` | the payout of a Schlussrechnung's Guthaben |
| `jahresabschluss:{malo}:{year}` | the annual settlement |
| `manual:{uuid}` | `POST /buchen` without `reference_id` |

The same key with different content is refused. `POST /buchen` is idempotent
only when it carries a `reference_id`.

---

## Endpoints

Every `/api/v1/*` route requires a JWT and a Cedar action — see
[Authorization](#authorization). `/webhook` is signature-authenticated instead.

An account is addressed by its MaLo and the MP-ID it is kept under. The routes
that serve every account — master data, balance, ledger, Kontoauszug, open
items, clearing, Zahlungsinformation, reconcile, anonymize, balance proof — take
`?mp_id=` (the Lieferant's for a customer, `[eeg] nb_mp_id` for an EEG plant);
the Lieferant's customer features — Verbraucher status, Abschlag,
Vorauszahlung, payment plans, locks, interest, Jahresabschluss, payment
assignment — take `?lf_mp_id=`. Both default to the configured `lf_mp_id`, and
a key a route does not take is refused rather than ignored.

`GET /api/v1/openapi.json` serves the OpenAPI 3.1 document of every `/api/v1`
route below, committed as `services/accountingd/openapi.json`. The routes marked
**(OpenAPI)** answer a typed body; each read among them is shared with an MCP
tool: the route's documented response and the tool's `outputSchema` come from
the same type.

| Method | Path | Description |
|---|---|---|
| `POST` | `/webhook` | Inbound CloudEvents (billingd, einsd, invoicd), Standard Webhooks signature |
| `GET/PUT` | `/api/v1/accounts/{malo_id}` | Account master data (IBAN, Abschlag, `billing_day`) |
| `PUT` | `/api/v1/accounts/{malo_id}/verbraucher` | The § 13 BGB status, `{"verbraucher": true\|false\|null}` — vertragd's contract command only (Cedar `sync-verbraucher`, held to the principal `vertragd`) |
| `GET` | `/api/v1/accounts/{malo_id}/balance` | **(OpenAPI)** `Kontostand`: balance in ct and EUR, `status` `overdue` / `credit` / `settled`, the Abschlag |
| `GET` | `/api/v1/accounts/{malo_id}/ledger` | **(OpenAPI)** `Kontoauszug`: movements, newest first, with `opening_ct` (`?limit=`, default 100, at most 1000) |
| `GET` | `/api/v1/accounts/{malo_id}/kontoauszug` | Statement for portald; `?from=&to=` returns `eroeffnungssaldo_ct` / `bewegung_ct` / `schlusssaldo_ct` |
| `GET` | `/api/v1/accounts/{malo_id}/open-items` | Offene Posten after clearing |
| `POST` | `/api/v1/accounts/{malo_id}/clear` | Run the FIFO Zahlungszuordnung |
| `POST` | `/api/v1/clearings/{position}/reset` | Release one mis-assigned clearing (the position `clear` returned) |
| `GET` | `/api/v1/trial-balance` | Summen- und Saldenliste (§ 238 HGB) |
| `PUT` | `/api/v1/accounts/{malo_id}/abschlag` | Change the monthly advance; body `{ "abschlag_ct" }` |
| `GET` | `/api/v1/accounts/{malo_id}/abschlaege` | Deductible advances with their USt rate (`?from=&to=`) |
| `GET/PUT` | `/api/v1/accounts/{malo_id}/vorauszahlung` | `rubo4e::current::Vorauszahlung` through [the BO4E gate](https://hupe1980.github.io/mako/docs/architecture/domain-model/#the-bo4e-gate) |
| `GET/PUT` | `/api/v1/accounts/{malo_id}/zahlungsinformation` | `rubo4e::current::Zahlungsinformation` through the gate; strict enums keep `zahlungsart` valid. Both PUTs refuse a key BO4E does not define (`422`, `bo4e.unknown_field`) |
| `POST` | `/api/v1/accounts/{malo_id}/buchen` | Manual booking |
| `POST` | `/api/v1/accounts/{malo_id}/reconcile` | Compare `balance_ct` with the ledger; `?repair=true` resets it |
| `POST` | `/api/v1/accounts/{malo_id}/anonymize` | GDPR Art. 17 pseudonymization |
| `GET/POST` | `/api/v1/accounts/{malo_id}/interest-charges` | § 288 BGB interest |
| `GET/POST` | `/api/v1/accounts/{malo_id}/payment-plans` | Zahlungsvereinbarungen |
| `GET/DELETE` | `/api/v1/payment-plans/{plan_id}` | One plan with its schedule; cancel |
| `PUT` | `/api/v1/accounts/{malo_id}/business-partner` | Link to a `kunden_nr`; body `{ "kunden_nr" }` |
| `GET` | `/api/v1/business-partners/{kunden_nr}/accounts` · `/balance` | A partner's accounts; consolidated balance |
| `GET` | `/api/v1/aging` | Receivables in 0–30 / 31–60 / 61–90 / >90 day buckets |
| `GET` | `/api/v1/offene-posten` | **(OpenAPI)** `UeberfaelligeKonten`: overdue accounts, largest first; never an EEG plant account (`?min_balance_eur=&limit=`; Cedar `read-books`) |
| `POST` | `/api/v1/periods/{period_id}/seal` | Festschreibung of every open month through `YYYY-MM`; no body |
| `GET` | `/api/v1/periods/seals` | Sealed months, `sealed_through`, `verified` (a full `audit`) |
| `POST` | `/api/v1/bookings/{key}/rebook` · `/discard` | Resolve a parked booking |
| `GET` | `/api/v1/entries/{entry_id}/proof` | Merkle inclusion proof |
| `GET` | `/api/v1/periods/{period_id}/balance-proof` | Closing balance of a Kontokorrent in a sealed period (`?malo_id=&mp_id=`) |
| `GET` | `/api/v1/entries/consistency-proof` | Append-only proof since `?since=<tree_size>` |
| `GET` | `/api/v1/dunning` | **(OpenAPI)** `Mahnfaelle`: open dunning cases, newest first (`?limit=`) |
| `POST` | `/api/v1/payments/match` | **(OpenAPI)** `Zahlungszuordnung`: the accounts a transfer may belong to (body `amount_ct`, `reference`, `iban`, `end_to_end_id`); a read posted as a body so no access log holds the IBAN; books nothing |
| `POST` | `/api/v1/dunning/{account_id}/escalate` | Manual Mahnstufe; body `{ "stufe": 1–3, "due_days": ≥ 1 }`, both required |
| `POST` | `/api/v1/dunning/{id}/resolve` | Resolve a case |
| `POST` | `/api/v1/dunning/{id}/abwendung/angebot` | Record the Abwendungsvereinbarung offer (§ 41g Abs. 1 S. 2 EnWG) |
| `GET/POST` | `/api/v1/dunning/{id}/locks` | Mahnsperren: history; place one |
| `POST` | `/api/v1/accounts/{malo_id}/locks` | Place one on an account with no dunning case (e.g. `insolvenz`) |
| `DELETE` | `/api/v1/dunning/locks/{lock_id}` | Lift one, with a reason |
| `GET` | `/api/v1/dunning/locks/review` | Open-ended locks (`?older_than_days=`) |
| `GET/POST` | `/api/v1/dunning/{id}/einwaende` | Forderungseinwände (§ 41f Abs. 3 S. 3–5 EnWG) |
| `POST` | `/api/v1/einwaende/{einwand_id}/erledigen` | Close an objection |
| `POST` | `/api/v1/sepa/mandates` | Register a mandate (IBAN mod-97) |
| `GET/DELETE` | `/api/v1/sepa/mandates/{mandate_id}` | Fetch; revoke |
| `GET` | `/api/v1/sepa/mandates/dormant` | Mandates at or near the 36-month dormancy limit |
| `POST` | `/api/v1/sepa/run` | Build and archive one pain.008; `409` if the date was dispatched |
| `GET` | `/api/v1/sepa/collections/{run_id}/entries` | What a run collected, with status |
| `POST` | `/api/v1/sepa/pain002` | Apply a pain.002 (payouts and collections, with VoP) |
| `POST` | `/api/v1/sepa/reversals` | pain.007 for a settled collection |
| `POST` | `/api/v1/sepa/recalls` | camt.055 for a submitted collection |
| `POST` | `/api/v1/sepa/camt029` | Apply the bank's answer to a recall |
| `POST` | `/api/v1/payments/import/camt053` · `camt054` · `camt052` | Bank statements |
| `POST` | `/api/v1/payments/import` | Flat JSON bank export |
| `GET` | `/api/v1/payments/unmatched` | **(OpenAPI)** `UnzugeordneteZahlungen`: bank lines no account claimed, oldest first, the IBAN masked (`?limit=`; Cedar `read-books`) |
| `POST` | `/api/v1/payments/{payment_id}/assign` | **(OpenAPI)** Book an unmatched line to an account and close it, one transaction; body `{ "malo_id", "lf_mp_id"? }`; `409 payment_already_assigned` (Cedar `import-payments`) |
| `GET` | `/api/v1/credit-payouts` | **(OpenAPI)** `Guthabenauszahlungen`: Guthaben from Schlussrechnungen, `due_on`, `overdue` (`?status=open\|paid\|cancelled&overdue=true&malo_id=&limit=`; Cedar `read-books`) |
| `POST` | `/api/v1/credit-payouts/{payout_id}/paid` | **(OpenAPI)** Book the transfer of a Guthaben and close its item, one transaction; body `{ "paid_on", "reference"? }`; `409 credit_payout_not_open` (Cedar `post-entry`) |
| `GET` | `/api/v1/eeg/payouts` | **(OpenAPI)** `EegAuszahlungen`: EEG payout orders, newest first (`?tr_id=&malo_id=&year=&month=&status=&payment_type=&limit=`); `NB` (`read-eeg-payouts`) |
| `GET` | `/api/v1/eeg/payouts/{payout_id}` | One payout order with its pain.001; `NB` (`read-eeg-payouts`) |
| `POST` | `/api/v1/eeg/payouts/run` | Pay a billing month's receipt chains, Vergütung and Marktprämie, what each has outstanding (`billing_year`, `billing_month` required) |
| `GET` | `/api/v1/eeg/rueckforderungen` | Receipt chains paid beyond their current receipt, with the amount owed back |
| `POST` | `/api/v1/eeg/rueckzahlungen` | Record an operator's repayment of one; `409` on a second the same day |
| `PUT` | `/api/v1/eeg/payouts/{payout_id}/status` | Decoded pain.002 status (`ACCP`/`ACSC`/`RJCT`/`CANC`) |
| `GET` | `/api/v1/eeg/enfg-zahlungen` | EEG/KWKG payments made in a billing month (`?year=&month=`, both required): `ACSC` payouts, Aufrechnungen, Rückzahlungen (negative) |
| `POST` | `/api/v1/eeg/aufrechnungen` | Record an Aufrechnung against an EEG claim; `409` on a repeat |
| `POST` | `/api/v1/jahresabschluss/{malo_id}` | Annual settlement (`?year=`, `?dry_run=true`) |
| `GET` | `/accountingd/metrics` | Ledger and dunning gauges |
| `GET` | `/health/live` · `/health/ready` | Liveness; readiness |
| `POST` | `/mcp` | MCP Streamable HTTP |

### Manual booking

```bash
curl -X POST "http://accountingd:9380/api/v1/accounts/51238696012/buchen" \
  -H "Content-Type: application/json" \
  -d '{
    "entry_type":   "ZAHLUNG",
    "amount_ct":    -5000,
    "reference_id": "BANK-TXN-2026-07-10",
    "description":  "Überweisung Kunde (ausserhalb SEPA)"
  }'
```

`entry_type` is one of `ledger::ENTRY_TYPES`; positive `amount_ct` is a debit,
negative a credit.

### Vorauszahlung (§ 40 Abs. 1 EnWG)

```bash
curl -X PUT "http://accountingd:9380/api/v1/accounts/51238696012/vorauszahlung" \
  -H "Content-Type: application/json" \
  -d '{
    "_typ": "VORAUSZAHLUNG",
    "betrag": { "_typ": "BETRAG", "wert": "75.00", "waehrung": "EUR" },
    "gueltigkeit": { "_typ": "ZEITRAUM", "startdatum": "2026-08-01" }
  }'
```

This sets `abschlag_ct = 7500` in the same write. Without a stored object the
`GET` synthesises one from `abschlag_ct`.

---

## Offene Posten and balance integrity

Every booking records a FIFO **Zahlungszuordnung** in doubleentry's clearing
register — one clearing per matched pair, the whole run in one transaction:
open credits (payments, Abschläge,
Gutschriften) against the oldest open debits (Einzelbewertung, § 252 Abs. 1
Nr. 4 HGB). `open-items` lists the
debits with a residual above zero, oldest first:

```json
{
  "malo_id": "51238696012",
  "balance_ct": 8500,
  "balance_eur": "85.00",
  "open_item_count": 2,
  "open_items": [
    { "entry_id": "…", "entry_type": "RECHNUNG", "amount_ct": 12000,
      "outstanding_ct": 4500, "booking_date": "2026-06-15",
      "document": "R2026-06-001" },
    { "entry_id": "…", "entry_type": "MAHNGEBUEHR", "amount_ct": 500,
      "outstanding_ct": 500, "booking_date": "2026-07-20",
      "document": null }
  ]
}
```

`POST …/clear` re-runs the match (a no-op when cleared); `POST
/clearings/{id}/reset` releases a mis-assignment and keeps the record of it.

`GET /api/v1/trial-balance` gives Soll/Haben/Saldo per GL account with the
Kontokorrent leaves aggregated into one Debitoren line; `balanced: true` holds
by construction.

`POST …/reconcile` returns `{ is_consistent, cached_balance_ct,
recomputed_balance_ct, drift_ct }`; `?repair=true` resets the cache from the
ledger. Drift is not expected, because the cache is set absolutely.

`GET /api/v1/aging` buckets overdue accounts by the oldest unresolved
`dunning_cases.issued_at`, falling back to `accounts.updated_at`.

---

## Mahnwesen

```mermaid
graph LR
    trigger["verzug_ct > 0, oldest charge older<br/>than grace_days, no open case"]
    a1["Mahnstufe 1 + fee1"]
    a2["Mahnstufe 2 + fee2"]
    a3["Mahnstufe 3 + fee3<br/>→ Sperr-Sequenz"]
    resolved["resolved"]
    trigger --> a1 -->|"due_date passed"| a2 -->|"due_date passed"| a3
    a1 & a2 & a3 -->|"paid"| resolved
```

With `dunning_auto_enabled = true` a daily worker escalates (idempotent through
`auto_dunning_runs`) and then runs the [Sperr-Sequenz](#sperr-sequenz). Its
first step closes every open case whose account owes nothing and clears its
§§ 41f/41g state, so a paid-up customer is never walked into disconnection.

`POST /api/v1/dunning/{account_id}/escalate` is the manual override. It takes
the Mahnstufe and the Zahlungsfrist in days as required fields — they are what
the Mahnung tells the customer, so an omitted one is refused, not defaulted.
The automatic run takes the Zahlungsfrist from
`dunning_zahlungsfrist_stufe{1,2,3}_tage` (at least 1) and the Mahngebühr from
`dunning_fee_stufe{1,2,3}_ct` (at least 0; `0` charges none); with
`dunning_auto_enabled = true` each is required, and the daemon refuses to start
without it.

An account with a live Mahnsperre of any ground or an `ACTIVE` payment plan is
not dunned: the run opens no Mahnstufe 1, escalates no open case and charges no
Mahngebühr. A lifted or lapsed lock and a plan that is no longer `ACTIVE`
re-open dunning on the next run.

**An EEG plant account is never dunned.** An account an EEG receipt was booked
to (`pg::is_eeg_anlagenkonto`, read off `eeg_belege`) is the plant operator's,
and what the operator owes back of an overpayment is no payment obligation from
a supply contract. Such an account is not an Offener Posten, the worker opens
and escalates no case on it, the Sperr-Sequenz skips it, and the manual
escalation is `422` (`code: eeg_anlagenkonto`); `create_dunning_case` refuses it
in the statement that writes the case. The claim is served by
`GET /api/v1/eeg/rueckforderungen`.

**The Mahnung document.** Every open case without a document is rendered as a
`MAHNUNG` through `outputd` (`outputd::document::mahnung::MahnungView`) and
queued on the customer's channels; the document id is stamped on the case.

Set `outputd_url` **and** `vertragd_url`: accountingd holds no customer master,
and a case whose recipient cannot be resolved is not documented, because an
unaddressed Mahnung is not Textform (§ 126b BGB). The Posten are the live open
receivables after clearing; Verzugsschaden is on its own lines; the § 41f Abs. 1
threat block prints only once `sperrandrohung_at` is set.

### Sperr-Sequenz

Payment-default disconnection of a Haushaltskunde follows **§§ 41f/41g EnWG**
(consolidated version of 23.12.2025, BGBl. 2025 I Nr. 347). The daily worker
calls `sperr::run_sperr_sequence` every cycle and advances each qualifying
Mahnstufe-3 case one phase:

| Phase | Trigger | Action | Basis |
|---|---|---|---|
| 1. Sperrandrohung | Mahnstufe 3, both thresholds cleared, no lock | `de.mako.accounting.sperrandrohung`; sets `sperrandrohung_at` | § 41f Abs. 1 |
| 2. Sperrankündigung | `sperrandrohung_frist_days` (default 28) after the Androhung | `de.mako.accounting.sperrankuendigung`; `geplantes_sperrdatum` = today + `sperrankuendigung_frist_werktage` (default 8) Werktage | § 41f Abs. 5 |
| 3. Sperrauftrag | `geplantes_sperrdatum` reached | `gpke.sperrung.beauftragen` → **ORDERS 17115** via makod; `de.mako.accounting.sperrauftrag` | § 41f |
| 4. Entsperrauftrag | arrears settled, an Abwendungsvereinbarung accepted, or Schutzbedürftigkeit found | `gpke.entsperrung.beauftragen` → **ORDERS 17117**; `de.mako.accounting.entsperrauftrag` | § 41f Abs. 7 |

Phases 1 and 2 commit the state and the event in one transaction. Phase 3 marks
the case **before** enqueueing, so a lost announcement is replayable and a
second disconnection order is impossible. Phase 4 is a sweep because restoration
is owed *unverzüglich* without the customer asking. Phases 3 and 4 are market
messages: on the NB side the order lands in processd's
[Sperr-/Entsperrauftrag queue](https://hupe1980.github.io/mako/docs/services/processd/#sperr-entsperrauftrag-queue-nb-role),
which answers with ORDRSP 19116/19117 and reports execution with IFTSTA 21039,
tracked by the LF's `gpke-sperrung-lf` process.

**Thresholds (§ 41f Abs. 3), re-checked at every phase.** The case stays eligible
only while both hold:

- Satz 2: Zahlungsverzug ≥ `sperrung_threshold_ct` (default 100 EUR);
- Satz 1: Zahlungsverzug ≥ **2×** the monthly `abschlag_ct`, or, with no
  Abschlag, ≥ **⅙** of the last annual bill (`jahresabschluss_runs.annual_bill_ct`).
  With neither on record the case is excluded.

The Zahlungsverzug is `accounts.verzug_ct`: open debit residuals after clearing,
less Verzugsschaden (Mahngebühren, Verzugszinsen, Pauschale), less open
Forderungseinwände. It is refreshed absolutely on every posting, every objection
and at the start of each run. Fees are excluded so the dunning cannot push a
customer over the threshold it is measured against.

**Notice content (§ 41f Abs. 6).** Both notices carry the Grund and the expected
`sperrkosten_ct` / `entsperrkosten_ct` (a Pauschale is permitted under § 41f
Abs. 7 S. 2 if it does not exceed actual cost); the Androhung adds the § 41f
Abs. 4 avoidance options. Unset costs announce a free disconnection.

**Configuration gates.** Without `makod_url` the sequence does not run (startup
warning); `makod_url` without `makod_api_key` is a startup error. Without
`erp_webhook_url` the notice phases pause, because the ERP renders and sends the
letters, and nothing progresses to a Sperrauftrag (a warning every cycle).

The § 41g Abs. 3–6 Sozialhilfeträger flow is the ERP's, off the emitted events;
the Abwendungsvereinbarung terms (zinsfrei, 6–18 months, 12–24 above 300 EUR)
ride on `de.mako.accounting.abwendung.angeboten`.

### Mahnsperren

Every halt is a row in `dunning_locks`, **account-scoped**, with a ground, a
validity and the operator who set it:

| `grund` | Norm | Meaning |
|---|---|---|
| `abwendungsvereinbarung` | § 41g Abs. 1 S. 10 | Accepted in Textform before the disconnection; bars it |
| `schutzbeduerftigkeit` | § 41f Abs. 2 | Konkrete Gefahr für Leib oder Leben |
| `zahlungsaussicht` | § 41f Abs. 1 S. 2 | Hinreichende Aussicht auf Zahlung |
| `operator` | — | Operator decision; a note is required |
| `insolvenz` | § 87 InsO | The debtor is in Insolvenz |

Lifting with **`vereinbarung_gebrochen`** applies § 41g Abs. 1 S. 11: the
Ankündigung state is cleared, so the sequence resumes with a fresh 8-Werktage
announcement, and `de.mako.accounting.abwendung.gebrochen` is emitted.
Open-ended locks are allowed and listed by
`GET /api/v1/dunning/locks/review?older_than_days=90`.

### Forderungseinwände (§ 41f Abs. 3 S. 3–5)

Amounts kept **out of the Verzug** rather than halts — the sequence stops by
itself when what remains falls below the thresholds:

| `art` | Norm |
|---|---|
| `forderung_bestritten` | S. 3 — schlüssig bestritten, not titled |
| `preiserhoehung_bestritten` | S. 4 |
| `schlichtung` | S. 5 — before a § 111b EnWG Schlichtungsverfahren |
| `ratenzahlung_nicht_faellig` | S. 3 — instalments not yet due |

Recording or closing one refreshes `verzug_ct` immediately.

### Verzugszinsen (§ 288 BGB)

```bash
curl -X POST "http://accountingd:9380/api/v1/accounts/51238696012/interest-charges" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "invoice_reference": "R2026-05-001",
    "principal_ct":      50000,
    "period_from":       "2026-06-15",
    "period_to":         "2026-07-15"
  }'
```

The rate follows the account's `verbraucher` (§ 13 BGB), which vertragd
writes from the contract and nothing else can: Cedar `sync-verbraucher` is
granted only to the principal `vertragd` — name vertragd's
`[[oidc.service_keys]]` entry so — and an operator token is refused. Without
authentication (`allow_insecure_no_auth`) the caller is `dev-admin`, so the
status stays unrecorded there.

| `verbraucher` | Rate | Basis |
|---|---|---|
| `true` | Basiszinssatz + 5 pp | § 288 Abs. 1 BGB |
| `false` | Basiszinssatz + 9 pp | § 288 Abs. 2 BGB |
| not recorded | Basiszinssatz + 5 pp | § 288 Abs. 1 BGB — Abs. 2 needs a Rechtsgeschäft „an denen ein Verbraucher nicht beteiligt ist" |

The Basiszinssatz (§ 247 BGB, announced by the Deutsche Bundesbank on 1 January
and 1 July) is read from `ecb_base_rates`, seeded through 01.07.2026 (1.27 %
from 01.07.2025, unchanged on 01.01.2026, 1.52 % from 01.07.2026); add later
rates by SQL. A period without a seeded rate **refuses the request**.
`interest_ct = principal_ct × rate × days / 36500`, integer only, booked as
`VERZUGSZINSEN`; `rate_segments` itemises each rate in force across a Stichtag.

### Pauschale (§ 288 Abs. 5 BGB)

Every dunning step on an account with `verbraucher = false` (§ 13 BGB, from
the vertragd contract) claims one Pauschale of 40 EUR per
open Entgeltforderung — a `RECHNUNG` or an `ABSCHLAG` — keyed on the receivable,
so a second Mahnung for the same claim books none. A Verbraucher owes none, and
an account whose status is not recorded is charged none.

Satz 3 credits the Pauschale against the Mahngebühren of the same Verzug (those
booked since the oldest open Entgeltforderung, so with several open claims the
Mahngebühren are credited against all their Pauschalen together): each step
books the Anrechnung
`min(Pauschalen, Mahngebühren)` not yet credited, in the step's transaction, as
a negative `VERZUGSPAUSCHALE`. The customer pays the larger of the two, never
both in full, and the Pauschale never goes negative. It books to its own GL
account, neither Energieerlöse nor Zinserträge, and is Verzugsschaden: it is
not part of the § 41f Abs. 3 Zahlungsverzug.

### Payment plans

```bash
curl -X POST "http://accountingd:9380/api/v1/accounts/51238696012/payment-plans" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "total_ct":        30000,
    "installment_ct":  10000,
    "billing_day":     1,
    "first_due_date":  "2026-08-01",
    "dunning_case_id": "a1b2-...",
    "note":            "Customer agreed to payment plan #42"
  }'
```

The plan is created `ACTIVE` with `ceil(total_ct / installment_ct)` instalments,
the last covering the remainder; `installment_ct ≤ 0` is refused. `DELETE
/api/v1/payment-plans/{id}` sets `CANCELLED`. An `ACTIVE` plan keeps the
account out of every phase of the Sperr-Sequenz.

When the plan is the Ratenzahlung of an Abwendungsvereinbarung, name its lock
as `abwendung_lock_id`; it must be a live `abwendungsvereinbarung` lock on the
same account.

The daily worker, before the Sperr-Sequenz, runs `pg::run_payment_plans`, one
transaction per plan:

- **Matching.** The cash booked on the account since the day the plan was made
  (`ZAHLUNG` less `BANKRUECKLAST` and `SEPA_STORNO`) pays the instalments in
  schedule order, recomputed each run. Every payment on the account counts,
  a current Abschlag's included, as the FIFO Zahlungszuordnung settles the
  oldest debt first: a covered instalment is `PAID` with the
  completing payment's `ledger_entry_id` and booking date as `paid_at`; one a
  Rücklast uncovers returns to `PENDING`. All `PAID` or `WAIVED` → `COMPLETED`.
- **Default.** An instalment still unpaid after its due date (against
  `heute()`) turns `OVERDUE` and the plan `DEFAULTED` — on the first run after
  the due date, with no grace for a payment the bank import has not yet
  booked. A linked
  Abwendungsvereinbarung lock is lifted with `vereinbarung_gebrochen` in the
  same transaction (§ 41g Abs. 1 S. 11 EnWG): the Ankündigung is cleared and
  `de.mako.accounting.abwendung.gebrochen` emitted, so the case resumes at a fresh
  § 41f Abs. 5 Ankündigung with no operator call.

`COMPLETED`, `CANCELLED` and `DEFAULTED` are final.

---

## Jahresabschluss (§ 40 Abs. 1 EnWG)

```bash
# Preview — POST like the commit; the route has no GET
curl -X POST "http://accountingd:9380/api/v1/jahresabschluss/51238696012?year=2025&dry_run=true"

# Commit
curl -X POST "http://accountingd:9380/api/v1/jahresabschluss/51238696012?year=2025"
```

```json
{
  "malo_id":                  "51238696012",
  "year":                     2025,
  "rechnung_sum_ct":          120000,
  "abschlag_net_ct":          0,
  "zahlung_net_ct":           -108000,
  "verzugsschaden_ct":        0,
  "sonstige_ct":              0,
  "settlement_ct":            12000,
  "settlement_eur":           "120.00",
  "new_monthly_abschlag_ct":  10000,
  "action":                   "NACHZAHLUNG",
  "committed":                true,
  "ce_id":                    "jahresabschluss:51238696012:2025"
}
```

`settlement_ct` is the net of the year's **whole** Kontokorrent movement; the
buckets partition it and `sonstige_ct` takes any kind they do not name.

- **Nachzahlung** (> 0): no entry is written; the balance is the open
  receivable.
- **Erstattung** (< 0): a clearing debit zeroes the credit and a **pain.001**
  refund goes to the stored IBAN (`de.mako.accounting.erstattung.faellig`); without
  an IBAN the credit is carried forward.

It is idempotent per `(tenant, malo_id, year)` (`jahresabschluss_runs`), resets
`abschlag_ct` to the year's supply billing ÷ 12 (Verzugsschaden excluded), and
emits `de.mako.accounting.jahresabschluss.abgeschlossen` in the same transaction.

**Annual worker (§ 40b Abs. 1 EnWG).** `jahresabschluss_auto_enabled = true`
settles the previous year for every account without a run row, through the same
function, at most 500 accounts per daily pass, and not before
`jahresabschluss_start_day` (default `"02-01"`): the settlement moves money, and
§ 40c Abs. 2 EnWG leaves six weeks to render the bill.

---

## Festschreibung and audit proofs

Sealing (GoBD, § 146 AO, § 239 HGB) closes calendar months in order: `POST
/periods/2026-01/seal` seals every open month through January, each committing
its closing balances per account to the log. A booking dated in a sealed month
is refused (`ledger.301`) and parks; a correction books into an open month
(§ 146 Abs. 4 AO).

```bash
curl -X POST "http://accountingd:9380/api/v1/periods/2026-01/seal"
# → { sealed_through: "2026-01-31", count, sealed: [{ period, position, start, end }] }

curl "http://accountingd:9380/api/v1/periods/seals"
# → { count, sealed_through, verified, audit_error, log_size, seals: […] }
```

`verified` is doubleentry's `audit`: the whole log is replayed and every
balance, clearing and seal compared with it.

| Question | Endpoint | Returns |
|---|---|---|
| Is this booking in the books? | `GET /entries/{entry_id}/proof` | `leaf_hash`, `tree_size`, `tree_root`, `verified`, `proof` |
| What did this customer owe at the balance-sheet date (§ 147 AO)? | `GET /periods/{id}/balance-proof?malo_id=&mp_id=` | `balance_ct`, `debits_ct`, `credits_ct`, `verified`, `tree_size/root`, `proof` |
| Has the journal only been appended to? | `GET /entries/consistency-proof?since=<tree_size>` | `archived_size/root`, `current_size/root`, `verified`, `proof` |

All three verify against a head alone, without this service; each is verified
before it is published.

- A customer whose account opened after the month was sealed has no sealed
  balance: `404`, never a manufactured zero.
- The consistency proof refuses `since=0`: every log extends the empty tree,
  so it would verify against anything.
- **Refusal, absence and failure answer differently** on every ledger-backed
  route. A ledger refusal is `422` with code `ledger.<n>` (`409` for `200`, a
  reused key); an unknown entry or an unsealed month is `404`; a ledger that is
  unavailable is `503`; a store that fails or books that do not audit is `500`
  with an `error_id` the log line carries.

---

## Bank statement import

| Endpoint | Input | Use when |
|---|---|---|
| `/api/v1/payments/import/camt053` | camt.053 XML | End-of-day statement — the authoritative record, with closing balance |
| `/api/v1/payments/import/camt054` | camt.054 XML | Intraday notifications |
| `/api/v1/payments/import/camt052` | camt.052 XML | Intraday account report |
| `/api/v1/payments/import` | flat JSON array | No camt available |

Prefer camt: `EndToEndId`, `NtryDtls/Btch` and return reasons do not survive
flattening.

Every ISO 20022 import — camt.05x, pain.002, camt.029 — is read only under a
namespace the `sepa` reader supports, with exactly one matching message body;
anything else is `422`.

```bash
curl -X POST "http://accountingd:9380/api/v1/payments/import/camt053" \
  -H "Content-Type: application/xml" --data-binary @statement.xml

curl -X POST "http://accountingd:9380/api/v1/payments/import" \
  -H "Content-Type: application/json" \
  -d '[{ "iban": "DE89 3704 0044 0532 0130 00", "amount_eur": "155.42",
          "reference": "Rechnung R2026-06-001", "date": "2026-07-10",
          "bank_transaction_id": "NTRY-REF-20260710-001" }]'
```

Response: `{ "accepted", "deduplicated", "skipped", "unmatched", "malformed",
"failed", "total" }`. `skipped` is the sum of three:

| | Meaning | Action |
|---|---|---|
| `malformed` | Bad IBAN, amount or date (`warn`) | Fix the export |
| `unmatched` | No account claims it (`warn`) | Kept in `unmatched_payments`; assign it |
| `failed` | Lookup or ledger write errored (`error`) | Not applied — retry |

**Only `BOOK` entries post.** `INFO`, `PDNG` and `FUTR` are counted `not_booked`;
an append-only ledger cannot un-book a provisional entry. Status, direction and
currency codes are read in their exact ISO spelling, so `book` or `crdt` is not
recognised.

**Only a determined EUR amount posts.** A booking whose `Amt`, `Amt/@Ccy` or
`CdtDbtInd` is missing, unreadable or contradictory, that carries a significant
sub-cent digit, or that is denominated in another currency is skipped with a
`warn` naming what arrived (`sepa::camt_posting_ct`): an absent currency is not
EUR and an absent direction is not a credit.

**Sign.** camt is signed from the bank's side; `sepa::bank_to_ledger_ct` is the
single negation every path uses. A row gives money back when it carries a return
reason **or** debits the account.

**Resolving the customer**, strongest evidence first (`matched_by` records the
rung): `iban` → `end_to_end_id` (a reference accountingd generated) →
`remittance_token` (an exact Mandatsreferenz or MaLo-ID among whole tokens of
the Verwendungszweck, matched against the generated
`sepa_mandates.mandatsref_norm`, so `MND 000123` and `mnd000123` both find
`MND-000123`).

A reference naming two customers resolves to nothing and counts `unresolved` —
alert on it.

**Unmatched lines are kept.** Every booked line no rung attributes — flat or
camt — is stored in `unmatched_payments` (amount in the Kontokorrent sign, value
date, Verwendungszweck, `EndToEndId`, the IBAN masked to `DE…3000`, the door).
`GET /api/v1/payments/unmatched` (MCP `list_unmatched_payments`) lists the open
ones; `POST /api/v1/payments/match` proposes an account; `POST
/api/v1/payments/{payment_id}/assign` books the line as `ZAHLUNG` or
`BANKRUECKLAST` under the key `bank:{bank_transaction_id}`, writes its
`bank_import_log` row and its `de.mako.accounting.payment.imported` /
`.bankruecklast` (`matched_by: "manual"`) and closes the line in one
transaction. A later import that resolves the same line closes it in its own
booking's transaction; an assigned line imported again is a duplicate.

**Batches.** `NtryDtls/Btch/PmtInfId` is stored on `bank_import_log` and counted
as `batches_matched`; a booking whose `EndToEndId` names a collection sets that
entry `SETTLED`, or `RETURNED` for an R-transaction. Batches expand per
`TxDtls`, reading the return reason per detail. Details that do not add up to the
entry total are logged and returned as `unreconciled_batches`.

**Deduplication** is on `bank_transaction_id` (`AcctSvcrRef`, per detail by
`EndToEndId`; otherwise a hash of `iban|amount|date|reference`), tenant-scoped in
`bank_import_log`, so an intraday report and the evening camt.053 book once.

**IBAN lookup** uses `iban_hash`, a keyed BLAKE3 of the normalised IBAN under
`iban_hash_secret`, so matching works when the IBAN column is encrypted.
Without the secret the hash is unkeyed and a startup warning says so (dev only).
Amounts parse with `sepa::ct_from_eur_str`, integer only.

---

## SEPA

accountingd uses the [`sepa`](https://crates.io/crates/sepa) crate.
Defaults are `pain.008.001.08` and `pain.001.001.09`; `pain008_schema` /
`pain001_schema` pin another (an unknown value is a startup error). Every
message is validated before serialisation, and the crate's CI checks output
against the ISO schemas and the Deutsche Kreditwirtschaft GBIC 5 subsets.

```mermaid
graph LR
    pain008["pain.008 /sepa/run"] --> entries["sepa_collection_entries"]
    pain002["pain.002 /sepa/pain002"] -->|EndToEndId| entries
    camt["camt.052/053/054"] -->|Btch/PmtInfId| entries
    entries --> pain007["pain.007 /sepa/reversals"]
    entries --> camt055["camt.055 /sepa/recalls"]
    camt029["camt.029 /sepa/camt029"] --> entries
    pain001["pain.001 EEG + Erstattung"] --> payouts["eeg_payout_orders"]
    pain002 -->|EndToEndId| payouts
```

### Structured addresses

EPC153-22 v2.2 (30 September 2026) permits structured, hybrid and unstructured
addresses, with no end date set for the unstructured form (EPC Payment Scheme
Management Board decision of 9 September 2026, all five scheme rulebooks).
accountingd emits the **structured** form — `TwnNm` and `Ctry` plus street,
building number, post code and subdivision — or no `PstlAdr` at all.

| Party | Element | Source |
|---|---|---|
| The Lieferant | `Cdtr/PstlAdr` (pain.008, pain.007) · `Dbtr/PstlAdr` (Jahresabschluss-Erstattung pain.001) | `[creditor_address]` |
| The Netzbetreiber | `Dbtr/PstlAdr` (EEG pain.001) | `[eeg.debtor_address]` |
| A direct-debit customer | `Dbtr/PstlAdr` (pain.008) | `sepa_mandates.debtor_*` |
| An EEG Anlagenbetreiber | `Cdtr/PstlAdr` (EEG pain.001) | the current receipt's `zahlungsempfaenger_anschrift` (einsd's Einspeiser, snapshotted in `eeg_belege.creditor_*`), else `accounts.addr_*` |
| A payee | `Cdtr/PstlAdr` (pain.001) | `accounts.addr_*` (BO4E `Zahlungsinformation` has no address) |

A half-filled address is refused (`AddressParts::to_postal_address`); `Ctry` is
checked against ISO 3166; the legacy DK schemas (`pain.008.003.02`,
`pain.001.003.03`) carry no structured address, so it is dropped with a warning
— the stored address reaches the bank only on the current schema versions.

### pain.008 direct debit

```bash
curl -X POST "http://accountingd:9380/api/v1/sepa/run" > batches.json
```

One message per collection date, one `PmtInf` group per `SequenceType` present
(FRST, RCUR, FNAL, OOFF; `PmtInfId = <MsgId>-<SEQ>`) — the EPC SDD Core Rulebook
§ 3.8 separates FRST and RCUR. The XML is returned only after the run and its
entries are archived; a date already dispatched answers **`409`**, and the
scheduler holds an advisory lock so one replica builds the day's batch.

```json
{
  "run_id": "9f1c…",
  "msg_id": "DD-2026-07-25",
  "collection_date": "2026-07-25",
  "entry_count": 43,
  "total_ct": 320000,
  "groups": [
    { "sequence_type": "FRST", "payment_info_id": "DD-2026-07-25-FRST", "entry_count": 1,  "total_ct": 5000 },
    { "sequence_type": "RCUR", "payment_info_id": "DD-2026-07-25-RCUR", "entry_count": 42, "total_ct": 315000 }
  ],
  "xml": "<?xml version=\"1.0\"?>..."
}
```

- `creditor_id` (Gläubiger-ID, EPC AT-02) is checked by
  `sepa::validate_creditor_id` and required. A missing `creditor_id` or
  `creditor_iban` is a configuration gap and answers **`500`** with an
  `error_id` the log line carries; an invalid one, or a run with no billable
  mandate, is **`422`** naming it.
- `Mandatsreferenz` is the `EndToEndId`, ≤ 35 characters (registration check and
  DB `CHECK`).
- `Purp/Cd` follows the account's Sparte from `de.mako.billing.rechnung.erstellt`:
  `ELEC`, `GASB`, `WTER`, `ENRG` (district heating); `STROM_UND_GAS` emits none.
- `Ustrd` is `"Abschlag YYYY-MM"`; the 140-character limit binds after
  transliteration.
- A mandate moves from `FRST` to `RCUR` after its first collection
  (`first_collected_at`).

**Pre-notification.** A daily worker builds and dispatches the pain.008
`sepa_pre_notification_days` (default **14** calendar days, clamped to 1–60)
before each `billing_day` and emits `de.mako.accounting.payment.due`, which the ERP
turns into the debtor's pre-notification (EPC SDD Core Rulebook). This is not
the bank submission lead time.

### Collection entries

| `status` | Set by | From | Typical `status_reason` |
|---|---|---|---|
| `SUBMITTED` | pain.008 | — | — |
| `SETTLED` | accepted pain.002 or a camt booking | `SUBMITTED` | — |
| `REJECTED` | pain.002 `RJCT` (never left the bank) | `SUBMITTED` | `AM04` |
| `RETURNED` | camt R-transaction | `SUBMITTED`, `SETTLED` | `MS03` |
| `REVERSED` | pain.007 | `SUBMITTED`, `SETTLED` | `MD06` |
| `RECALLED` | accepted camt.055 via camt.029 | `SUBMITTED` | `CNCL` |

Each transition is guarded on its legal predecessors; a replayed or impossible
one changes nothing and is logged. A pain.002 rejecting a whole file (matched on
`OrgnlMsgId`) moves every `SUBMITTED` entry of the run to `REJECTED`. Entries
hold no IBAN — it stays on `sepa_mandates`, so erasure works from one place.
Regenerating a run for the same date replaces its entries.

### pain.002 status report

```bash
curl -X POST "http://accountingd:9380/api/v1/sepa/pain002" \
  -H "Content-Type: application/xml" --data-binary @status-report.xml
```

| About | Matched on | Effect |
|---|---|---|
| an EEG payout (pain.001) | `eeg_payout_orders.end_to_end_ref` | status, reason, `settled_at`, VoP outcome |
| a collection (pain.008) | `sepa_collection_entries.end_to_end_id` | `SETTLED` / `REJECTED` + `de.mako.accounting.sepa.collection-rejected` |

`OrgnlEndToEndId` or `OrgnlInstrId` is the key; a report naming neither is
`unmatched`. A missing `TxSts` falls back to the group status; no status is not
an acceptance; `PDNG` and verification statuses are not recorded as lifecycle
steps. A status outside ISO 20022 — a lower-case `rjct` included — is applied to
nothing and counted `unrecognised`. `NbOfTxsPerSts` is returned as
`status_counts`, each row with `status`, `count` and `total_ct` beside the bank's
own text (`status_raw`, `count_raw`, `total_raw`); an unreadable count is
`null`, never `0`.

**A rejected collection is not a Bankrücklastschrift**: no money moved, so no
`BANKRUECKLAST` is booked and the receivable stays open. A settled-then-returned
collection arrives as a camt R-transaction (`de.mako.accounting.bankruecklast`).

**Verification of Payee** (mandatory for euro credit transfers since 9 October
2025) arrives in the same pain.002 on a separate axis:

| Code | `vop_outcome` | Meaning |
|---|---|---|
| `RCVC` | `MATCH` | Name matched |
| `RVMC` | `CLOSE_MATCH` | Actual name in `AddtlInf`, stored in `vop_name` |
| `RVNM` | `NO_MATCH` | Name did not match |
| `RVNA` | `NOT_APPLICABLE` | No answer, timeout (`AB11`) or PSP outside the scheme (`AG03`) |
| `RVCM` | group level | The file contains mismatches |

Anything but a match emits `de.mako.accounting.payee.verification-mismatch`; whether
to execute is the operator's decision. The codes are the Deutsche
Kreditwirtschaft's pain.002 conventions (DFÜ-Abkommen Anlage 3 V3.9
Kap. 2.2.6).

### camt.055 recall and pain.007 reversal

A **recall** asks the bank to stop a collection still `SUBMITTED`:

```bash
curl -X POST "http://accountingd:9380/api/v1/sepa/recalls" \
  -H "Content-Type: application/json" \
  -d '{ "run_id": "…", "reason_code": "UPAY", "end_to_end_ids": ["MND-4711", "MND-4712"] }'
```

`reason_code` is a `CancellationReason5Code` — `UPAY` (default), `DUPL`, `AGNT`,
`CURR`, `CUST`, `CUTA`, `TECH`, `FRAD`. Without `end_to_end_ids` the whole
message is recalled (`GrpCxl`). Nothing changes until the bank answers;
`debtor_agent_bic` must be configured (`500` with an `error_id` otherwise).

The camt.029 is matched on `RslvdCase/Id` (an unknown case is `404`): `CNCL` or
all `ACCR` → `RECALLED`; `RJCR` leaves the collection; `PDCR` or an unknown
outcome (a lower-case `cncl` included) leaves the case open. Events: `de.mako.accounting.sepa.recall-requested`,
`de.mako.accounting.sepa.recall-resolved`.

A **reversal** gives back a `SETTLED` collection:

```bash
curl -X POST "http://accountingd:9380/api/v1/sepa/reversals" \
  -H "Content-Type: application/json" \
  -d '{ "collection_entry_id": "…", "reason_code": "AM05" }'
```

`reason_code` is an `ExternalReversalReason1Code`, default `MS02`; `AM05`
duplicate collection, `DUPL` duplicate payment, `CUST` customer request.
`reversed_amount_ct` reverses part, never more than collected.

`OrgnlTxRef` is restated from stored data (the DK subset requires it), one
reversal per collection (unique index; a second is `409`), a `SEPA_STORNO`
re-opens the receivable, and an erased mandate makes a reversal impossible. It
emits `de.mako.accounting.sepa.reversal-issued` and is deliberately not an MCP tool.

Revoke a mandate (§ 58 ZAG) with `DELETE /api/v1/sepa/mandates/{mandate_id}`.

### pain.001 — EEG payout (§ 25 EEG 2023)

**The Netzbetreiber pays, the Anlagenbetreiber is paid.** § 19 Abs. 1 EEG 2023:
Betreiber von Anlagen „haben für den in diesen Anlagen erzeugten Strom gegen den
Netzbetreiber einen Anspruch auf 1. die Marktprämie nach § 20, 2. eine
Einspeisevergütung …, 3. einen Mieterstromzuschlag …". The
Direktvermarktungsunternehmer is not the payee, and no Lieferant is a party. So
the plant account is kept under `[eeg] nb_mp_id` — not the Lieferant's
`lf_mp_id` — and the pain.001 debits `[eeg] debtor_iban` in the name
`[eeg] debtor_name`, with `[eeg.debtor_address]` as `Dbtr/PstlAdr`; neither
falls back to `lf_mp_id` or `creditor_name`, because the Netzbetreiber is often
a legal entity of its own. Without `nb_mp_id` an EEG receipt is refused
`503 eeg_nb_not_configured`, so einsd redelivers it once it is set; without
`debtor_iban` or `debtor_name` the payout run is refused
`503 eeg_debtor_not_configured`. The payout confirmation and a Rückzahlung book
on the account the receipt credited.

einsd announces every settlement receipt as `de.mako.eeg.verguetung.berechnet` or
`de.mako.eeg.marktpraemie.berechnet` — a zero included — carrying `receipt_id`,
`korrektur_von` (the receipt a § 147 AO correction supersedes), the period and
`ketten_folge`. A period — plant (`tr_id`), billing year and month — is one
**receipt chain**, and every receipt in it states the period's *whole* amount;
the current receipt is the one with the highest `ketten_folge`, the position
einsd assigns when it writes the receipt — never the CloudEvent `time`, which
replica clocks can skew. A second event at a taken position is `422`.
accountingd records each in `eeg_belege` and applies two rules
(`accountingd::eeg_auszahlung`):

- **The ledger books what a receipt changes.** The first receipt credits its
  amount, a correction the difference to the current receipt (a lower one
  debits), a receipt overtaken by a later one nothing. The receipt and its
  booking draft commit in one transaction.
- **A payout pays what is outstanding:** the current receipt less what was
  already paid or ordered for the chain — every order not `RJCT`/`CANC`, plus
  every Aufrechnung (§ 13 Abs. 1 Satz 2 EnFG), less every Rückzahlung. A receipt
  corrected from 100,00 € to 110,00 € pays 10,00 € more; one corrected to
  90,00 € — or re-settled to `kein_anspruch` at 0 — pays nothing and leaves the
  difference owed back, listed by `GET /api/v1/eeg/rueckforderungen`. A
  replayed event finds nothing outstanding. Vergütung and Marktprämie are paid
  alike.

The Kontokorrent follows the money. A receipt credits the operator; the first
`ACSC` for its payout — from `POST /api/v1/sepa/pain002` or the status `PUT` —
books `EEG_AUSZAHLUNG`, so a paid 100,00 € leaves the account at 0, and a lower
correction then leaves the amount owed back as a debit — never dunned (see
[Mahnwesen](#mahnwesen)). A settled order keeps
`ACSC`; a later status is `409` on the `PUT` and ignored in a pain.002.
`POST /api/v1/eeg/rueckzahlungen` records the operator's repayment
(`tr_id`, `billing_year`, `billing_month`, `amount_ct`, `eingegangen_am`), books
`EEG_RUECKZAHLUNG` and drops the chain from the list once nothing is owed;
more than is owed is `422`.

With `[eeg] auto_payout = true` each receipt is paid as it arrives;
otherwise, and to pay a chain again after a rejected order,
`POST /api/v1/eeg/payouts/run` pays the billing month's chains by the same rule.
`auto_payout = true` without a valid `debtor_iban`, `debtor_name` or
`nb_mp_id`, or with an unparseable `pain001_schema`, is refused at startup;
without `auto_payout` a missing `nb_mp_id` or `debtor_name` is a warning, and a
`nb_mp_id` that is no MP-ID is refused either way. A payout that is owed but cannot be
ordered — a pain.001 that does not build, an invalid creditor IBAN — answers the
event `500`, so einsd redelivers it; the receipt stays recorded and the run pays
it once the cause is fixed. A receipt missing its plant, billing month, receipt
id, amount or `ketten_folge` is refused `422`, never defaulted, and so is one
whose `zahlungsempfaenger_anschrift` the pain.001 could not carry (no town or
country, a country that is none, a field the address does not have).

The creditor is the event's `bank_iban` / `zahlungsempfaenger` from einsd's
Einspeiser record, else the account's `zahlungsinformation`; with neither the
chain stays outstanding and the run counts it under `skipped_no_iban`. Its
`Cdtr/PstlAdr` is the current receipt's `zahlungsempfaenger_anschrift`, else the
plant account's `addr_*` — the account is the Anlagenbetreiber's own. § 25
Abs. 1 EEG 2023 requires payment „unverzüglich nach Ende des Monats".

| Mode | `[eeg] sepa_instant` | `LclInstrm` | Settlement |
|---|---|---|---|
| SCT Inst (EU Reg 2024/886) | `true` | `INST` | < 10 s |
| SCT | `false` | absent | D+1 |

The message version comes from `pain001_schema`; SCT Inst on
`pain.001.003.03` is refused (`UnsupportedBySchema`). `ReqdExctnDt` is always
explicit.

```
created → pain001_xml stored
  └─ POST to bank_submit_url (if set) → pain002_status = PDNG
       ├─ ACCP → settled_at set
       ├─ ACSC → settled_at set, EEG_AUSZAHLUNG booked (terminal)
       └─ RJCT (reason_code) → de.mako.accounting.eeg.payout.rejected; fix the IBAN and run the payouts
```

```bash
curl "http://accountingd:9380/api/v1/eeg/payouts?malo_id=51238696012&year=2026&month=7"

curl -X POST "http://accountingd:9380/api/v1/eeg/payouts/run" \
  -H "Content-Type: application/json" \
  -d '{ "billing_year": 2026, "billing_month": 7, "instant_override": true }'

curl -X PUT "http://accountingd:9380/api/v1/eeg/payouts/a1b2c3d4-.../status" \
  -H "Content-Type: application/json" \
  -d '{ "status": "RJCT", "reason_code": "AC01" }'
```

The run answers `generated`, `skipped_no_iban`, `nothing_outstanding` and
`errors`, the last naming each chain whose pain.001 could not be built.

`eeg_payout_orders` holds, per payout:

- the payout — `payout_id`, `malo_id`, `tr_id` and `billing_year/month` of the
  chain it pays (all `NOT NULL`, so every order is attributable), `amount_ct`,
  `creditor_iban`, `payment_type` (`SCT_INST` / `SCT_CORE`), and the creditor
  address **as sent**;
- the message — `end_to_end_ref` (unique,
  `EEG-{malo}-{year}-{month}-{payout_short}`) and the full `pain001_xml`;
- the answer — the verbatim `pain002_status` (`ACTC`, `ACCP`, `ACSP`, `ACSC`,
  `ACWC`, `PART`, `PDNG`, `RJCT`, plus `CANC`), `pain002_reason`, `vop_outcome` /
  `vop_name`, `submitted_at`, `settled_at` (first accepted status — only `ACSC`
  means money moved);
- `source_ce_id` — the event of the chain's current receipt when it was made.

### Payments made, for the EnFG Belastungsausgleich

The ÜNB reimburses the Netzbetreiber „die … geleisteten Zahlungen" (§ 13 Abs. 1
Satz 1 EnFG). `GET /api/v1/eeg/enfg-zahlungen?year=&month=` serves exactly
those for one billing month, and einsd builds its EnFG ledger from them:

- a payout order whose `pain002_status` is `ACSC` — `ACCP`, `ACSP`, `ACWC`,
  `PART`, `PDNG`, `RJCT`, `CANC` and no status are not a payment made;
- every recorded Aufrechnung — „Als geleistete Zahlungen im Sinn des Satzes 1
  gelten auch Forderungen eines Anlagenbetreibers auf Zahlung, die durch
  Aufrechnung erloschen sind" (§ 13 Abs. 1 Satz 2 EnFG);
- every Rückzahlung of the month (`quelle: RUECKZAHLUNG`, a negative
  `amount_ct`): § 13 Abs. 1 Satz 1 Nr. 1 EnFG reimburses the payments
  „abzüglich der Rückzahlungen nach § 26 Absatz 1 Satz 3" EEG 2023.

A receipt whose event carries `sect52.aufgerechnet_eur` (einsd under
`[policy] sect52_aufrechnung = "aufrechnen"`) records that much as an
`EEG_52_PFLICHTZAHLUNG` Aufrechnung on its chain — the difference to what the
chain already holds — so the payout pays the rest.

`POST /api/v1/eeg/aufrechnungen` records one in `eeg_aufrechnungen`:

```json
{ "tr_id": "TR-1", "malo_id": "51238696012", "billing_year": 2026, "billing_month": 3,
  "amount_ct": 3000, "gegenforderung": "EEG_52_PFLICHTZAHLUNG", "erklaert_am": "2026-04-10" }
```

`gegenforderung` is the claim it was set off against, one per set-off the EEG
2023 admits: `EEG_52_PFLICHTZAHLUNG` (§ 52 Abs. 6 Satz 2), `ENFG_UMLAGE`
(§ 27 Abs. 1 Satz 2), `UNBESTRITTEN` (§ 27 Abs. 1 Satz 1, „soweit die Forderung
unbestritten oder rechtskräftig festgestellt ist"). A positive `amount_ct`, a
month 1–12 and a declaration date no later than today are required; the same
plant, month, Gegenforderung and day twice is `409`.

Every payout order carries the `tr_id` and billing month of the receipt chain
it pays, from the auto-payout and from `POST /api/v1/eeg/payouts/run` alike, so
einsd attributes each to its plant, month and head.

---

## GDPR Art. 17

```bash
curl -X POST "http://accountingd:9380/api/v1/accounts/51238696012/anonymize" \
  -H "Content-Type: application/json" \
  -d '{ "requested_by": "operator-1", "legal_basis": "GDPR Art. 17 - customer request #42" }'
```

Pseudonymized: `accounts.iban` and `sepa_mandates.iban`/`kontoinhaber` →
`ANONYMIZED`; `mandatsref`, `zahlungsinformation`, `vorauszahlung`, `addr_*`,
`bic`, `debtor_*` and the creditor einsd forwarded on each EEG receipt
(`eeg_belege.bank_iban` / `zahlungsempfaenger` / `creditor_*`) → `NULL`. The ledger is untouched (Art. 17(3)(b); § 257
Abs. 1, 4 HGB and § 147 Abs. 1, 3 AO — ten years for the books, eight for the
Buchungsbelege), as are the address snapshots on `eeg_payout_orders`, which
are Buchungsbelege. Each erasure is logged in `anonymization_log`; a repeat is
`409`.

---

## Events

Emitted through the outbox to `erp_webhook_url`:

| Type | When |
|---|---|
| `de.mako.accounting.abschlag.posted` | An Abschlagsforderung is raised |
| `de.mako.accounting.payment.due` | A pain.008 is scheduled — the ERP's pre-notification |
| `de.mako.accounting.payment.imported` · `de.mako.accounting.bankruecklast` | A camt payment or R-transaction is booked |
| `de.mako.accounting.sepa.collection-rejected` | pain.002 `RJCT` on a collection |
| `de.mako.accounting.sepa.reversal-issued` | A pain.007 is built |
| `de.mako.accounting.sepa.recall-requested` · `.recall-resolved` | camt.055 recorded; camt.029 decided it |
| `de.mako.accounting.payee.verification-mismatch` | VoP other than a match |
| `de.mako.accounting.eeg.payout.rejected` | pain.002 `RJCT` on an EEG payout |
| `de.mako.accounting.erstattung.faellig` | A Jahresabschluss refund |
| `de.mako.accounting.jahresabschluss.abgeschlossen` | Every committed settlement |
| `de.mako.accounting.mahnung.issued` | A Mahnstufe is reached |
| `de.mako.accounting.interest.charged` | A § 288 BGB charge is booked |
| `de.mako.accounting.sperrandrohung` · `.sperrankuendigung` · `.sperrauftrag` · `.entsperrauftrag` | Sperr-Sequenz phases |
| `de.mako.accounting.abwendung.angeboten` · `.gebrochen` | Abwendungsvereinbarung offered; broken |

---

## Database

| Table | Purpose |
|---|---|
| `accounts` | One per `(malo_id, mp_id, tenant)` — `mp_id` the Lieferant's for a customer, `[eeg] nb_mp_id` for an EEG plant: `balance_ct` and `verzug_ct` caches, `abschlag_ct`, `billing_day` (1–28), `iban` (ciphertext when `iban_encrypted`), `iban_hash`, `mandatsref`, `sparte`, `addr_*`, `vorauszahlung`, `zahlungsinformation`, `anonymized_at` |
| `ledger.*` | Journal, postings, Merkle log, seals, clearings — doubleentry's own tables, created by the migration role |
| `booking_drafts` | Every booking, staged with its business change: `entwurf`, `status` (`offen`/`gebucht`/`geparkt`/`verworfen`), rejection `code` and `meldung`, `entry_id` |
| `abschlag_forderungen` | USt rate and absorbing invoice per Abschlag |
| `sepa_mandates` | Unique per `(tenant, mandatsref)`; `sequence_type` (defaults `FRST`), `signed_at`, `revoked_at`, `first_collected_at`, `debtor_*`, generated `mandatsref_norm` |
| `sepa_collection_runs` | One per pain.008, with XML and `msg_id`; `UNIQUE (tenant, collection_date)`; `dispatch_status` |
| `sepa_collection_entries` | One per collected mandate — the attribution key for replies |
| `sepa_reversals` | One per pain.007; `UNIQUE (collection_entry_id)` |
| `sepa_recalls` | One per camt.055, with its camt.029 outcome |
| `eeg_belege` | Every EEG settlement receipt einsd announced, per receipt chain, with what its booking changed and the creditor it named (`bank_iban`, `zahlungsempfaenger`, `creditor_*` address); `PRIMARY KEY (tenant, source_ce_id)`, one per `ketten_folge` |
| `eeg_ketten` (view) | Each chain's current receipt beside what was paid or ordered for it, less repayments |
| `eeg_payout_orders` | pain.001 payouts, each for one chain's outstanding difference |
| `eeg_aufrechnungen` | EEG claims extinguished by Aufrechnung, with the Gegenforderung; `UNIQUE (tenant, tr_id, billing_year, billing_month, gegenforderung, erklaert_am)` |
| `eeg_rueckzahlungen` | Operators' repayments of an overpaid chain; `UNIQUE (tenant, tr_id, billing_year, billing_month, eingegangen_am)` |
| `interest_charges` | § 288 BGB charges with `rate_segments`; `UNIQUE (tenant, account_id, period_from, period_to)` |
| `ecb_base_rates` | Bundesbank Basiszinssatz series |
| `payment_plans` · `payment_plan_installments` | Zahlungsvereinbarungen |
| `bank_import_log` | Deduplication for all four import doors; `UNIQUE (tenant, bank_transaction_id)` |
| `unmatched_payments` | Booked bank lines no account claimed, until assigned; `UNIQUE (tenant, bank_transaction_id)`, `source` `flat`/`camt052`/`camt053`/`camt054` |
| `credit_payouts` | A Schlussrechnung's Guthaben owed back (§ 40c Abs. 3 EnWG): `due_on`, `status` `open`/`paid`/`cancelled`; `UNIQUE (tenant, rechnungsnummer)` |
| `dunning_cases` · `dunning_locks` · `forderungs_einwaende` · `auto_dunning_runs` | Dunning state, Mahnsperren, Einwände, run guard |
| `jahresabschluss_runs` | One per `(tenant, malo_id, billing_year)`; `annual_bill_ct` |
| `account_audit_log` | Insert-only master-data change log with `operator_sub` |
| `anonymization_log` | GDPR erasures |

The schema is `migrations/0001_schema.sql`.

---

## Authorization

Every handler extracts `Claims` (a JWT) and checks one Cedar action from
`policies/accountingd.cedar`. accountingd refuses to start without `[oidc]` and
`erp_hmac_secret` unless `allow_insecure_no_auth = true` is set explicitly.

| Action | Covers | Roles |
|---|---|---|
| `read-account` | Account, balance, Kontoauszug, open items, Vorauszahlung, plans, interest, business-partner views, payment match | any caller of the tenant |
| `read-banking` | Mandates, `Zahlungsinformation`, collection entries | `LF`, `MSB` |
| `read-eeg-payouts` | EEG payout orders and their pain.001 XML, MCP `list_eeg_payouts` | **`NB`** |
| `read-books` | Trial balance, aging, Offene Posten, dunning list, seals, proofs | `LF`, `MSB` |
| `write-account` | Account master data, Abschlag, Vorauszahlung, `Zahlungsinformation`, business-partner link | `LF`, `MSB` |
| `post-entry` | Manual booking, clearing, reset, interest, reconcile | `LF`, `MSB` |
| `manage-sepa` | Mandates, collection run, pain.002, pain.007 | `LF`, `MSB` |
| `import-payments` | camt and flat imports | `LF`, `MSB` |
| `run-payout` | EEG payout run and pain.002 status | **`NB`** |
| `read-enfg` | EEG/KWKG payments made per month (`/eeg/enfg-zahlungen`), EEG Rückforderungen | **`NB`** |
| `record-aufrechnung` | Record an Aufrechnung (`/eeg/aufrechnungen`) | **`NB`** |
| `record-rueckzahlung` | Record an operator's repayment (`/eeg/rueckzahlungen`) | **`NB`** |
| `manage-dunning` | Escalation, resolution, Abwendung offer, Mahnsperren, Einwände | **`LF`** |
| `close-period` | Jahresabschluss, seal | **`LF`** |
| `erase-pii` | Anonymization | **`LF`** |
| `read-policy` | `GET /api/v1/policy` and the MCP tool `get_policy` — the posture report | any caller of the tenant |
| `read-config` | `GET /admin/einrichtung` — the configuration findings | any caller of the tenant |
| `use-mcp` | Open the MCP surface | any caller of the tenant |

Roles are market roles from `mako_roles`; an MSB runs the same receivable
machinery for its Messentgelte. `tests/it/authorization_guard.rs` fails the build
on a routed handler without a Cedar check, on policy/code action drift, and on an
MCP tool without a mapping.

### Inbound webhook

`POST /webhook` verifies the Standard Webhooks signature against
`erp_hmac_secret` (held as `SecretString`); a missing or invalid signature is
`403`.

---

## Configuration

Every table block goes last: in TOML a bare key after a table header belongs to
that table.

```toml
tenant                = "stadtwerke-musterstadt"   # isolation key, not an MP-ID
lf_mp_id              = "9900357000028"     # required: the Lieferant whose customer accounts these are
erp_webhook_url       = "http://erp:8000/webhooks/accounting"
erp_hmac_secret       = "env:ACCOUNTINGD_INBOUND_HMAC_SECRET"
iban_hash_secret      = "env:ACCOUNTINGD_IBAN_HASH_SECRET"

# Dunning
# Mahngebühr per Mahnstufe in ct — required with dunning_auto_enabled
dunning_fee_stufe1_ct = 0
dunning_fee_stufe2_ct = 500
dunning_fee_stufe3_ct = 1000
dunning_grace_days    = 30
dunning_auto_enabled  = true          # default false
# Zahlungsfrist per Mahnstufe in days — required with dunning_auto_enabled
dunning_zahlungsfrist_stufe1_tage = 14
dunning_zahlungsfrist_stufe2_tage = 14
dunning_zahlungsfrist_stufe3_tage = 7

# Mahnung documents
outputd_url           = "http://outputd:9880"
vertragd_url          = "http://vertragd:9780"

# §§ 41f/41g EnWG Sperr-Sequenz
makod_url                         = "http://makod:8080"
makod_api_key                     = "env:ACCOUNTINGD_MAKOD_API_KEY"
sperrkosten_ct                    = 4500
entsperrkosten_ct                 = 4500
sperrung_threshold_ct             = 10000
sperrandrohung_frist_days         = 28
sperrankuendigung_frist_werktage  = 8

# Jahresabschluss worker (default false; start day default "02-01")
jahresabschluss_auto_enabled = false
# jahresabschluss_start_day  = "02-01"

# SEPA
creditor_iban         = "DE89370400440532013000"   # required for pain.008 (500 otherwise)
creditor_id           = "DE74ZZZ09999999999"       # Gläubiger-ID, required
creditor_name         = "Muster Energie GmbH"      # required to issue pain.008, Erstattung pain.001, Mahnung
# debtor_agent_bic    = "…"                        # required for camt.055 recalls
# pain008_schema      = "pain.008.001.02"          # default pain.008.001.08
# pain001_schema      = "pain.001.001.03"          # default pain.001.001.09
sepa_pre_notification_days = 14

[http]
addr = "0.0.0.0:9380"

[creditor_address]   # optional; never half-filled
street          = "Musterstraße"
building_number = "12"
post_code       = "10115"
town            = "Berlin"
country         = "DE"

[eeg]
nb_mp_id        = "9900357000004"   # the Netzbetreiber the EEG plant accounts are kept under
debtor_name     = "Muster Netz GmbH"   # the Netzbetreiber as SEPA debtor of every EEG pain.001
debtor_iban     = "env:NB_BANK_IBAN"   # the Netzbetreiber's account the payouts are debited from
sepa_instant    = true
auto_payout     = true
bank_submit_url = "https://banking-adapter.internal/api/v1/pain001"
bank_api_key    = "env:BANK_API_KEY"

[eeg.debtor_address]   # optional; never half-filled
town            = "Berlin"
country         = "DE"

[database]
url           = "postgresql://accountingd_app:secret@db:5432/accountingd?sslmode=verify-full"
migration_url = "env:ACCOUNTINGD_MIGRATION_URL"   # the owning role; creates the ledger and grants `url`'s role

[oidc]   # required unless allow_insecure_no_auth = true
issuer   = "https://keycloak:8080/realms/mako"
audience = "accountingd"
```

**Two database roles.** With `migration_url` set, the owning role migrates,
creates the ledger and grants `url`'s role exactly what doubleentry's store
names — read and append, update only the maintained projections, never
`DELETE`, `TRUNCATE` or DDL — and accountingd serves as that role, so the
journal cannot be rewritten by the process that writes it. Without it, `url`
does both. TLS is the URL's `sslmode` (`verify-full` recommended).

`outputd_api_key` and `vertragd_api_key` authenticate the two clients; `[mcp]`
configures the MCP credential layer.

---

## Metrics

`GET /accountingd/metrics` — gauges queried on scrape:
`accountingd_open_receivables_ct`, `accountingd_credit_balances_ct`,
`accountingd_dunning_open{stufe}`, `accountingd_sepa_runs_pending`,
`accountingd_sepa_collections{status}`, `accountingd_sepa_collections_open_ct`,
`accountingd_sperrung_pending`, `accountingd_accounts_total`.

The path is its own because the runner owns `/metrics` — see [what `/metrics`
carries on every
service](https://hupe1980.github.io/mako/docs/architecture/#what-metrics-carries-on-every-service).

---

## MCP server

`accountingd` exposes **20 tools** at `/mcp` (Streamable HTTP, revisions 2026-07-28 and 2025-11-25, no session), the
contract pinned by `services/accountingd/mcp.snapshot.json`. Every
tool is authorized by `mcp_server::tool_action` against the Cedar action its
REST twin enforces; a tool without a mapping is refused. An `[mcp]` key
authorizes as `User::"<key name>"` with the roles its `roles` list declares.

| Tool | Description | Action |
|---|---|---|
| `get_policy` | The posture this deployment runs under | `read-policy` |
| `get_balance` | Balance in ct and EUR, with the Abschlag — typed (`Kontostand`), REST twin `GET /accounts/{malo_id}/balance` | `read-account` |
| `get_vorauszahlung` | The BO4E `Vorauszahlung` of a MaLo — the body of `GET /api/v1/accounts/{malo_id}/vorauszahlung` | `read-account` |
| `list_ledger` | The Kontoauszug of a MaLo: opening balance and movements with running balance, newest first — typed (`Kontoauszug`), REST twin `GET /accounts/{malo_id}/ledger` | `read-account` |
| `suggest_payment_match` | Match a transfer: exact resolution first, amount ranking as fallback — typed (`Zahlungszuordnung`), REST twin `POST /payments/match` | `read-account` |
| `trigger_jahresabschluss` | **Preview** of the annual settlement | `read-account` |
| `list_dunning` | Open dunning cases with Mahnstufe, amount and due date — typed (`Mahnfaelle`), REST twin `GET /dunning` | `read-books` |
| `list_overdue` | Accounts with an open balance, largest first — typed (`UeberfaelligeKonten`), REST twin `GET /offene-posten` | `read-books` |
| `compute_bilanzielle_abgrenzung` | pRAP/aRAP for the HGB § 250 period close | `read-books` |
| `list_parked_bookings` | Bookings the ledger refused for good, with what to do — typed (`outputSchema`), read by the Desk | `read-books` |
| `get_parked_booking` | One parked booking by its key — what the assistant's proposal on it reads | `read-books` |
| `list_sepa_collections` | Collections and their status | `read-banking` |
| `list_unmatched_payments` | Bank lines no account claimed — typed (`UnzugeordneteZahlungen`), REST twin `GET /payments/unmatched` | `read-books` |
| `list_credit_payouts` | Guthaben from Schlussrechnungen and which are overdue — typed (`Guthabenauszahlungen`), REST twin `GET /credit-payouts` | `read-books` |
| `list_eeg_payouts` | EEG payout orders by plant and billing month (`tr_id`, `malo_id`, `year`, `month`, `status`, `payment_type`) — typed (`EegAuszahlungen`), REST twin `GET /eeg/payouts` | `read-eeg-payouts` |
| `update_abschlag` | Change the monthly advance | `write-account` |
| `import_payments` | Flat bank-export import | `import-payments` |
| `run_sepa_collection` | Build a pain.008 for two days out without archiving it | `manage-sepa` |
| `run_abschlag_cycle` | Abschlagslauf for one billing day | `post-entry` |
| `post_manual_booking` | Manual ledger entry | `post-entry` |

One prompt: `check-customer-account`. agentd's `payment-reconciliation-agent`
uses these tools, and `portald-agent` reads `get_balance`, `get_vorauszahlung` and `list_dunning`.

---

## Testing

```bash
cargo test -p accountingd --all-features   # unit, pure-logic and guard tests
just test-accountingd-db                   # DB scenarios against a throwaway PostgreSQL
```

The DB scenarios live in `tests/it/db_scenarios.rs` (`#[ignore]` without
`DATABASE_URL`).
