grid-billing
Deterministic, regulation-aware German grid settlement engine — NNE, KA, MMM, MSB, and GeLi Gas AWH Sperrprozesse (PIDs 31001, 31002, 31005, 31006, 31009, 31011).
What this crate does
grid-billing computes BDEW INVOIC billing positions with full explainability:
- NNE Strom (PID 31001) — flat-rate Arbeit, Leistung (RLM), Konzessionsabgabe
- NNE Gas (PID 31005) — GasNEV §14 legal basis, auto-set when
Sparte::Gas - §14a Modul 2 ToU — mandatory HT/NT Arbeit split for controllable loads (BNetzA BK6-22-300)
- Selbst ausgestellte NNE (PID 31006) — LF runs the identical formula (§20 MessZV)
- MMM Strom (PID 31002) — Mehr-/Mindermengensaldo, StromNZV §15
- MMM Gas (PID 31002 via GasNZV §14) — Gas imbalance with GeLi Gas legal basis
- MSB-Rechnung (PID 31009) — Grundgebühr Messstellenbetrieb + optional Messdienstleistung
- GeLi Gas AWH Sperrprozesse (PID 31011) — abrechnungswürdige Handlungen (BK7-24-01-009 §5.4)
- Reversal (Stornorechnung) —
calculate_reversal()negates any prior settlement immutably
All calculations are pure functions — zero I/O, zero async, no side effects.
All monetary arithmetic uses rust_decimal::Decimal via billing::EuroAmount — no f64 anywhere.
Architecture
Settlement flow
NneInput / MmmInput / MsbInput
│
▼
validate_*_input() ← optional pre-check: ValidationResult
│
▼
calculate_*_invoice() ← pure, deterministic, no I/O
│
▼
GridSettlement {
pid, settlement_type, status,
rechnungsnummer, correction_of,
nb_mp_id, counterparty_mp_id, ← auto-populated from input
positions: Vec<InvoicePosition {
text, quantity, unit, unit_price_eur, net_eur,
trace: CalculationTrace { ← "why is this amount here?"
explanation,
legal_refs: Vec<LegalReference>, ← StromNEV §17, KAV §2, …
tariff_source: Option<TariffSource>,
gross_eur, regulatory_reduction_factor, …
}
}>,
total_eur,
warnings: Vec<SettlementWarning>,
}
│
▼ (service-layer concern — grid-billing has no rubo4e dep)
into_rechnung(&settlement) → rubo4e::current::Rechnung
│
▼
InvoicCheckEngine::check(pid, &nb_mp_id, &rechnung, …)
│
▼
invoice_drafts (PostgreSQL) → AS4 dispatch
Responsibility split
grid-billing has zero dependency on rubo4e. BO4E conversion lives exclusively in the
service layer, keeping this crate publishable to crates.io without pulling in internal workspace crates.
| Responsibility | Where |
|---|---|
| Settlement math + legal refs | grid-billing |
BO4E Rechnung conversion |
netzbilanzd::into_rechnung() / invoicd::into_rechnung() |
| INVOIC plausibility checks 1–6 | invoic-checker |
| EDIFACT serialization + AS4 dispatch | makod |
Domain types
GridSettlement — canonical output
// Backward-compatible alias — existing code using GridInvoice continues to compile:
pub type GridInvoice = GridSettlement;
Helper methods on GridSettlement:
| Method | Returns | Description |
|---|---|---|
is_clean() |
bool |
true when no Warning/Error severity items in warnings |
recomputed_total() |
Decimal |
Re-sums positions — should equal total_eur (regression guard) |
all_legal_refs() |
Vec<String> |
Deduplicated citation strings across all positions |
positions_count() |
usize |
Number of billing positions |
InvoicePosition with CalculationTrace
Every position carries a full audit record so any amount can be explained without re-running the calculation:
LegalReference
.citation() returns a short German-language string (e.g. "StromNEV §17",
"§14a EnWG Modul 2", "ARegV §17").
TariffSource
Sparte — commodity dispatch
Sparte is required on NneInput and MmmInput. The calculation automatically
selects the correct legal references, SettlementType, and default PID — no
manual r.pid = 31005 override needed for standard Gas paths.
KaKlasse — KAV rate tier
When ka_klasse is set, the KA position text and trace include the tier so
auditors can verify the rate matches the correct KAV §2 band without looking up
the underlying master data.
Who uses this library
| Consumer | Role | Use case |
|---|---|---|
netzbilanzd |
NB | Generate INVOIC 31001/31002/31005/31009/31011 to LF/MSB/LFG |
invoicd |
LF | §20 MessZV selbstausstellen PID 31006 — same formula, LF-initiated |
Quick start
[]
= { = "0.10" }
= "1"
= "0.3"
NNE flat-rate (SLP, Strom)
use ;
use Decimal;
use date;
let settlement = calculate_nne_invoice.expect;
// settlement.total_eur = 52.50 + 1.65 = 54.15 EUR
assert_eq!;
// counterparty_mp_id is auto-populated from lf_mp_id:
assert_eq!;
// Every position is self-explanatory:
for pos in &settlement.positions
NNE Gas (GasNEV §14)
use ;
// Only Sparte changes — GasNEV §14 legal refs and PID 31005 are automatic:
let settlement = calculate_nne_invoice.unwrap;
assert_eq!;
§14a Modul 2 ToU (HT/NT split, mandatory since 2024-01-01)
use ;
let settlement = calculate_nne_invoice.unwrap;
// HT: 600×4.20ct=25.20; NT: 400×1.50ct=6.00; KA: 1000×1.32ct=13.20 → total 44.40 EUR
assert_eq!; // HT + NT + KA
assert!;
Stornorechnung (reversal)
use ;
use date;
let original = calculate_nne_invoice.unwrap;
let storno = calculate_reversal;
assert_eq!;
assert_eq!;
Pre-calculation validation
use ;
let input = NneInput ;
let v = validate_nne_input;
if !v.is_valid
let settlement = calculate_nne_invoice.unwrap;
Service-layer conversion to BO4E Rechnung
// In netzbilanzd/src/billing.rs — grid-billing itself has no rubo4e dep:
use ;
use ;
Generated invoice types
| PID | Description | Direction | billing_type / Sparte |
|---|---|---|---|
| 31001 | NNE Strom | NB → LF | nne_strom / Sparte::Strom |
| 31002 | MMM Strom | NB → LF | mmm_strom / Sparte::Strom |
| 31002 | MMM Gas | GNB → LFG | mmm_gas / Sparte::Gas |
| 31005 | NNE Gas | GNB → LFG | nne_gas / Sparte::Gas (auto) |
| 31006 | Selbst ausgestellte NNE | LF → LF | invoicd only |
| 31009 | MSB-Rechnung | NB → MSB | msb_31009 |
| 31011 | AWH Sperrprozesse Gas | GNB → LFG | nne_gas_awh_31011 (PID override) |
Billing position reference
NNE
| # | Position text | Unit | Condition | Legal basis |
|---|---|---|---|---|
| 1 | Netznutzung Arbeit |
kWh | SLP / RLM flat | StromNEV §21 (Strom) · GasNEV §14 (Gas) |
| 1+2 | Netznutzung Arbeit HT (§14a Modul 2) + NT |
kWh | HT + NT both set | §14a EnWG Modul 2 · BNetzA BK6-22-300 |
| next | Netznutzung Leistung |
kW | spitzenleistung_kw set (RLM) |
StromNEV §17 |
| last | Konzessionsabgabe[tier] |
kWh | ka_satz_ct_per_kwh set |
KAV §2 Abs. 2 |
MMM
| # | Position text | Formula | Condition |
|---|---|---|---|
| 1 | Mehrmengen |
max(0, actual−profil) × mehr_ct ÷ 100 |
actual > profil |
| 2 | Mindermengen (Gutschrift) |
−max(0, profil−actual) × minder_ct ÷ 100 |
profil > actual |
MSB
| # | Position text | Formula | Condition |
|---|---|---|---|
| 1 | Grundgebühr Messstellenbetrieb |
grundgebuehr × months |
Always |
| 2 | Messdienstleistung |
flat amount | messdienstleistung_eur set |
Design invariants
| Invariant | Detail |
|---|---|
| No floating-point money | rust_decimal::Decimal throughout; billing::EuroAmount for overflow guard. No f64. |
| No rubo4e dependency | Returns GridSettlement; service layer owns into_rechnung(). |
counterparty_mp_id auto-populated |
lf_mp_id (NNE/MMM) or msb_mp_id (PID 31009) copied automatically — service layer always has the recipient. |
Sparte drives settlement type |
Sparte::Gas → SettlementType::NneGas, GasNEV §14, PID 31005. No manual override needed. |
| Every position cites regulation | trace.legal_refs is non-empty for every position. Enables BNetzA audit without re-calculation. |
| Immutable correction chain | calculate_reversal() mirrors positions, sets status = Reversal, links via correction_of. Original never mutated. |
| Pure functions | All calculate_* functions are sync with no side effects. |
| Decimal-only input | All rates via Decimal::from_str_exact. Never Decimal::try_from(f64). |
See also
invoic-checker— validates the generatedRechnungin the service layernetzbilanzd— NB billing service that callsgrid-billinginvoicd— LF service usinggrid-billingfor selbstausstellen- Operator guide → netzbilanzd
grid-billing computes BDEW INVOIC billing positions for:
- NNE (Netznutzungsentgelt) — flat-rate or §14a Modul 2 ToU (HT/NT split)
- KA (Konzessionsabgabe) — §17 StromNZV, included as separate position
- MMM (Mehr-/Mindermengensaldo) — actual vs. SLP profile deviation, credit when Mindermengen dominate
- MSB-Rechnung — metering service fee (NB → MSB, PID 31009)
All calculations are pure functions — zero I/O, zero async, no side effects.
All monetary arithmetic uses EuroAmount = i64 × 10⁻⁵ EUR — no f64 anywhere in the billing path.