# marktd Operator Guide

> Operator guide for marktd, the market data hub: Marktpartner, Marktlokationen, price sheets and the durable CloudEvents fan-out every other service reads.

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

`marktd` is the **market data hub** — the single source of truth for market
entity state in a MaKo deployment, on port **8180**. It stores:

- Marktlokationen, Messlokationen, Zähler and Geräte as typed `rubo4e::current`
  BOs, gated on every `PUT`;
- Marktpartner (`Geschaeftspartner`), NB network contracts (BO4E `Vertrag`),
  price sheets (Netznutzung, Messung, KA, Dienstleistung, Hardware) and the
  Mehr-/Mindermengen prices;
- the **VersorgungsStatus** per MaLo with full history and point-in-time reads;
- MaLo grid topology (`malo_grid`, from the NB's NIS/GIS), NeLos, Tranchen,
  steuerbare and technische Ressourcen, the location graph, ESA consents and
  §20b EnWG Netzzugang requests.

It also runs the **durable fan-out**: inbound `de.mako.engine.*` events from `makod`
and its own `de.mako.markt.*` events reach every webhook endpoint whose filter
matches (`makod`, `processd`, `invoicd`, `edmd` from its config, an ERP through
the API) as signed webhooks. Forwarded events retain the original occurrence time through retries and replay.

`marktd` holds **no domain policy**. Automated Anmeldung decisions belong to
[`processd`](https://hupe1980.github.io/mako/docs/services/processd/), which reads `marktd` and decides with
`mako-pruefung`.

```mermaid
graph TB
    makod["makod :8080<br/>EDIFACT ↔ BO4E"]
    marktd["marktd :8180<br/>Market Data Hub"]
    processd["processd :8580<br/>NB STP + LF answers"]
    erp["ERP"]
    invoicd["invoicd :8280"]
    edmd["edmd :8380"]
    pg["PostgreSQL"]

    makod -->|"de.mako.engine.process.*<br/>signed POST"| marktd
    marktd --- pg
    marktd -->|"de.mako.engine.* + de.mako.markt.*"| erp
    marktd -->|"de.mako.engine.* · de.mako.markt.versorgung.*"| processd
    marktd -->|"de.mako.engine.process.initiated"| invoicd
    marktd -->|"de.mako.engine.*"| edmd
    erp -->|"PUT /api/v1/malos/{id}<br/>PUT /api/v1/partners/{mp_id}"| marktd
    invoicd -->|"GET /api/v1/preisblaetter/{nb_mp_id}"| marktd
    processd -->|"GET /api/v1/versorgung/{malo_id}<br/>GET /api/v1/malos/{id}/grid"| marktd
    processd -->|"POST /api/v1/commands"| makod
```

---

## Quick start

`just dev` starts PostgreSQL and runs `marktd` with `deploy/demo/marktd.toml`,
first of the estate, since every other service receives its fan-out;
`just demo` runs the same configuration in Docker (`compose.yaml`). The demo
names makod, processd, edmd and invoicd as `[[subscriptions.endpoints]]` and
sets `[subscriptions] allow_loopback = true`, so `just listen` can register an
`http` endpoint on this machine; any other deployment leaves it off.

A minimal container:

```yaml
services:
  postgres:
    image: postgres:17-alpine
    environment:
      POSTGRES_DB:       marktd
      POSTGRES_USER:     marktd
      POSTGRES_PASSWORD: secret
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U marktd -d marktd"]
      interval: 5s
      retries: 10

  marktd:
    image: ghcr.io/hupe1980/mako-marktd:<version>
    depends_on:
      postgres:
        condition: service_healthy
    volumes:
      - ./marktd.toml:/etc/marktd/marktd.toml:ro
    environment:
      MARKTD_CONFIG:        /etc/marktd/marktd.toml
      DATABASE_URL:         postgres://marktd:secret@postgres/marktd
      MAKOD_API_KEY:        my-makod-api-key
      MAKOD_WEBHOOK_SECRET: my-webhook-secret
    ports: ["8180:8180"]
```

The config path is an **environment variable**. The binary accepts only
`--check`, `--print-config` and `--help`, and refuses any other argument, so a
`--config=…` flag stops the container from starting.

Migrations (`migrations/0001_initial.sql`) run at startup.

---

## Configuration

`mako_service::load_config` reads `marktd.toml` (path from `MARKTD_CONFIG`,
default `./marktd.toml`), then `MARKTD_*` variables with `__` as the section
separator, then any `*_FILE` variable from a file. The file is optional
(`MARKTD_DATABASE__URL`, `MARKTD_MARKT__TENANT`, `MARKTD_MAKOD__API_KEY_FILE`, …).
`"env:VAR"` defers a value to the environment. Unknown keys are refused.

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

[database]
url             = "env:DATABASE_URL"  # required
pool_size       = 20
min_connections = 2

[markt]
# This deployment's identity: the `resource_tenant` every Cedar check compares
# the caller's `mako_tenant` against, the `tenant` column on tenant-scoped rows,
# and the source URN of every outbound CloudEvent.
tenant = "stadtwerke-musterstadt"  # required — data-isolation key

[makod]
base_url  = "http://makod:8080"   # required
api_key   = "env:MAKOD_API_KEY"   # required

[webhook]
inbound_path   = "/api/v1/mako/events"        # default; must match makod's [erp] webhook_url
inbound_secret = "env:MAKOD_WEBHOOK_SECRET"   # required unless allow_insecure_no_auth

[subscriptions]
# How long events stay in event_outbox for replay and GET /api/v1/events. It
# also bounds how far back processd's read model can be rebuilt
# (POST /api/v1/obs/rebuild pages this feed).
retention_days = 30                           # default

# One entry per in-cluster receiver; see „Fan-out".
[[subscriptions.endpoints]]
name        = "makod"
url         = "http://makod:8080/webhooks/marktd"
secret      = "env:MAKOD_MARKTD_WEBHOOK_SECRET"   # makod's [marktd] webhook_secret
event_types = ["de.mako.markt.malo.updated"]

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

[mcp]               # the /mcp surface's own credential layer
api_key = "env:AGENTD_KEY"   # optional; also named_keys, api_key_roles

[mmma_import]       # monthly Mehr-/Mindermengenpreis import; off by default
enabled        = false
gas_url        = ""   # THE Gas MMMA CSV/JSON; empty skips Gas
strom_url      = ""   # BDEW Strom MMM CSV/JSON; empty skips Strom
check_hour_utc = 6    # 1st of each month, at or after this UTC hour

# Fail-closed: without [oidc] AND webhook.inbound_secret marktd refuses to
# start. The insecure dev posture must be requested by name:
# allow_insecure_no_auth = true
```

| Setting | How | Default |
|---|---|---|
| Health probe | `--check` — `GET /health/ready` on loopback against the **running** instance; exit 0 when ready. Not a config validator | — |
| Effective config | `--print-config` — merged layers, secrets redacted | — |
| Config path | `MARKTD_CONFIG` | `./marktd.toml` |
| Log level | `MARKTD_LOG_LEVEL`, else `LOG_LEVEL`, else `RUST_LOG` | `info` |
| Log format | `MARKTD_LOG_FORMAT`, else `LOG_FORMAT` (`json` \| `pretty` \| `compact`) | `json` |

---

## Authentication and authorization

Every REST request carries a JWT Bearer token (RS256, ES256 or PS256; HS256/HS512
are refused) with these claims:

| Claim | Type | Required | Description |
|---|---|---|---|
| `sub` | `string` | yes | Principal |
| `mako_tenant` | `string` | yes | Tenant the principal belongs to |
| `mako_roles` | `string[]` | yes | e.g. `["NB"]`, `["MSB","NB"]` |
| `mako_sparte` | `string[]` | no | Commodity scope, e.g. `["Strom","Gas"]` |

### Cedar policy

`policies/marktd.cedar` is compiled into the binary and has **five `permit`
statements over 56 actions**, each starting from tenant equality:

| Group | Actions | Extra condition |
|---|---|---|
| Tenant-wide reads | every `read-*` action except the ESA pair — `read-policy` (`GET /api/v1/policy`) and `read-config` (`GET /admin/einrichtung`) among them — plus `use-mcp` | none |
| Ordinary writes | `write-malo`, `write-melo`, `write-nb-contract`, `write-partner`, `write-versorgungsstatus`, `write-device`, `write-sr`, `write-netzzugang`, `write-msb-rv`, `write-melo-msb`, `write-bilanzierung`, `write-mabis-zp`, `write-lokationszuordnung` | none |
| Grid-operator writes | `write-preisblatt`, `write-nelo`, `write-tranche`, `write-malo-grid`, `write-grundversorger`, `write-energiemix`, `write-mmma-preis`, `write-netznutzungsdaten`, `dispatch-pricat` | `mako_roles` contains `NB` |
| ESA consent | `read-einwilligung`, `write-einwilligung` | `MSB` **or** `ESA` |
| Operations | `manage-subscription`, `read-events`, `import-referenzreihen` | `ADMIN` |

Tenant and roles arrive in the **context** — `context.principal_tenant`
(`mako_tenant`), `context.principal_roles` (`mako_roles`),
`context.resource_tenant` (`[markt] tenant`). A policy written against
`principal.tenant` compiles and denies every caller.

A denial is `403` built by `ApiError::forbidden`:
`{"error": "Forbidden", "detail": "<reason>"}`. The reason names the action
(`manage-subscription denied`) or reads `access denied`; it never names the
resource tenant.

To customise, edit `policies/marktd.cedar` and rebuild.

### The authorization guard

`marktd` has no global auth middleware: `Claims` is an axum extractor, so a
handler that does not name it is unauthenticated, and an action missing from
the policy is a permanent `403`. `services/marktd/tests/it/authorization_guard.rs`
fails the test suite when:

| Check | Defect caught |
|---|---|
| Every action checked in code appears in the policy | A permanent `403` on a live route |
| Every policy action is checked somewhere | A dead grant |
| Every handler module extracts `Claims` and calls the enforcer | An unauthenticated route |
| No handler reads `Claims` as an `Extension` | Claims that bypass verification |
| No request body carries a `tenant` field | A caller naming its own tenant |

---

## REST API

OpenAPI: `GET /api/v1/openapi.json`, the document to open in any Swagger UI or Redoc,
committed as `services/marktd/openapi.json` (a test fails when the served one
differs). Three reads are **shared**: one function behind the documented `GET`
and the MCP tool of the same name, one response type for both, the same Cedar
action on both — `GET /api/v1/versorgung/{malo_id}[?at=]` (`get_versorgung_at`),
`…/history` (`get_versorgungsstatus_history`) and
`GET /api/v1/malos/{malo_id}/lokationsbuendel` (`get_lokationsbuendel`).
Every request body denies unknown fields.

### Failures

A failure of `marktd` itself — a database error, a stored document that no
longer deserialises, an outbox write — is a `500` whose body carries only
`"detail": "internal server error"` and an `error_id`; the error's own text is
logged beside the same id.

A failed call to `makod` is a `502` naming it. A test delivery
(`POST /api/v1/webhooks/endpoints/{id}/test`) answers `200` with what the
endpoint answered. Client errors carry a sentence in
`detail`; a domain refusal raised by the repositories (an invalid identifier,
a validity overlap, an `If-Match` mismatch as `412`) carries its stable reason
in `code` — `invalid_malo_id`, `unprocessable`, `not_found`,
`version_conflict`, `makod_conflict`.

### The BO4E gate

Every `PUT` carrying a BO4E payload runs `mako_markt::bo4e::decode` — see
[The BO4E gate](https://hupe1980.github.io/mako/docs/architecture/domain-model/#the-bo4e-gate). A refusal
is a `422` naming the stage in `code`:

```json
{
  "error":  "Unprocessable Entity",
  "detail": "MARKTLOKATION carries 1 out-of-schema enum value(s) at: sparte",
  "code":   "bo4e.unknown_enum",
  "paths":  ["sparte"]
}
```

- **The stored `data` is the canonical round-trip**, and the typed columns are
  derived from the same object, so a column cannot disagree with its document.
- **The envelope never asks for a field the BO declares.** `sparte` on a NeLo,
  `nutzung`/`verbrauchsart`/`ist_fernschaltbar`/`malo_id`/`melo_id` on a
  TechnischeRessource, `konfigurationsprodukte` on a SteuerbareRessource and
  `zaehler_typ`/`eichung_bis` on a Zaehler come from the payload. Fields the BO
  lacks — `nelos.nb_mp_id`, a MaLo's `fallgruppe`, `abwicklungsmodell`,
  `fernsteuerbar` — stay in the envelope, and an upsert leaves them alone.
- Writes that touch a shadowed column merge into the JSONB in the same
  statement.

### Endpoints

| Method | Path | Cedar action | Description |
|---|---|---|---|
| `GET` | `/health/live` · `/health/ready` | — | Liveness; readiness with a bounded DB ping |
| `GET` | `/metrics` | — | Prometheus |
| `PUT` | `/api/v1/malos/{malo_id}` | `write-malo` | Upsert a Marktlokation through the gate; emits `de.mako.markt.malo.updated` |
| `GET` | `/api/v1/malos/{malo_id}` | `read-malo` | Typed `Marktlokation` plus the typed columns |
| `GET` | `/api/v1/malos/{malo_id}/lastprofil` | `read-malo` | Lastprofil (SLP/TLP) of the MaLo |
| `GET` | `/api/v1/malos/{malo_id}/bundesland` | `read-malo` | The Land of the MaLo's `lokationsadresse`, from its PLZ over the GeoNames postal code table for Germany (CC BY 4.0, `services/marktd/data/plz_bundesland.tsv`); a missing PLZ, an unknown one or one whose places lie in two Länder is `422` (`KEINE_POSTLEITZAHL`, `PLZ_UNBEKANNT`, `PLZ_MEHRDEUTIG`) |
| `GET` | `/api/v1/malos` | `read-malo` | List MaLos (records that do not decode are skipped) |
| `PUT` | `/api/v1/melos/{melo_id}` | `write-melo` | Upsert a Messlokation through the gate |
| `GET` | `/api/v1/melos/{melo_id}` | `read-melo` | Typed `Messlokation` |
| `GET` | `/api/v1/melos/{melo_id}/standorteigenschaften` | `read-melo` | BO4E `Standorteigenschaften` |
| `PUT` | `/api/v1/partners/{mp_id}` | `write-partner` | Upsert a Marktpartner — see [Trading partners](#trading-partners) |
| `GET` | `/api/v1/partners/{mp_id}` · `/api/v1/partners` | `read-partner` | One partner; list by `?marktrolle=`, `?sparte=`, `?name=` |
| `GET` | `/api/v1/partners/{mp_id}/as4-address` | `read-partner` | AS4 endpoint and certificate |
| `GET` | `/api/v1/partners/{mp_id}/marktteilnehmer` | `read-partner` | BO4E `Marktteilnehmer` view |
| `GET/PUT` | `/api/v1/mmma-preise/gas/{year}/{month}` | `read-mmma-preis` / `write-mmma-preis` | Gas MMM prices (THE) |
| `GET` | `/api/v1/mmma-preise/gas` | `read-mmma-preis` | List Gas MMM prices (`?limit=`) |
| `POST` | `/api/v1/mmma-preise/import-trigger` | `write-mmma-preis` | Run the monthly import now |
| `GET/PUT` | `/api/v1/mmm-preise/strom/{year}/{month}` | `read-mmma-preis` / `write-mmma-preis` | Strom MMM prices (one nationwide series) |
| `GET` | `/api/v1/referenzreihen` | `read-referenzreihen` | The [Referenzreihen](#referenzreihen) catalogue, each series with its newest value |
| `GET` | `/api/v1/referenzreihen/{reihe}/werte` | `read-referenzreihen` | Values overlapping `?von=&bis=` (Berlin days), `?dim=`, as known at `?stand=` |
| `GET` | `/api/v1/referenzreihen/{reihe}/wert` | `read-referenzreihen` | The value of `?jahr=` (`&monat=`), as known at `?stand=`; none is `422 referenzwert_fehlt` |
| `POST` | `/api/v1/referenzreihen/{reihe}/import` | `import-referenzreihen` | A publisher's file as the body; `?vorschau=true` writes nothing; idempotent on the file's SHA-256 |
| `PUT` | `/api/v1/preisblaetter/{nb_mp_id}` | `write-preisblatt` | Upsert a Netznutzung sheet, snapshot it, emit `de.mako.markt.pricat.published` |
| `GET` | `/api/v1/preisblaetter/{nb_mp_id}` | `read-preisblatt` | Sheet valid on `?date=` |
| `GET` | `/api/v1/pricat/{nb_mp_id}/history` | `read-pricat` | PRICAT versions, newest first |
| `GET` | `/api/v1/pricat/{nb_mp_id}/dispatch-log/{version_id}` | `read-pricat` | Dispatch audit log of a version |
| `POST` | `/api/v1/pricat/{nb_mp_id}/dispatch` | `dispatch-pricat` | Re-queue the latest PRICAT to all active LF |
| `GET` | `/api/v1/versorgung/{malo_id}` | `read-versorgungsstatus` | Current state; `?at=YYYY-MM-DD` for point-in-time |
| `GET` | `/api/v1/versorgung/{malo_id}/history` | `read-versorgungsstatus` | Change history, newest first, paged |
| `PUT` | `/api/v1/versorgung/{malo_id}` | `write-versorgungsstatus` | ERP override (`If-Match` for OCC) |
| `GET/PUT` | `/api/v1/grundversorger/{nb_mp_id}` | `read-grundversorger` / `write-grundversorger` | §36 Abs. 2 EnWG Feststellung (`?sparte=STROM\|GAS`); optional `default_bilanzkreis` for an EoG ohne Antwort |
| `POST` | `/api/v1/esa/einwilligungen` | `write-einwilligung` | Grant an ESA consent (§49 Abs. 2 Nr. 9 MsbG); emits `de.mako.markt.einwilligung.erteilt` |
| `GET` | `/api/v1/esa/einwilligungen` · `/{id}` | `read-einwilligung` | List active consents (`?esa_mp_id=`); one consent |
| `DELETE` | `/api/v1/esa/einwilligungen/{id}` | `write-einwilligung` | Revoke (GDPR Art. 7(3)); commits `de.mako.markt.einwilligung.widerrufen` and one ORDERS 17008 Abbestellung command per covered location with the revocation |
| `PUT` | `/api/v1/esa/preise/{msb_mp_id}/{esa_mp_id}` | `write-einwilligung` | Prices of an accepted QUOTES 15003, filed by makod on the ORDRSP 19011 |
| `GET` | `/api/v1/esa/preise/{msb_mp_id}/{esa_mp_id}?at=` | `read-einwilligung` | Prices in force; invoicd's basis for an ESA INVOIC 31009 (an ESA has no Preisblatt) |
| `PUT/GET` | `/api/v1/esa/framework/{msb_mp_id}/{esa_mp_id}` | `write-einwilligung` / `read-einwilligung` | Framework agreement and AS4 certificate state |
| `PUT` | `/api/v1/esa/messprodukte/{msb_mp_id}` | `write-einwilligung` | Which Kapitel-4.6 Messprodukte the MSB serves, in which Abo mode; another code is `422` |
| `GET` | `/api/v1/esa/messprodukte/{msb_mp_id}/{messprodukt}?at=` | `read-einwilligung` | Served on `at`, in which mode — see [notes](#notes-on-the-endpoints) |
| `GET` | `/api/v1/esa/subscriptions/{bestellung_ref}` | `read-einwilligung` | Messprodukt behind an ORDERS 17007 Belegnummer, for edmd's Typ-2 surveillance; `404` → configured threshold |
| `GET` | `/api/v1/esa/consent-check` | `read-einwilligung` | `?esa_mp_id=&msb_mp_id=&location_id=&perspective=` → `{allowed, code, reason}`; `msb_inbound` (default, lenient) or `esa_outbound` (strict) |
| `GET` | `/api/v1/mabis-zp` | `read-mabis-zp` | Every Bilanzierungsgebiet → MaBiS-Zählpunkt |
| `GET` | `/api/v1/bilanzierungsgebiete/{eic}/mabis-zp` | `read-mabis-zp` | MaBiS-Zählpunkt (`LOC+172`); `404` makes `netzbilanzd` refuse the MaBiS filing, never fall back to the EIC |
| `PUT` | `/api/v1/bilanzierungsgebiete/{eic}/mabis-zp` | `write-mabis-zp` | Assign it; `400` for a value equal to the EIC or not 33 characters |
| `GET` | `/api/v1/zuordnungsermaechtigungen/{lf_mp_id}` | `read-zuordnungsermaechtigung` | Every Zuordnungsermächtigung (BKV, BK, BG, ZRT, `[valid_from, valid_to)`) naming the LF, from the UTILMD 55071/55072 the event ingest recorded; processd's `E_0622` Prüfschritt 60 reads it. No write route — only the BKV's message sets one |
| `PUT` | `/api/v1/netzzugang/antraege` | `write-netzzugang` | Upsert a §20b EnWG request; emits `de.mako.markt.netzzugang.antrag.updated` |
| `GET` | `/api/v1/netzzugang/antraege` · `/{id}` | `read-netzzugang` | List (`?status=&netzanschluss_id=`); one |
| `PATCH` | `/api/v1/netzzugang/antraege/{id}/status` | `write-netzzugang` | `erfasst → uebermittelt → bestaetigt/abgelehnt`; optional `platform_ref`, `expected_version` (→ `412`) |
| `PUT` | `/api/v1/msb-rahmenvertraege` | `write-msb-rv` | MSB-Rahmenvertrag NB ↔ MSB, `sparte` `STROM` or `GAS`; idempotent on `(tenant, sparte, nb_mp_id, msb_mp_id, valid_from)`; `version` → `412`; an overlapping window → `422` |
| `GET` | `/api/v1/msb-rahmenvertraege` · `/{id}` | `read-msb-rv` | List (`?sparte=&nb_mp_id=&msb_mp_id=&status=`); one |
| `GET` | `/api/v1/msb-rahmenvertraege/check` | `read-msb-rv` | `?sparte=&nb_mp_id=&msb_mp_id=&datum=` → `abgeschlossen`, `befund`, `vertrag`; read by `processd` for the Anmeldung MSB |
| `GET` | `/api/v1/nelos` · `/{id}` | `read-nelo` | List (`?nb_mp_id=`); one by EIC or BDEW-Codenummer |
| `PUT` | `/api/v1/nelos/{id}` | `write-nelo` | Upsert through the gate; `sparte` from the payload, `STROM` or `GAS` only |
| `GET` | `/api/v1/tranchen` · `/{id}` | `read-tranche` | List (`?malo_id=`); one |
| `PUT` | `/api/v1/tranchen/{id}` | `write-tranche` | GPKE Teil 4 „Daten der Tranche" |
| `GET/PUT` | `/api/v1/malos/{malo_id}/grid` | `read-malo-grid` / `write-malo-grid` | Grid topology from NIS/GIS |
| `GET` | `/api/v1/malos/{malo_id}/utilmd-stammdaten?stichtag=` | `read-utilmd-stammdaten` | The Marktlokation's [UTILMD Stammdaten](#utilmd-stammdaten) on the Stichtag; `404` for an unknown MaLo |
| `PUT` | `/api/v1/malos/{malo_id}/netznutzungsdaten` | `write-netznutzungsdaten` (NB) | One dated row of the NB's Netznutzungsdaten; an overlapping row is `422` |
| `GET` | `/api/v1/malos/{malo_id}/lokationsbuendel?stichtag=` | `read-utilmd-stammdaten` | The Marktlokation's [Lokationsbündel](#lokationsbuendel) on the Stichtag and the NB's Angaben of it; `404` for an unknown MaLo |
| `GET` | `/api/v1/lokationsbuendelstrukturen` | `read-utilmd-stammdaten` | The Codeliste der Lokationsbündelstrukturen (BDEW V1.0): each `lokationsbuendelcode` with its Bezeichnung |
| `PUT` | `/api/v1/malos/{malo_id}/lokationsbuendel-angaben` | `write-netznutzungsdaten` (NB) | One dated row of the NB's Lokationsbündel-Angaben; an overlapping row is `422` |
| `GET/PUT` | `/api/v1/preisblaetter-messung/{msb_mp_id}` | `read-preisblatt` / `write-preisblatt` | `PreisblattMessung`; GET includes `auf_abschlaege` |
| `GET/PUT` | `/api/v1/netzbetreiber/{nb_mp_id}/grundzustaendiger-msb` | `read-malo-grid` / `write-malo-grid` | The MP-ID the grundzuständige MSB of the NB's grid acts under — its own, not the NB's (§ 2 Nr. 4 MsbG; one MP-ID per Rolle, Identifikatoren AWH V1.2 Kap. 2.1). `PUT { gmsb_mp_id, valid_from }` records it from a day on and ends the link before it that day, as a transfer of the Grundzuständigkeit does (§§ 41, 43 MsbG); `GET ?at=` answers the link in force that day (today by default), `404` where none is. productd reads the Messung sheet of an Endkunden-Angebot under the link on its Lieferbeginn |
| `GET/PUT` | `/api/v1/preisblaetter-ka/{nb_mp_id}` | `read-preisblatt` / `write-preisblatt` | `PreisblattKonzessionsabgabe` |
| `GET/PUT` | `/api/v1/preisblaetter-dienstleistung/{msb_mp_id}` | `read-preisblatt` / `write-preisblatt` | `PreisblattDienstleistung` |
| `GET/PUT` | `/api/v1/preisblaetter-hardware/{msb_mp_id}` | `read-preisblatt` / `write-preisblatt` | `PreisblattHardware` |
| `GET/PUT` | `/api/v1/steuerbare-ressourcen/{sr_id}` | `read-sr` / `write-sr` | `SteuerbareRessource` |
| `GET/PUT` | `/api/v1/steuerbare-ressourcen/{sr_id}/konfigurationsprodukte` | `read-sr` / `write-sr` | List or replace the §14a Konfigurationsprodukte |
| `DELETE` | `/api/v1/steuerbare-ressourcen/{sr_id}/konfigurationsprodukte/{produktcode}` | `write-sr` | Remove one |
| `GET/PUT` | `/api/v1/technische-ressourcen/{tr_id}` | `read-device` / `write-device` | `TechnischeRessource` |
| `GET` | `/api/v1/malos/{malo_id}/technische-ressourcen` | `read-device` | Those linked to a MaLo |
| `GET` | `/api/v1/malos/{id}/lokationen` · `/api/v1/melos/{id}/lokationen` | `read-lokationszuordnung` | Location graph (`?at=`) |
| `GET` | `/api/v1/malos/{id}/buendel` | `read-lokationszuordnung` | The [Lokationsbündel and its audit](#lokationsbuendel-audit) |
| `PUT` | `/api/v1/lokationszuordnungen` | `write-lokationszuordnung` | Upsert an edge; `data` is a gated `Bo4e<Lokationszuordnung>` |
| `DELETE` | `/api/v1/lokationszuordnungen/{von_id}/{nach_id}` | `write-lokationszuordnung` | Delete an edge pair, every temporal variant |
| `GET` | `/api/v1/melos/{melo_id}/zaehler` | `read-device` | Zähler of a MeLo |
| `GET/PUT` | `/api/v1/melos/{melo_id}/msb` | `read-melo-msb` / `write-melo-msb` | MSB on `?at=` (WiM Teil 2 UC 4.1.1); PUT `{ msb_mp_id, valid_from }` closes the open assignment, and may state `msb_rolle` (`GRUNDZUSTAENDIG`/`WETTBEWERBLICH`/`AUFFANG`), `grundlage` (`VERTRAG`/`WEITERVERPFLICHTUNG`) and `gmsb_mp_id` |
| `GET` | `/api/v1/melos/{melo_id}/msb/history` | `read-melo-msb` | Dated MSB timeline |
| `GET/PUT` | `/api/v1/malos/{malo_id}/bilanzierung` | `read-bilanzierung` / `write-bilanzierung` | BO4E `Bilanzierung` keyed on `(malo, bilanzierungsbeginn)`; GET at `?at=`. `422` without `bilanzierungsbeginn` or with an end at/before it |
| `GET` | `/api/v1/malos/{malo_id}/bilanzierung/history` | `read-bilanzierung` | Full history |
| `GET` | `/api/v1/melos/{melo_id}/sharing-eligibility` | `read-sharing-eligibility` | §42c EnWG metering capability: Zählerstandsgangmessung (§2 Satz 1 Nr. 27 MsbG) or viertelstündliche RLM, with `basis`, `required_action`, `reasons`, `evidence` |
| `PUT` | `/api/v1/zaehler/{zaehler_id}` | `write-device` | Upsert a Zähler through the gate |
| `GET` | `/api/v1/zaehler/{zaehler_id}/zaehlwerke` | `read-device` | `Zaehlwerk` registers (`[]` when none) |
| `GET` | `/api/v1/zaehler/{zaehler_id}/geraete` · `/{geraet_id}` | `read-device` | Geräte; one with `konfigurationen` |
| `GET/PUT` | `/api/v1/zaehler/{zaehler_id}/geraete/{geraet_id}/konfigurationen` | `read-device` / `write-device` | Replace `GeraetKonfiguration` entries; emits `de.mako.markt.geraet.konfiguration.updated` |
| `GET/PUT` | `/api/v1/zaehler/{zaehler_id}/register` | `read-device` / `write-device` | TOU registers |
| `GET/PUT` | `/api/v1/zaehler-register/{register_id}/saisons` | `read-device` / `write-device` | Seasonal windows |
| `GET` | `/api/v1/zaehler/{zaehler_id}/tariff-zone` | `read-device` | HT/NT/EINZEL at `?datetime=`; `422` when no Zählzeit window covers the instant |
| `GET` | `/api/v1/zaehler/{zaehler_id}/zaehlzeitdefinitionen` | `read-device` | BO4E `Zaehlzeitdefinition`; `?valid_only=true` |
| `PUT` | `/api/v1/geraete/{geraet_id}` | `write-device` | Upsert a Gerät through the gate |
| `GET/PUT` | `/api/v1/nb-contracts/{id}` | `read-nb-contract` / `write-nb-contract` | NB contract as `Vertrag`; PUT emits `de.mako.markt.nb-contract.updated` |
| `GET` | `/api/v1/nb-contracts` | `read-nb-contract` | List (`?nb_mp_id=` required) |
| `GET` | `/api/v1/nb-contracts/by-malo/{malo_id}` | `read-nb-contract` | Contract in force on `?on=` |
| `GET/PUT` | `/api/v1/energiemix/{nb_mp_id}` | `read-energiemix` / `write-energiemix` | §42 EnWG Energiemix (`?year=`) |
| `GET` | `/api/v1/energiemix/{nb_mp_id}/history` | `read-energiemix` | Every published year |
| `…` | `/api/v1/webhooks/**` | `manage-subscription` | Webhook endpoints, deliveries, replay — see „Webhooks" |
| `GET` | `/api/v1/events` | `read-events` | The outbox as a feed, in commit order |
| `GET` | `/api/v1/correlations` · `/{id}` | `read-correlation` | Process correlations (`?malo_id=`, `?workflow=`); one by `process_id` or `erp_order_id` |
| `POST` | `[webhook] inbound_path` | — | Signed CloudEvent from makod, logged before fan-out |

### Notes on the endpoints

- **The Messprodukt answer has three states.** `als_abo` and `als_einmalig` are
  `true`, `false` or `null`; `null` („nothing recorded") makes the `E_0252` /
  `E_0256` walks escalate rather than refuse. A Pflichtprodukt is served whatever
  the catalogue holds (BNetzA Mitteilung Nr. 3, § 34 Abs. 2 S. 2 Nr. 10 MsbG).
- **A NeLo is Strom or Gas.** A `WASSER` or `FERNWAERME` Netzlokation is a
  payload error.
- **The MSB-Rahmenvertrag is per Sparte.** The NB checks the Vertrag nach § 9
  Abs. 1 Nr. 3 MsbG with the MSBN before it confirms an Anmeldung MSB (WiM
  Teil 1 Kap. 2.3.2 Nr. 2 Ziff. 3; AWH WiM Gas 2.0 Kap. 3.5.2 Nr. 2 Ziff. 3),
  and the NB has one MP-ID per Sparte, so a Gas contract never answers a Strom
  lookup. `check` is `abgeschlossen: true` only for a contract with status
  `abgeschlossen` whose `[valid_from, valid_to)` covers `datum`; otherwise
  `befund` names why — `kein_vertrag`, `angeboten`, `anpassung_erforderlich`
  or `beendet` — and `processd` escalates the Anmeldung naming that Befund,
  so the operator reads whether a contract is to be concluded, settled,
  renewed or adapted. Two contracts of the same parties
  and Sparte cannot claim the same day.
- **Two columns are Gas-only.** GeLi Gas 3.0 (BK7-24-01-009, S. 6–7) revokes
  BK7-17-026 with effect from 01.10.2026 (Tenor 13) and requires the
  Messstellenbetreiberrahmenvertrag in the jeweils gültige Fassung, adapting
  those already concluded (Tenor 15). A Gas row's `fassung` defaults to
  `KoV XV Anlage 8` (KoV Gas XV Haupttext § 2 Ziff. 2 lit. h); a Strom row gets
  none it did not name. `anpassung_erforderlich` is refused on a Strom row, and
  a Gas contract still in Fassung `BK7-17-026` answers `anpassung_erforderlich`
  for any day from 01.10.2026. Every upsert emits
  `de.mako.markt.msb-rahmenvertrag.updated` (`sparte`, `version`, `valid_from`,
  `valid_to`, `signed_at`) in the write's transaction.
- **Partner role `LFG` is refused** (`422`): a gas supplier is `LF` +
  Rollencodetyp `DVGW`.

### The end of a consent

`E_0256` Prüfschritt 8 code `A08` covers a consent „widerrufen **oder ihre
Gültigkeit ist abgelaufen**", and both owe the ORDERS 17008 Abbestellung.
`DELETE` covers the Widerruf; an **hourly sweep** closes every consent past its
`valid_to` (one at a time, `FOR UPDATE SKIP LOCKED`); a grant for the same ESA
and Anschlussnutzer replaces the active consent.

Every ending commits, in the transaction that sets `revoked_at`, its
`de.mako.markt.einwilligung.widerrufen` event and one `esa.abbestellung.beauftragen`
command per location in `event_outbox`. A worker delivers the commands to makod
(`POST /api/v1/commands`, keyed `esa-abbestellung:{consent}:{location}`) with
retry and a dead-letter budget, so a makod outage delays the 17008 and never
loses it; a `404` or `409` — nothing left to stop — discharges the command. A
failure before the commit leaves the consent open for a retry. The event's
`grund` is `einwilligung_widerrufen`, `einwilligung_abgelaufen` or
`einwilligung_ersetzt`; a replacement abbestellt only the locations the new
consent no longer covers.

---

## Price sheets — PreisblattNetznutzung

Validity comes from the payload's `gueltigkeit.startdatum` / `enddatum`.
`?date=YYYY-MM-DD` selects the sheet (default today, Europe/Berlin).

```json
{
  "data": {
    "_typ": "PREISBLATTNETZNUTZUNG",
    "bezeichnung": "Netznutzungspreise 2025 — 9900357000004",
    "gueltigkeit": { "startdatum": "2025-10-01", "enddatum": "2026-09-30" },
    "marktteilnehmer": {
      "_typ": "MARKTTEILNEHMER",
      "marktrolle": "NB",
      "rollencodenummer": "9900357000004",
      "rollencodetyp": "BDEW"
    },
    "preispositionen": [ ... ]
  }
}
```

`bo4e_version` is provenance, returned on `GET` and not accepted on `PUT`. The
`GET` adds `source`, `updated_at` and `zeitvariable_preispositionen`:

```json
{
  "data":         { "_typ": "PREISBLATTNETZNUTZUNG", ... },
  "source":       "api",
  "bo4e_version": "202607.1.0",
  "updated_at":   "2025-10-01T08:15:00Z",
  "zeitvariable_preispositionen": [
    {
      "_typ": "ZEITVARIABLEPREISPOSITION",
      "bezeichnung": "HT-Arbeitspreis",
      "zaehlzeitregister": "HT",
      "preisreferenz": "ENERGIEMENGE",
      "preis": { "wert": "8.35", "einheit": "CT", "bezugswert": "KWH" }
    }
  ]
}
```

A BO4E `Preis` keeps the currency in `einheit` (`CT` or `EUR` only), the
per-unit in `bezugswert` and the kind in `preisreferenz` (`ENERGIEMENGE` /
`LEISTUNG` / `ANZAHL` / `ZEITRAUM` / `PAUSCHAL`); a composite such as
`"CT_PRO_KWH"` in `einheit` decodes to `Unknown`.

Time bands live in the `zaehlzeitdefinition` the position's `zaehlzeitregister`
points into. The array is omitted when empty; `netzbilanzd` reads it for §14a
Modul 3 (BK8-22/010-A). A `PUT` names each position's Tarifstufe `HT`, `ST` or
`NT` and prices all three (Tenor 3. b)), or is `422`. `lastvariablePreispositionen`
are quantity-tiered (`STAFFELN`, `ZONEN`, …) and pass the BO4E gate only.

**`source` and the operator override.** `api` rows come from the REST `PUT`,
`mako` rows from the PRICAT ingest. An `api` row is never overwritten by a
`mako` row for the same NB and `valid_from`; `preisblaetter_messung` and
`preisblaetter_konzessionsabgabe` carry the same protection.

### PRICAT 27003 dispatch

| | `preisblaetter` | `pricat_versions` |
|---|---|---|
| Answers | Which sheet is valid on date X? | What did we transmit, to whom, when? |
| Overlap | Forbidden (`EXCLUDE USING gist`) | Allowed |
| Correction | Replaces the row | Adds a version |
| Read by | `invoicd`, `netzbilanzd`, `invoic-checker` | Operators, via `/pricat/{nb}/history` |

`pricat_versions.data` is a **snapshot**, so a later correction never rewrites
what was transmitted. Only the Netznutzung sheet has a PRICAT.

A `PUT /api/v1/preisblaetter/{nb_mp_id}` writes, in **one transaction**, the
sheet, a snapshot keyed on `(nb_mp_id, tenant, valid_from)`, and the
`de.mako.markt.pricat.published` outbox row. A background task then dispatches
PRICAT 27003 to every active LF via makod and logs each NB × LF attempt in
`pricat_dispatch_log`.

```mermaid
sequenceDiagram
    participant ERP
    participant marktd
    participant makod
    ERP->>marktd: PUT /api/v1/preisblaetter/{nb_mp_id}
    marktd->>marktd: preisblaetter + pricat_versions + outbox (one tx)
    marktd-->>ERP: 204 No Content
    Note over marktd: background task
    loop per active LF partner
        marktd->>makod: POST /api/v1/commands dispatch-pricat-27003
        marktd->>marktd: pricat_dispatch_log
    end
```

| State | Meaning |
|---|---|
| `pending` | Stored; no dispatch started |
| `queued` | Picked up by the dispatch task |
| `done` | Every active LF reached |
| `error` | Last attempt failed; retried on the next poll |

Registering a partner with `marktrolle = "LF"` re-queues the latest PRICAT for
it. `POST /api/v1/pricat/{nb_mp_id}/dispatch` re-queues manually — after an AS4
outage, for instance.

### PreisblattMessung

MSB metering tariffs, keyed on `msb_mp_id`; the basis for REQOTE/QUOTES and for
invoicd's checks of INVOIC 31009.

```bash
curl -s -X PUT "http://marktd:8180/api/v1/preisblaetter-messung/9900012345678" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "data": {
      "_typ": "PREISBLATTMESSUNG",
      "bezeichnung": "Messentgelte 2026",
      "gueltigkeit": { "startdatum": "2026-10-01", "enddatum": "2027-09-30" },
      "preispositionen": [],
      "zeitvariablePreispositionen": [
        { "zaehlzeitregister": "HT", "preis": { "wert": "12.50", "einheit": "CT", "bezugswert": "KWH" } },
        { "zaehlzeitregister": "NT", "preis": { "wert": "8.75",  "einheit": "CT", "bezugswert": "KWH" } }
      ]
    }
  }'
```

Every `ZeitvariablePreisposition` must carry a non-empty `zaehlzeitregister`
(`422` otherwise); a `bandNummer` field is `422` because BO4E v202607 has none. `invoic-checker` check 4 routes INVOIC 31009
positions by that code.

---

## MMM settlement prices

Mehr-/Mindermengen prices are B2B settlement prices read by `netzbilanzd`
(issues MMM invoices) and `invoicd` (check 6 on inbound ones).

| | Gas | Strom |
|---|---|---|
| Publisher | Trading Hub Europe, per Marktgebiet | BDEW, one nationwide series |
| Key | month + `marktgebiet` | month alone |
| Route | `/api/v1/mmma-preise/gas/{year}/{month}` | `/api/v1/mmm-preise/strom/{year}/{month}` |
| `source` (CHECK) | `manual` \| `the-api` \| `csv-import` | `manual` \| `bdew-csv` \| `csv-import` |
| INVOIC | 31007/31008 | 31005/31006 |

The Strom series is *einheitlich* (§ 13 Abs. 3 StromNZV bis 31.12.2025, § 20
Abs. 3 EnWG über BK6-24-174 seit 01.01.2026), so `mmm_preise_strom` has no
operator or area column and the import refuses a file with more than one price
pair for a month.

```bash
curl -s -X PUT "http://marktd:8180/api/v1/mmma-preise/gas/2026/7" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "marktgebiet": "THE",
    "mehr_ct_kwh": "1.25",
    "minder_ct_kwh": "0.87",
    "source": "manual"
  }'

curl -s -X PUT "http://marktd:8180/api/v1/mmm-preise/strom/2026/7" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "mehr_ct_kwh": "2.10",
    "minder_ct_kwh": "1.45",
    "source": "manual"
  }'
```

**Monthly import.** With `[mmma_import] enabled = true` the worker wakes hourly
and, on the 1st at or after `check_hour_utc`, fetches `gas_url` / `strom_url`,
parses CSV (`year,month,marktgebiet,mehr_ct_kwh,minder_ct_kwh`) or JSON (one
object or an array) and upserts idempotently. It emits
`de.mako.markt.mmma.import.success` or `de.mako.markt.mmma.import.failed` (operator
action). Catch up by hand:

```bash
curl -s -X POST "http://marktd:8180/api/v1/mmma-preise/import-trigger?year=2026&month=7" \
  -H "Authorization: Bearer <token>"
```

Without the month's prices `netzbilanzd` needs them in the request and
`invoicd` skips check 6.

---

## Referenzreihen

A Referenzreihe is a figure a publication sets, not a statute — billing reads
it and a release should not have to carry it. The catalogue is
`mako_markt::referenzreihen::Reihe`; marktd stores the values.

| `reihe` | Value | Period | Dimensions | Publisher | Anchor | Licence | Reader |
|---|---|---|---|---|---|---|---|
| `kav_grenzpreis_strom` | Durchschnittserlös Strom aller Sondervertragskunden, ct/kWh | Kalenderjahr | — | Statistisches Bundesamt | KAV § 2 Abs. 4 | DL-DE/BY 2.0 (frei) | netzbilanzd, for the vorletzte Kalenderjahr |
| `kav_durchschnittserloes_gas` | Durchschnittserlös Gas aller Letztverbraucher, ct/kWh | Kalenderjahr | — | Statistisches Bundesamt | KAV § 2 Abs. 5 Nr. 2 | DL-DE/BY 2.0 (frei) | caller supplies the Gas Grenzpreis |
| `eeg_monatsmarktwert` | Monatsmarktwert, ct/kWh | Kalendermonat | `spot` · `wind_an_land` · `wind_auf_see` · `solar` | Übertragungsnetzbetreiber | EEG 2023 Anlage 1 Nr. 3 | Betreiber | — |
| `eeg_jahresmarktwert` | Jahresmarktwert, ct/kWh | Kalenderjahr | as above | Übertragungsnetzbetreiber | EEG 2023 Anlage 1 Nr. 4 | Betreiber | — |
| `day_ahead_de_lu` | Spotmarktpreis, ct/kWh | Viertelstunde | — | Strombörsen | EEG 2023 § 3 Nr. 42a | Betreiber | — |

**Bitemporal, append-only.** `referenzwerte` keeps `gilt` (when the value holds
— an annual or monthly value between the Berlin midnights that bound it) and
`erfasst` (when marktd knew it). A correction — the final Grenzpreis after the
provisional one, a corrected file — closes the current row's `erfasst` and
inserts the new row; nothing is updated in place or deleted. A read with
`?stand=<RFC 3339>` returns what marktd knew then, so a settlement computed on a
provisional value can be reproduced after the final one has arrived. An
`EXCLUDE … USING gist (reihe, dim, gilt &&, erfasst &&)` makes „the value for
this period as known then" a single answer.

**Missing is a refusal.** `GET …/{reihe}/wert` without a value answers
`422 referenzwert_fehlt` with `reihe`, `dim`, `zeitraum` and `faelligkeit` —
the series' publication rule (`KAV § 2 Abs. 4 nennt keinen
Veröffentlichungstermin`; the EEG Marktwerte are due „bis zum Ablauf des
zehnten Werktags des Folgemonats", EEG 2023 Anlage 1 Nr. 5.2). Never a zero and
never the neighbouring period.

**Licence.** mako seeds a series only when its licence allows redistribution
(`frei`) and the value was read from a document mirrored in the repository; it
seeds none today. A `Betreiber` series — the EPEX day-ahead price, the
netztransparenz Marktwerte whose terms are unverified — is loaded by the
operator under its own licence. `cargo xtask check-referenzreihen` refuses a
seed row for a `Betreiber` series, a series nothing reads that is not listed as
waiting for its reader, and a series without source or licence.

**Import.** `POST /api/v1/referenzreihen/{reihe}/import` takes the file as the
request body:

| `format` | File | Series |
|---|---|---|
| `generisch` | `zeitraum;dim;wert` with a header row; `zeitraum` is `YYYY`, `YYYY-MM` or the RFC 3339 start of a quarter hour; `,` or `.` as decimal mark | every series |
| `smard` | SMARD `chart_data` JSON (`series: [[ms, EUR/MWh]]`), converted to ct/kWh; `null` entries are skipped | `day_ahead_de_lu` |
| `energy_charts` | energy-charts `/price` JSON (`unix_seconds`, `price`, `unit` = `EUR / MWh`) | `day_ahead_de_lu` |

The query names `status` (`vorlaeufig` \| `endgueltig`), `quelle_url`
(`https://` only) and optionally `veroeffentlicht_am`. The import is one
transaction; a file the reader refuses — an unknown dimension, a period twice,
a decimal with both marks — is refused whole (`422 datei_unlesbar`). The same
file twice is answered `bereits_importiert` with the earlier import and adds
nothing. `?vorschau=true` runs the same transaction and rolls it back, so the
preview lists exactly the rows (`neu`, `ersetzt`, `unveraendert`) the import
would write. Convert the netztransparenz Marktwert CSV and the Destatis GENESIS table
to the `generisch` format before import.

```bash
curl -s -X POST "http://marktd:8180/api/v1/referenzreihen/kav_grenzpreis_strom/import?format=generisch&status=endgueltig&quelle_url=https://www-genesis.destatis.de/&vorschau=true" \
  -H "Authorization: Bearer <token>" \
  --data-binary @grenzpreis.csv
```

---

## Trading partners

`partners` is keyed on `mp_id` (BDEW- or DVGW-Codenummer).

| Part | Validation |
|---|---|
| `marktrolle`, `rollencodetyp`, `sparte` (top level) | Typed enums; `422` on an unknown value, including the EDIFACT `LFG` |
| `geschaeftspartner` | A `Bo4e<Geschaeftspartner>` through the gate; the canonical round-trip is stored |

`?name=` filters by what a customer types („stadtwerke münchen"). Every word
must begin a word of the partner's `display_name`. Case, umlauts and legal
forms are ignored, and exact names come first. It is for a front end showing
candidates the customer confirms. marktd never resolves a name to an MP-ID on
its own.

`marktrolle`, `rollencodetyp` and `marktteilnehmerstatus` are `Marktteilnehmer`
fields. Inside `geschaeftspartner` they are absorbed as unvalidated extension
fields and read back as nothing — put them at the top level. AS4 endpoints go
in `makoadresse`.

`edi_zustimmung` and `edi_extrahierbar` record what an outbound INVOIC to this
partner rests on: the partner's Zustimmung to EDI invoices, and whether the
agreed format extracts into EN 16931 (§ 14 Abs. 1 Satz 6 Nr. 2 UStG). Whether
EDI@Energy INVOIC does is not settled, so the operator records it per partner;
`null` is „not recorded", and
[makod](https://hupe1980.github.io/mako/docs/services/makod/#outbound-invoic-and-the-e-rechnung) refuses on it.

```bash
# `mp_id` may be omitted — the path names the partner — and is refused if it differs.
curl -s -X PUT "http://marktd:8180/api/v1/partners/9904234560001" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "display_name": "Muster Energieversorgung GmbH",
    "marktrolle":    "LF",
    "rollencodetyp": "BDEW",
    "sparte":        "STROM",
    "makoadresse":   ["https://as4.muster-ev.de/as4/in"],
    "edi_zustimmung":   true,
    "edi_extrahierbar": false,
    "geschaeftspartner": {
      "_typ": "GESCHAEFTSPARTNER",
      "anrede": "FRAU",
      "adresse": {
        "_typ": "ADRESSE",
        "strasse": "Musterstraße",
        "hausnummer": "1",
        "postleitzahl": "10115",
        "ort": "Berlin",
        "landescode": "DE"
      }
    }
  }'
```

The `GET` returns the same fields plus `mp_id`, `version` and `updated_at`. A
stored document that does not decode is returned raw in `geschaeftspartner`
rather than failing the read.

---

## Marktlokation and Messlokation

A `PUT /api/v1/malos/{malo_id}` decodes `data` as `Marktlokation` (`_typ`
injected when absent, `422` for another `_typ` or an unknown enum value),
stores the canonical camelCase form, and derives the typed columns from the
typed object:

| Column | Vocabulary | Purpose |
|---|---|---|
| `netzebene` | `NSP` \| `MSP` \| `HSP` \| `HSS` \| `MSP_NSP_UMSP` \| `HSP_MSP_UMSP` \| `HSS_HSP_UMSP` \| `HD` \| `MD` \| `ND` | NNE tier |
| `bilanzierungsgebiet` | EIC (`Y`) | `processd` NB check 4 |
| `gasqualitaet` | `H_GAS` \| `L_GAS` | Gas tariff routing |
| `energierichtung` | `EINSP` (feeds the grid) \| `AUSSP` (draws from it) | Named from the grid's side |
| `bilanzierungsmethode` | `RLM` \| `SLP` \| `IMS` \| `TLP_GEMEINSAM` \| `TLP_GETRENNT` \| `PAUSCHAL` | `netzbilanzd` Leistungspreis routing |
| `regelzone` | EIC | ÜNB for MaBiS IFTSTA 21000 and Redispatch 2.0 |

Every enum column holds a BO4E wire value (`as_wire()`), enforced by a SQL
`CHECK` listing the enum's `VARIANTS`; a `mako-markt` test pins the lists to
`rubo4e`. A field the payload lacks leaves its column `NULL`.

Three MaLo columns are **not** written by this `PUT`: `fallgruppe` (GaBi RLM)
and `abwicklungsmodell` (NZR-EMob, `MODELL_1`/`MODELL_2`; `NULL` means none
stated, not Modell 1) belong to `Bilanzierung`, and `fernsteuerbar` (§14a EnWG)
has no BO4E field. The `Bilanzierung` resource and the UTILMD
Stammdatenänderung (`TM+Z10`, `CCI+Z24++Z96/Z97`, `CCI+ZA2++ZE9/ZF0`) write
them. `lokationsbuendel_objektcode` on `malo` and `melo` is validated on write.

The `PUT` calls no other service. It enqueues `de.mako.markt.malo.updated` (data
`{"version"}`) in the write's transaction; makod's MaLo-Ident cache follows it
through the [fan-out](#fan-out) as a config endpoint and reads the record back —
see [makod's MaLo cache](https://hupe1980.github.io/mako/docs/services/makod/#malo-cache-follows-marktd).

```json
{
  "malo_id": "10001234558",
  "sparte": "STROM",
  "version": 3,
  "netzebene": "NSP",
  "bilanzierungsgebiet": "11YDE-RWE-NETZ-1",
  "gasqualitaet": null,
  "energierichtung": "AUSSP",
  "bilanzierungsmethode": "SLP",
  "regelzone": "10YDE-EON------1",
  "rollenzuordnung": [...],
  "data": { "_typ": "MARKTLOKATION", ... }
}
```

**From makod.** A `de.mako.engine.process.initiated` for 55001/55077 or 44001 patches
`malo.bilanzierungsmethode` (UTILMD `TM+EM`: Z01→SLP, Z02→RLM, Z04→IMS) and
`malo.fallgruppe` (`TM+Z10`). A MaLo not yet stored is a no-op.

A `PUT /api/v1/melos/{melo_id}` runs the same gate and derives
`netzebene_messung` (BO4E `Netzebene` — `NSP`/`MSP`/…, never `NS`) and
`regelzone` from `standorteigenschaften.eigenschaftenStrom[0].regelzoneEic`.
Fill `regelzoneEic`, not `regelzone`: the latter is the zone's free-text name,
and a payload carrying only it leaves the column `NULL`.

```json
{
  "malo_id": "10001234558",
  "data": {
    "_typ": "MESSLOKATION",
    "standorteigenschaften": {
      "eigenschaftenStrom": [
        { "regelzoneEic": "10YDE-EON------1" }
      ]
    }
  }
}
```

---

## UTILMD Stammdaten {#utilmd-stammdaten}

`GET /api/v1/malos/{malo_id}/utilmd-stammdaten?stichtag=YYYY-MM-DD` is the
Marktlokation's UTILMD record on a date, as facts: the record an Anmeldung EoG
(55013 Strom, 44013 Gas) carries whole and makod reads at its boundary. GeLi
Gas 3.0 Kap. 3.3.2 has the NB tell the E/G names and addresses, whether the
Letztverbraucher is a Haushaltskunde, and the identity of the MSB. The
Stichtag is required — an EoG Zuordnung may be retroactive — and every dated
source is resolved for it.

| Fact | Source |
|---|---|
| Netzebene, Gasqualität, Marktgebiet, Lokationsadresse, Endkunde (name, Korrespondenzanschrift), Zählwerke with their OBIS and Konzessionsabgabe | the BO4E `Marktlokation` |
| Prognosegrundlage, Profiltypen, Jahresverbrauchsprognose (kWh), Fallgruppe | the BO4E `Bilanzierung` effective at the start of the Stichtag (Europe/Berlin) |
| Messlokationen | the `MELO → MALO` edges of the location graph covering the Stichtag |
| MSB, its Rolle and Grundlage, the gMSB | `melo_msb_zuordnungen` on the Stichtag |
| Zähler (Nummer, Typ, Größe, fernauslesbar) and their OBIS | `zaehler` (BO4E `Zaehler`) and the `zaehler_register` rows active on the Stichtag |
| Haushaltskunde, Betriebszustand, Termin / nächstes Jahr / Intervall der Netznutzungsabrechnung, `abrechnungsjahresbeginn` for Gas G1.1 DTM+155, Abrechnungsvariante, Gemeinderabatt, Turnusablesung des NB (`MMDD` or `MMWWMMWW`, never `0229`), Netznutzungsvertrag (`KUNDE_NB`/`LIEFERANT_NB`) and its Zahler (`KUNDE` only under `KUNDE_NB`) | `malo_netznutzungsdaten`, written by `PUT /api/v1/malos/{malo_id}/netznutzungsdaten` (NB) |

A fact no row holds is `null` (or an empty list), never a default: the message
that needs it is refused by makod, naming it. The type is
`mako_markt::utilmd_stammdaten::MaloUtilmdStammdaten`.

## Lokationsbündel {#lokationsbuendel}

`GET /api/v1/malos/{malo_id}/lokationsbuendel?stichtag=YYYY-MM-DD` is the
Lokationsbündel the Marktlokation belongs to on a date: what the NB's answer to
a Geschäftsdatenanfrage Stammdaten Strom (UTILMD 55035 / 55095 / 55060,
UTILMD AHB Strom 2.2 Kap. 9.5, S. 599–665) transmits beside the UTILMD
Stammdaten, and what makod reads at its boundary for it. The Stichtag is
required.

| Fact | Source |
|---|---|
| Energierichtung (`AUSSP` verbrauchend, `EINSP` erzeugend) | `malo.energierichtung` |
| Objects — Markt-, Mess-, Netzlokationen, Technische and Steuerbare Ressourcen — and the edges joining them | every `lokationszuordnungen` edge valid on the Stichtag (half-open `[valid_from, valid_to)`) reachable from the Marktlokation, followed in **both** directions: the MeLo PUT writes `MELO → MALO`, the graph API either way |
| Lokationsbündelstruktur | the distinct `lokationsbuendelcode`s of those edges — one is a bündel with a structure, more than one a graph that disagrees with itself |
| Each object's position in it | the object's `lokationsbuendelObjektcode` (typed column of `malo`/`melo`, BO4E document of `nelo`, `technische_ressourcen`, `steuerbare_ressourcen`) |
| Zählertyp-Spezifikation (EDL40/EDL21/sonstiger EHZ, mME Standard/MeDa) | `zaehler.data` (BO4E `Zaehler.zaehlertypSpezifikation`) |
| ÜNB, technische Einrichtungen, normiertes Profil and Verfahren, Netznutzungsabrechnungspositionen (Artikel-ID with Zu-/Abschlag), the Marktlokation's OBIS-Kennzahlen with their Verwendungszwecke for NB/LF/ÜNB, each Zähler register's Wertegranularität | `malo_lokationsbuendel_angaben`, written by `PUT /api/v1/malos/{malo_id}/lokationsbuendel-angaben` (NB) |

The `PUT` refuses a Verwendungszweck the Codeliste der Verwendungszwecke 1.0
(Kap. 2, S. 5–7) does not admit for a Marktlokation and that Marktrolle, a
Zu-/Abschlag with more than two decimals, and an OBIS-Kennzahl listed twice.
A fact no row holds is `null` (or an empty list), never a default. The type is
`mako_markt::lokationsbuendel::MaloLokationsbuendel`.

---

## NB network contracts

`nb_contracts` carries typed columns (`netzebene`, `bilanzierungsmethode`,
`billing_schedule`, `netznutzer_mp_id`, `netznutzer_typ`, `valid_from`,
`valid_to`, plus `vertragsart` and `vertragsstatus` from the payload) and the
full BO4E `Vertrag` in `data`.

```json
{
  "malo_id":             "51238696012",
  "nb_mp_id":            "9900357000004",
  "sparte":              "STROM",
  "netzebene":           "NS",
  "bilanzierungsmethode": "SLP",
  "billing_schedule":    "MONTHLY",
  "netznutzer_mp_id":    "9905555550003",
  "netznutzer_typ":      "LIEFERANT",
  "valid_from":          "2026-10-01",
  "valid_to":            null,
  "data": {
    "_typ":            "VERTRAG",
    "vertragsart":     "NETZNUTZUNGSVERTRAG",
    "vertragsstatus":  "AKTIV",
    "sparte":          "STROM",
    "vertragsbeginn":  "2026-10-01T00:00:00+00:00"
  }
}
```

Without `data` a minimal `Vertrag` (`NETZNUTZUNGSVERTRAG`, `AKTIV`) is built.
`_typ` other than `VERTRAG` or an unknown enum is `422`. The `GET` adds
`contract_id`, `vertragsart`, `vertragsstatus`, `version` and `tenant`.
`netzebene` accepts the Strom levels `NS`/`MS`/`MSP`/`HSP`/`HS`/`HöS`/`HöS/HS`
and the Gas levels `GND`/`GMT`/`GHD`.

`netznutzer_typ` is `LIEFERANT` (default; the LF owes the Netznutzungsentgelt)
or `LETZTVERBRAUCHER` — the **Selbstzahler**, „Netznutzer ohne
All-Inklusiv-Vertrag", who takes the LF role in GPKE (Teil 1, Vorbemerkung) and
is an ordinary LF on the wire.

The flag matters only for the Lieferantenwechsel carve-out, where
[`processd`](https://hupe1980.github.io/mako/docs/services/processd/#selbstzahler-the-lieferantenwechsel-carve-out)
holds an `E03` for the operator.

`GET /api/v1/nb-contracts/by-malo/{malo_id}?on=` is the read `processd` makes
before deciding an Anmeldung.

---

## Database

`migrations/0001_initial.sql` is the whole schema.

| Table | Purpose |
|---|---|
| `malo` · `melo` | Location BOs — JSONB, `bo4e_version`, typed columns |
| `rollenzuordnungen` | Dated NB/LF/MSB roles per MaLo |
| `melo_msb_zuordnungen` | Dated MSB per MeLo, from IFTSTA 21012 — never from the vorläufige Anmeldebestätigung 55043 |
| `zuordnungsermaechtigungen` | Per (LF, BK, BG, ZRT), half-open `[valid_from, valid_to)` under a GiST exclusion: a 55071 opens a row on its Bilanzierungsbeginn, a 55072 ends it on its Deaktivierungsdatum and records the day it was sent (MaBiS Kap. 10.2–10.3) |
| `bilanzierungen` | BO4E `Bilanzierung` per MaLo; a currently effective one derives `malo.fallgruppe` |
| `malo_netznutzungsdaten` | The NB's facts of a MaLo's UTILMD record no BO4E object carries — Gruppenzuordnung, Betriebszustand, Termine and Intervall der Netznutzungsabrechnung, Abrechnungsvariante, Gemeinderabatt, Turnusablesung, Netznutzungsvertrag and Zahler; dated, half-open, non-overlapping |
| `lokationszuordnungen` | Location graph edges, typed `Lokationstyp` (`MALO`/`MELO`/`NELO`/`SR`/`TR`) |
| `malo_lokationsbuendel_angaben` | The NB's Angaben of a MaLo's Lokationsbündel a Geschäftsdatenanfrage answer carries and no BO4E object holds — ÜNB, technische Einrichtungen, normiertes Profil, NNA-Positionen, OBIS Verwendungszwecke, register Wertegranularität; dated, half-open, non-overlapping |
| `partners` | Marktpartner |
| `process_correlation` · `processed_events` | Process tracking per MaLo; inbound idempotency |
| `preisblaetter` · `preisblaetter_messung` · `preisblaetter_konzessionsabgabe` · `preisblaetter_dienstleistung` · `preisblaetter_hardware` | Price sheets |
| `pricat_versions` · `pricat_dispatch_log` | PRICAT snapshots and dispatch attempts |
| `nb_energiemix` | §42 EnWG energy mix per NB and year |
| `mmma_preise_gas` · `mmm_preise_strom` | MMM prices |
| `referenzwerte` · `referenz_importe` | [Referenzreihen](#referenzreihen) values, bitemporal and append-only; one row per imported document |
| `versorgungsstatus` · `lf_zuordnung` · `versorgungsstatus_history` | Supply state, effective LF assignments and the append-only history of decisions |
| `grundversorger` | §36 Abs. 2 EnWG Feststellung per (NB, Sparte) and `default_bilanzkreis` |
| `mabis_zaehlpunkte` | Bilanzierungsgebiet → MaBiS-Zählpunkt |
| `nb_contracts` | NB contracts |
| `nelo` · `tranche` · `malo_grid` | NeLos; Tranchen (open `data`, no BO4E type exists); grid topology |
| `steuerbare_ressourcen` · `technische_ressourcen` | SR (`C[A-Z0-9]{9}[0-9]`); TR |
| `zaehler` · `geraete` · `zaehler_register` · `zaehler_saisons` | Device registry and TOU definitions |
| `event_outbox` · `webhook_endpoints` · `webhook_deliveries` | The shared outbox, the webhook endpoints and the per-endpoint delivery log (`mako_service::subscriptions`) |
| `esa_einwilligungen` · `esa_framework_agreements` · `esa_messprodukt_preise` · `esa_messprodukt_katalog` | ESA consents, agreements, accepted prices, product catalogue |
| `netzzugang_antraege` · `msb_rahmenvertraege` | §20b requests; MSB-Rahmenverträge, both Sparten |

A switch keeps the outgoing LF through the inclusive `zuordnungsende`. Its assignment carries `Abgeloest`, even when the end lies in the future. `Angekuendigt` marks a pending application. The scalar `lf_mp_id` on the supply read names the sole supplier in force on the requested Berlin day.

### Temporal integrity

Dated rows use **half-open `[valid_from, valid_to)`**: a successor starts on its
predecessor's `valid_to`, `NULL` is open-ended. Overlap is unrepresentable —
eight `EXCLUDE USING gist` constraints (with `btree_gist`) refuse two rows in
force on the same day:

| Constraint | Scoped by |
|---|---|
| `rollenzuordnungen_no_overlap` | MaLo × Zuordnungstyp |
| `melo_msb_no_overlap` | tenant × MeLo |
| `nb_contracts_no_overlap` | tenant × MaLo × NB |
| `preisblaetter_no_overlap` | NB |
| `preisblaetter_messung_no_overlap` | MSB |
| `preisblaetter_ka_no_overlap` | NB × Sparte × Kundengruppe |
| `preisblaetter_dienstleistung_no_overlap` · `preisblaetter_hardware_no_overlap` | MSB |

The price-sheet tables add `UNIQUE NULLS NOT DISTINCT (…, valid_from)`, so a
re-`PUT` of an open-started sheet updates instead of duplicating.

An overlap (`23P01`) or a `CHECK` breach (`23514`) is a **`422`** naming the
constraint:

```json
{
  "error":  "Unprocessable Entity",
  "code":   "unprocessable",
  "detail": "unprocessable: conflicting key value violates exclusion constraint \"melo_msb_no_overlap\": the row's [valid_from, valid_to) window overlaps one already stored. Close the existing row at the new start date, or move valid_from."
}
```

Close the incumbent's `valid_to` at the new start. An abutting successor is
never an overlap. `tests/it/temporal_constraints_integration.rs` and
`tests/it/overlap_is_a_client_error.rs` pin each constraint against PostgreSQL.

---

## VersorgungsStatus

One record per MaLo, derived from inbound CloudEvents. Every write appends to
`versorgungsstatus_history` in the same transaction and emits
`de.mako.markt.versorgung.changed`. All operations are idempotent under
at-least-once delivery.

| Phase | CloudEvent | PID | Operation | Effect |
|---|---|---|---|---|
| Announce | `process.initiated` | 55001 / 55077 / 44001 | `announce_lf_next` | Adds an `Angekuendigt` assignment (100 % or the Tranche share) with its Zuordnungsbeginn; `lieferstatus` unchanged |
| Confirm | `process.completed` | 55002 / 55078 / 44002 | `confirm_supply` | Promotes the originating Anmeldung to `Aktiv`. A named Tranche replaces its own running assignment |
| End | `process.completed` | 55005 / 44005, 55008, 55007 with `ohne_antwort` | `end_supply` | Removes the named running assignment (all when none named); `Unbeliefert` only when none is left. An uncovered interval emits `de.mako.markt.versorgung.gap-detected` |
| EoG | `process.completed` | 55013 / 44013 | `begin_eog_supply` | `Ersatzversorgung`/`Grundversorgung` (per `eog_art`), `eog_seit` = Zuordnungsbeginn; Bilanzkreis from the payload, else the NB's `default_bilanzkreis`. Emits `de.mako.markt.versorgung.eog-begonnen` |
| Clear | `process.completed` | 55003 / 55080 / 44003 | `clear_lf_next` | Removes the one announcement identified by the process subject and any supplier named in the refusal |
| Stammdatenänderung | `process.completed` | GPKE Teil 4 / GeLi Gas | `patch_stammdaten` | See below |

```
VersorgungsStatusRecord
├── malo_id, nb_mp_id, msb_mp_id
├── lieferstatus         — Beliefert | Unbeliefert | Grundversorgung | Ersatzversorgung | Ruhend | Stillgelegt
├── zuordnungen[]        — the authoritative supplier list
│   ├── lf_mp_id, prozent, tranche_id (SG5 LOC+Z21; null untranchiert)
│   ├── status           — Angekuendigt | Aktiv
│   └── zuordnungsbeginn, zuordnungsende, process_id
├── lf_mp_id, lf_mp_id_next, lieferbeginn, lf_next_lieferbeginn
│                        — derived; null when there are 0 OR several
├── lieferende, eog_seit, last_process_id, updated_at
└── version              — OCC counter
```

Use `zuordnungen` when a scalar supplier is null. Several pending Anmeldungen can name the same LF and Tranche. An unmatched decision leaves the supply status, version and event stream unchanged.

For 55077, ZW0 replaces the active shares with a whole assignment. ZW2 projects the exact percentage in `tranchengroesse_prozent`. An unresolved share, including a ZW1 transfer without a dated percentage, stays in the forwarded Anmeldung for NB review. It creates no supplier assignment.

```mermaid
stateDiagram-v2
    [*] --> Unbeliefert : MaLo registered
    Unbeliefert --> Beliefert   : 55002/55078/44002 confirm_supply
    Beliefert --> Beliefert     : 55005/44005 on one Tranche
    Beliefert --> Unbeliefert   : 55005/44005/55008/55007 ohne Antwort, last assignment gone
    Unbeliefert --> Ersatzversorgung : 55013/44013 (§38 EnWG)
    Unbeliefert --> Grundversorgung  : 55013/44013 (§36 EnWG)
    Ersatzversorgung --> Grundversorgung : 3 Monate, Haushaltskunde (by law)
    Ersatzversorgung --> Beliefert   : confirm_supply (clears eog_seit)
    Grundversorgung --> Beliefert    : confirm_supply
    Beliefert --> Ruhend    : suspended
    Ruhend --> Beliefert    : reactivated
    Beliefert --> Stillgelegt : decommissioned
    Stillgelegt --> [*]
```

**Gap closure (§38 EnWG).** A gap is an interval no supplier covers. `end_supply`
finds one when the successor starts later or not at all; a Bestätigung finds one
in Fall b, when the Altlieferant answered with an earlier Lieferende (`E_0624`
`A34`, EBD 4.3 Kap. 6.6.3; GPKE Teil 2 Kap. 2.1.2 Nr. 4). The NB's own
`gpke-supplier-change` queues a `ProcessCompleted` beside each Anmeldung answer
(55002/55003/55078/55080), and on a Fall-b Bestätigung it carries that
Lieferende as `lfa_lieferende` next to the Zuordnungsbeginn. Both emit `gap-detected` with
`gap_from`/`gap_until`; `processd` resolves the Grundversorger and dispatches
`gpke.eog.anmelden` (UTILMD 55013).

**GPKE rule A06.** `processd` checks for an announcement by a supplier **other
than** the requesting one. The announcement is recorded before the event is
fanned out, so the Anmeldung under evaluation is already in the projection.

**Tranchen.** `E_0623` Prüfschritte 500–540 decide on the arithmetic over the
shares. A constraint trigger holds the `Aktiv` shares of one MaLo to ≤ 100 % (a
60/60 split is `422`; 60/30 is stored, and Prüfschritt 530 asks about the
remainder).

`Angekuendigt` rows are unbounded — `E_0622` Prüfschritt 70 rules on competing
announcements. A Tranche is always > 0 % and < 100 % (GPKE Teil 1 Kap. 3.2.1.5), so
a `tranche_id` at 100 % is refused. Each refusal is a `422` mapped from the
SQLSTATE.

**Concurrency.** Writes are `WHERE … AND version = $n`; a conflict is
`412 Precondition Failed`.

### `patch_stammdaten`

`data.objekt` selects the typed-column patch; each present field overwrites its
column, the JSONB and `version` are untouched, and an object not held locally is
a no-op.

| `objekt` | Table | Beyond the plain columns |
|---|---|---|
| `MARKTLOKATION` | `malo` | §14a `fernsteuerbar` |
| `MESSLOKATION` | `melo` | MSB-Zuordnung (`CAV+7111=Z91`) on `melo_msb_zuordnungen`, effective the Änderungsdatum |
| `NETZLOKATION` | `nelo` | §14a `steuerkanal` |
| `TECHNISCHE_RESSOURCE` | `technische_ressourcen` | `nutzung` (`CCI+7059`), `verbrauchsart` (`CAV+7111`), `ist_fernschaltbar` |
| `STEUERBARE_RESSOURCE` | `steuerbare_ressourcen` | Konfigurationsprodukte, **replaced**: one per `SG8 SEQ+Z79` (`PIA+5`, `CAV+Z91`/`ZF0`, `CCI+Z66`) |
| `TRANCHE` | `tranche` | — |

It emits `de.mako.markt.malo.stammdaten-geaendert` for a MaLo and
`de.mako.markt.stammdaten.geaendert` otherwise.

### Reading it

```http
GET  /api/v1/versorgung/{malo_id}
GET  /api/v1/versorgung/{malo_id}?at=2025-10-01
GET  /api/v1/versorgung/{malo_id}/history?page=0&size=50
PUT  /api/v1/versorgung/{malo_id}
```

`?at=` returns the state at end of that German calendar day, or `404` when no
history exists by then.

```json
{
  "malo_id": "51238696012",
  "lieferstatus": "Beliefert",
  "zuordnungen": [
    {
      "lf_mp_id": "4012345000023",
      "prozent": "100.000",
      "tranche_id": null,
      "status": "Aktiv",
      "zuordnungsbeginn": "2026-10-01",
      "zuordnungsende": null
    }
  ],
  "lf_mp_id": "4012345000023",
  "lf_mp_id_next": null,
  "lf_next_lieferbeginn": null,
  "lieferbeginn": "2026-10-01",
  "lieferende": null,
  "msb_mp_id": "9900000000002",
  "nb_mp_id": "9900357000004",
  "eog_seit": null,
  "last_process_id": "...",
  "updated_at": "2026-07-10T08:23:41Z",
  "version": 5
}
```

---

## Device registry

```
MeLo ──► Zaehler (1..n) ──► Geraete (0..n)
              └──► Zaehlwerk (0..n, OBIS registers in data.zaehlwerke)
```

- **`Zaehler`** — `data` through the gate. `zaehler_typ` (from `zaehlertyp`,
  `CHECK`ed to the 13 BO4E `Zaehlertyp` variants; `GASZAEHLER` and `UNKNOWN`
  are not among them) and `eichung_bis` (from `eichungBis`) are derived, never
  sent. `Zaehlertyp` spells `INTELLIGENTES_MESSSYSTEM` (three `s`),
  `Geraetetyp` `INTELLIGENTES_MESSYSTEM` (two).
- **`Geraet`** — `data` through the gate; `geraet_typ` from `geraetetyp`, not
  `CHECK`ed; `konfigurationen` stored separately.
- The four device `PUT`s (`zaehler`, `geraete`, `steuerbare-ressourcen`,
  `technische-ressourcen`) inject `_typ` when absent.

```bash
curl -s -X PUT "http://marktd:8180/api/v1/zaehler/Z001234567" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "melo_id": "DE00056789000000000000000012345678",
    "data": {
      "zaehlertyp": "DREHSTROMZAEHLER",
      "eichungBis": "2030-12-31T23:00:00Z",
      "zaehlwerke": [
        { "_typ": "ZAEHLWERK", "obisKennzahl": "1-0:1.8.0", "richtung": "EINSP" }
      ]
    }
  }'
```

### Gerät configuration (MsbG §23)

`geraete.geraet_konfigurationen` is a GIN-indexed JSONB array of
`{parameter, wert, updated_at, notiz}`. `updated_at` is set by the server;
duplicate `parameter`s in one body keep the last.

| `parameter` | Value | Source |
|---|---|---|
| `FIRMWARE_VERSION` | string | BSI TR-03109-1 §4.3 |
| `HARDWARE_REVISION` · `HERSTELLER` · `MSB_VERTRAGSNUMMER` | string | MsbG §23 |
| `KOMMUNIKATION` | `GPRS` / `PLC` / `ETHERNET` / `FUNK` / `FESTNETZ` / `GSM` | — |
| `FERN_UPDATE_FAEHIG` | `"true"` / `"false"` | BSI TR-03109-4 |
| `CLS_FAEHIG` | `"true"` / `"false"` | §14a EnWG, BK6-22-300 |
| `SMGW_TLS_CERT_FINGERPRINT` | 64 hex chars | BSI TR-03109-3 |
| `SMGW_CERT_ABLAUFDATUM` | ISO date | BSI TR-03109-4 §6.3 |
| `CLS_KANAL_ID` | string | GPKE Teil 3 Kap. 2 |
| `GWA_CODENUMMER` | 13 digits | BDEW |
| `INBETRIEBNAHMEDATUM` · `LETZTE_WARTUNG` · `NAECHSTE_WARTUNG` | ISO date | — |
| `AUSLESE_PROTOKOLL` | `SML` / `DLMS` / `IEC62056` | — |
| `SONSTIGES` | string; key in `notiz` | — |

```bash
curl -s -X PUT "http://marktd:8180/api/v1/zaehler/Z001234567/geraete/SMGW-2026-001/konfigurationen" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "konfigurationen": [
      { "parameter": "FIRMWARE_VERSION",       "wert": "3.1.2"            },
      { "parameter": "CLS_FAEHIG",             "wert": "true"             },
      { "parameter": "CLS_KANAL_ID",           "wert": "CLS-00042"        },
      { "parameter": "SMGW_CERT_ABLAUFDATUM",  "wert": "2027-06-30"       },
      { "parameter": "GWA_CODENUMMER",         "wert": "9900000000099"    }
    ]
  }'
# → 204 No Content + de.mako.markt.geraet.konfiguration.updated
```

The configuration is master data for the ERP and `agentd`'s
`smgw-diagnostics-agent`; no service decides on it (`processd`'s §14a
Steuerungsauftrag reads the SteuerbareRessource, `edmd`'s certificate expiry its
own `SmgwSession`).

### TOU registers and Zaehlzeitdefinition

`zaehler_register` (HT / NT / EINZEL, OBIS, validity) and `zaehler_saisons`
(`SOMMER` / `WINTER` / `GESAMT`, `wochentage`, `zeit_von` inclusive and
`zeit_bis` exclusive, German local time) describe iMSys TOU bands. A window
whose `zeit_von` is after its `zeit_bis` crosses midnight: NT 22:00–06:00 is one
row, holding every time at or after 22:00 or before 06:00, so 06:00 itself is
outside it. A window belongs to the day it opens on: „Mo–Fr 22:00–06:00" holds
Friday 22:00 to Saturday 06:00 and not Monday 00:00–06:00, which is the tail of
Sunday's night.

A `SOMMER` or `WINTER` window carries its season's calendar days,
`saison_von` inclusive and `saison_bis` exclusive as `"MM-DD"`; a `saison_von`
after `saison_bis` crosses the turn of the year (WINTER `"10-01"` to
`"04-01"`). No published rule fixes when a Zählzeit season begins — BO4E's
`Zaehlzeitdefinition` leaves the dates to a `saisonprofil` the market partners
agree on — so the window states the Preisblatt's dates. A `GESAMT` window holds
all year and carries neither; the schema refuses an undated `SOMMER`/`WINTER`
window and a dated `GESAMT` one.

The season is the instant's own calendar day,
while the weekday stays the day the window opened on: on 1 April a SOMMER
night that opened on 31 March takes over from WINTER's at midnight, so the
seasons' windows meet without a gap or an overlap.

`GET …/tariff-zone?datetime=` classifies one Europe/Berlin wall-clock datetime
against the registers valid on its day — validity is half-open
`[valid_from, valid_to)`, so a register replaced since still answers for the
time before its replacement — and the windows of that day's season.
`GET …/zaehlzeitdefinitionen` assembles them into a BO4E `Zaehlzeitdefinition`.
A single-rate meter answers `EINZEL` from its own window. An instant no window
covers is a `422`, never a defaulted `EINZEL`, and so is one that windows of
different zones both hold: the row order does not choose between them.

A register is identified by Zähler, `bezeichnung` and `valid_from`, a window by
register, `saison` and `zeit_von`; a second `PUT` with the same identity updates
it. Each `PUT` answers `200` with the row as stored — the register's `id` is the
path of its windows. The Zähler, the register and the tenant come from the path
and the session, so a body naming `id`, `tenant` or `updated_at` is a `422`, as
is a window with `zeit_von` equal to `zeit_bis`, a weekday outside 1–7 or named
twice, a `SOMMER`/`WINTER` window without both season days, a `GESAMT` window
with one, or a season day not every year has (`"02-29"`). A register
the caller's tenant does not hold takes no window: `404`.

```bash
REGISTER_ID=$(curl -s -X PUT "http://marktd:8180/api/v1/zaehler/Z001234567/register" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "bezeichnung": "HT",
    "zaehlerauspraegung": "HT",
    "obis_kennzahl": "1-1:1.8.1",
    "valid_from": "2025-01-01"
  }' | jq -r .id)

curl -s -X PUT "http://marktd:8180/api/v1/zaehler-register/${REGISTER_ID}/saisons" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "saison": "WINTER",
    "saison_von": "10-01",
    "saison_bis": "04-01",
    "wochentage": [1,2,3,4,5],
    "zeit_von": "07:00",
    "zeit_bis": "22:00"
  }'

curl -s "http://marktd:8180/api/v1/zaehler/Z001234567/tariff-zone?datetime=2026-01-15T14:30:00" \
  -H "Authorization: Bearer <token>"
# → { "zaehler_id": "Z001234567", "local_datetime": "2026-01-15T14:30:00", "tariff_zone": "HT" }
```

### SteuerbareRessource and TechnischeRessource

An SR-ID is `C[A-Z0-9]{9}[0-9]` (check digit by the ASCII procedure). The
`konfigurationsprodukte` sub-resource is replaced as a whole. The body is
`{"konfigurationsprodukte": [...]}` — the list is required (`[]` clears it) —
and each element crosses the BO4E gate as a `Konfigurationsprodukt` with a
non-empty `produktcode`. A key the body or BO4E does not define, at any depth,
is `422` (`bo4e.unknown_field` inside an element): `bandNummer` is one. A `PUT` emits `de.mako.markt.sr.konfigurationsprodukt.updated`;
`processd` refuses a Steuerungsauftrag for an uncontracted `produktcode`.

```bash
curl -s -X PUT "http://marktd:8180/api/v1/steuerbare-ressourcen/C0000000011/konfigurationsprodukte" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "konfigurationsprodukte": [ { "produktcode": "FLEX-PRODUCT-001" } ]
  }'
```

A TechnischeRessource links a charging point, generator or storage unit to a
MaLo/MeLo. `nutzung` (`STROMVERBRAUCHSART` | `STROMERZEUGUNGSART` | `SPEICHER`),
`verbrauchsart` (`KRAFT_LICHT` | `WAERME` | `E_MOBILITAET` |
`STRASSENBELEUCHTUNG`, consumption only) and `ist_fernschaltbar` come from the
payload; an invalid value is `400`.

### NeLo

A Netzlokation is identified by a 16-character EIC or a 13-digit
BDEW-Codenummer and owned by an NB. `steuerkanal`, `eigenschaft_msb_lokation`
and `grundzustaendiger_msb_codenr` are typed columns. Writes need the `NB` role.

---

## Location graph

`lokationszuordnungen` holds directed, dated edges between typed nodes.
`GET /api/v1/malos/{id}/lokationen` (or `/melos/{id}/lokationen`) walks them
with a recursive CTE (max depth 8), ordered by `depth`; `?at=` filters by
validity. Several edges per `(von_id, nach_id)` are allowed with distinct
`valid_from`, at most one open-started.

### Lokationsbündel structure audit {#lokationsbuendel-audit}

`GET /api/v1/malos/{id}/buendel` projects the bundle of MeLos, NeLos, SRs and
TRs under a MaLo (`mako_markt::repository::Lokationsbuendel`). A consuming MaLo
needs at least one MeLo and every MeLo the same MSB; a bundle incomplete
mid-Einzug reports `valid: false` with `validation_error` rather than failing.

`struktur` and `befunde` audit the declared `lokationsbuendelcode` — a code from
EDI@Energy's *Codeliste der Lokationsbündelstrukturen* (v1.0, 31.03.2023,
applicable from 01.10.2024): check digit, structure, then per-object-type
cardinalities.

Steuerbare Ressourcen have no code in the list, and the projection keeps only
the root MaLo, so the three *Summenmessung* structures report „audit the BO4E
Lokationszuordnung instead". The per-code audit is `rubo4e`'s
`Lokationszuordnung::audit_buendel()` over an edge's `data`.

```json
{
  "malo_id": "51238696012",
  "lokationsbuendelcode": "9992000000026",
  "messlokationen": ["DE0001234567890123456789012345678"],
  "netzlokationen": [],
  "steuerbare_ressourcen": [],
  "technische_ressourcen": [],
  "valid": true,
  "struktur": {
    "code": "9992000000026",
    "bezeichnung": "Verbrauch mit einer Messlokation (Standard)",
    "max_ebene": 1
  },
  "befunde": []
}
```

A departure from the declared structure is **reported, not refused**
(`"the structure permits 1 Messlokation, the bundle holds 2"`).
`PUT /api/v1/lokationszuordnungen` answers `{ "id", "befunde" }` on the same
terms — an edge is often asserted before its objects exist. A `malo`/`melo`
`PUT` does refuse a mis-typed object code, because it lands in a typed column.

```http
PUT /api/v1/lokationszuordnungen
Content-Type: application/json

{
  "von_id":    "51238696012",
  "von_typ":   "MALO",
  "nach_id":   "DE-MEL-001",
  "nach_typ":  "MELO",
  "valid_from": null,
  "valid_to":   null,
  "data": {
    "lokationsbuendelcode": "9992000000026"
  }
}
```

---

## Fan-out

Every produced or relayed event is written to `event_outbox` in the
transaction of the write that caused it, and delivered by the shared webhook
module — see [Webhooks](#webhooks). The ordering key is the Marktlokation,
else the Messlokation: a delivery waits while an earlier event about the same
MaLo is outstanding to the same endpoint, and events about other MaLos never
wait. Events can carry `marktsparte` and `marktrole` for routing. An
event without `marktsparte` whose `data` names a `sparte` carries that one.

The other mako services receive marktd's events as **config-owned endpoints**,
one `[[subscriptions.endpoints]]` entry each: the API refuses a private
address, and an in-cluster receiver is private by design. The receiver
registers nothing; its entry names the types it reads and the secret it
verifies with (`env:VAR` reads it from the environment):

| Endpoint | `url` | `event_types` | The receiver's secret |
|---|---|---|---|
| `makod` | `http://makod:8080/webhooks/marktd` | `de.mako.markt.malo.updated` | `[marktd] webhook_secret` |
| `processd` | `http://processd:8580/webhook` | the `de.mako.engine.*` lifecycle types and `de.mako.markt.versorgung.{gap-detected,eog-begonnen,changed}` | `[webhook] inbound_secret` |
| `edmd` | `http://edmd:8380/webhook` | `de.mako.engine.process.completed`, `de.mako.markt.malo.updated` | `[webhook] inbound_secret` |
| `invoicd` | `http://invoicd:8280/webhook` | `de.mako.engine.process.initiated` | `[webhook] inbound_secret` |

`deploy/demo/marktd.toml` is the full set; a processd entry that leaves out a
type processd reads silently disables a module, which processd's
`published_config` test refuses for the demo. An entry narrows on an extension
with `extensions = { marktsparte = "GAS" }` — an event without the extension
then does not match.

## Webhooks

marktd mounts the shared subscription module: endpoint CRUD with a `whsec_`
secret shown once, rotation, test deliveries, the delivery log, replay of one
delivery or a window, and `GET /api/v1/events`. The routes, the signature, the
ordering and the retention are described once, in
[Webhook subscriptions](https://hupe1980.github.io/mako/docs/architecture/erp-integration/#webhook-subscriptions).
A failed delivery is listed with
`GET /api/v1/webhooks/endpoints/{id}/deliveries?status=failed` and replayed
from there; the MCP tools `list_webhook_endpoints` and
`list_webhook_deliveries` read the same.

### Metrics

Four gauges, sampled together once a minute:

| Metric | Meaning |
|---|---|
| `marktd_fanout_dlq_depth` | Dead-lettered webhook deliveries; non-zero means an endpoint is missing events |
| `marktd_fanout_pending` | In `event_outbox` but not yet fanned out; rising means the worker is behind or stopped |
| `marktd_active_subscriptions` | Active webhook endpoints |
| `marktd_processed_events` | Rows in the inbound idempotency table, bounded by the retention sweep; unbounded growth means the sweep is not running |

`mako_service` adds request count, latency and the BO4E decimal-spelling
counter — see
[what `/metrics` carries on every service](https://hupe1980.github.io/mako/docs/architecture/#what-metrics-carries-on-every-service).

---

## CloudEvents

Source: `urn:mako:marktd:tenant:{tenant}`.

| `type` | `subject` | Trigger | Consumers |
|---|---|---|---|
| `de.mako.markt.malo.updated` | `malo_id` | MaLo `PUT` | `edmd`, `processd`, ERP |
| `de.mako.markt.melo.updated` | `melo_id` | MeLo `PUT` | `edmd`, `processd`, ERP |
| `de.mako.markt.malo.stammdaten-geaendert` | `malo_id` | Stammdatenänderung on a MaLo, with the `patch` | ERP |
| `de.mako.markt.stammdaten.geaendert` | object id | Stammdatenänderung on another object | ERP |
| `de.mako.markt.partner.updated` | `mp_id` | Partner `PUT` | `makod`, ERP |
| `de.mako.markt.nb-contract.updated` | `contract_id` | NB contract `PUT` | ERP |
| `de.mako.markt.pricat.published` | `nb_mp_id` | Preisblatt `PUT` | `netzbilanzd`, `invoicd`, ERP |
| `de.mako.markt.sr.konfigurationsprodukt.updated` | `sr_id` | Konfigurationsprodukte replaced | `processd`, ERP |
| `de.mako.markt.geraet.konfiguration.updated` | `geraet_id` | Konfigurationen `PUT` (`geraet_id`, `zaehler_id`, `count`) | `agentd`, ERP |
| `de.mako.markt.msb-rahmenvertrag.updated` | contract id | MSB-Rahmenvertrag upsert (`sparte` in `data`) | ERP |
| `de.mako.markt.netzzugang.antrag.updated` | request id | §20b request upserted or advanced | `makod`, ERP |
| `de.mako.markt.einwilligung.erteilt` | consent id | Consent granted | `makod`, ERP |
| `de.mako.markt.einwilligung.widerrufen` | consent id | Revoked, expired or replaced (`grund`); the 17008 travels as its own outbox command | ERP |
| `de.mako.markt.versorgung.changed` | `malo_id` | Every supply transition and the REST upsert | `vertragd`, `billingd`, ERP |
| `de.mako.markt.versorgung.gap-detected` | `malo_id` | Uncovered interval (§38 EnWG) | `processd` |
| `de.mako.markt.versorgung.eog-begonnen` | `malo_id` | 55013/44013 completed | `processd`, ERP |
| `de.mako.markt.mmma.import.success` · `.failed` | year-month | Monthly MMM import | `netzbilanzd`, `invoicd`; operator |

For a makod notification, marktd publishes a fresh event ID under its configured
tenant. It keeps the event type, occurrence time, payload, schema and subject.
A signed request whose `webhook-id` differs from the event ID receives HTTP 400.
When makod omits the subject, marktd uses the incoming ID. Subscriber routing
uses market fields derived by marktd.

| Extension | Meaning |
|---|---|
| `marktmaloid` · `marktmeloid` | Resolved MaLo / MeLo; the MaLo is the ordering key |
| `marktrole` | `NB`, `LF`, `MSB`, `BIKO`, `UNB` |
| `marktsparte` | `STROM` / `GAS`; absent = not Sparte-scoped |
| `markterpref` | ERP `Idempotency-Key` |
| `makoconvid` · `makopid` · `makoworkflow` | Forwarded from makod |
| `makoerc` | ERC code on `aperak.rejected` |
| `makoakteur` | Engine actor class, such as `system` or `freigabe`, preserved through fan-out |
| `dataschema` | Schema URI for a typed payload, preserved from the producer |
| `traceparent` · `tracestate` | W3C Trace Context |

For `wim-ersteinbau`, `marktrole` comes from the local party on that announcement. For other relayed events it follows `makoworkflow`. A name ending in `-lf` or
containing `-lf-` → `LF`; `wim-` → `MSB`; `mabis-` → `BIKO`; otherwise `NB`.

```json
{
  "specversion":     "1.0",
  "id":              "01932a4f-7b3e-4c5d-8f6a-9e0b1c2d3e4f",
  "source":          "urn:mako:marktd:tenant:9900357000004",
  "type":            "de.mako.engine.process.completed",
  "time":            "2025-10-01T08:15:00+02:00",
  "subject":         "018f3a2b-7c4e-7d5f-8a9b-0c1d2e3f4a5b",
  "datacontenttype": "application/json",
  "makoconvid":      "018f3a2b-7c4e-7d5f-8a9b-0c1d2e3f4a5b",
  "makopid":         55001,
  "makoworkflow":    "gpke-lieferbeginn",
  "marktrole":       "LF",
  "data": { "_typ": "MARKTLOKATION", "marktlokationsId": "51238696012", ... }
}
```

To receive makod's events, point makod at the inbound path:

```toml
# makod.toml
[erp]
webhook_url    = "http://marktd:8180/api/v1/mako/events"
webhook_secret = "shared-hmac-secret"
```

Inbound delivery is idempotent on `event_id`.

---

## MCP server

`POST /mcp` (Streamable HTTP, revisions 2026-07-28 and 2025-11-25, no session) has its **own**
credential layer, `[mcp]` (API key or OIDC), independent of the REST `[oidc]`;
the principal is then checked against the single Cedar action `use-mcp`.

**Tools (24)**, every one a read:

| Tool | Description |
|---|---|
| `get_policy` | The operator policy and posture, as `GET /api/v1/policy` serves it |
| `get_malo` / `list_malo` | One MaLo / list |
| `get_melo` / `get_melo_standorteigenschaften` | MeLo record / site properties |
| `get_partner` / `list_partners` | Marktpartner registry |
| `partner_namen` | Names of up to 200 Marktpartner by MP-ID in one read, typed (`PartnerNamen`; snapshot `mcp.snapshot.json`) |
| `get_preisblatt` | Netznutzung sheet for an NB and date |
| `list_pricat_versions` | PRICAT history; dispatch stays REST-only, because `use-mcp` cannot tell a read from a write |
| `get_versorgungsstatus` | Supply state now |
| `get_versorgungsstatus_history` / `get_versorgung_at` | Supply-state history (paged) and point-in-time; shared reads of the REST `GET`s, typed, Cedar `read-versorgungsstatus` |
| `get_lokationsbuendel` | The [Lokationsbündel](#lokationsbuendel) on a Stichtag; shared read, typed, Cedar `read-utilmd-stammdaten` |
| `get_rollenzuordnung` | Dated NB/MSB/LF roles |
| `get_nb_contract` | NB contract for a MaLo |
| `get_nb_energiemix` | §42 EnWG energy mix |
| `get_correlation` | Process correlation |
| `get_technische_ressource` / `get_steuerbare_ressource` | §14a device registry |
| `list_referenzreihen` / `get_referenzwert` | The [Referenzreihen](#referenzreihen) catalogue; one value as known at `stand`, or `referenzwert_fehlt` |
| `list_webhook_endpoints` / `list_webhook_deliveries` | The [webhook](#webhooks) endpoints and one endpoint's deliveries; twins of the REST reads, Cedar `manage-subscription` |

**Prompts (4):** `lookup-malo`, `investigate-supply-gap`,
`versorgungswechsel-tracking`, `grid-topology`.

---

## Troubleshooting

| Symptom | Cause |
|---|---|
| Container exits at start | A CLI flag other than `--check`/`--print-config`/`--help`, or a missing `[markt] tenant` — the config path is `MARKTD_CONFIG` |
| `401` | `[oidc] issuer`, an expired token, or no `mako_tenant` claim |
| `403` | `mako_tenant` ≠ `[markt] tenant`, or the role is missing (`NB` for grid-operator writes, `ADMIN` for webhooks and the event feed) |
| `404` on a Preisblatt | No sheet valid on `?date=` |
| A PRICAT ingest does not replace a sheet | Intended: an `api` row is never overwritten by a `mako` row |
| `422` naming a `*_no_overlap` constraint | The new window overlaps the row in force; close its `valid_to` |
| Anmeldungen refused or deferred | A `processd` decision. `marktd` owes it data: the MaLo `PUT`, an NB `rollenzuordnung` naming this tenant, a price sheet covering the date |
| `relation "malo" does not exist` | Migrations did not run — check the database URL |

---

## See also

- [`makod`](https://hupe1980.github.io/mako/docs/services/makod/) · [`processd`](https://hupe1980.github.io/mako/docs/services/processd/) · [`netzbilanzd`](https://hupe1980.github.io/mako/docs/services/netzbilanzd/) · [`invoicd`](https://hupe1980.github.io/mako/docs/services/invoicd/) · [`edmd`](https://hupe1980.github.io/mako/docs/services/edmd/)
- [ERP Integration](https://hupe1980.github.io/mako/docs/architecture/erp-integration/) · [Domain Model](https://hupe1980.github.io/mako/docs/architecture/domain-model/) · [Getting Started](https://hupe1980.github.io/mako/docs/guide/getting-started/)
