grid-billing 0.19.0

Role-neutral grid invoice calculation: NNE/KA/MMM/MSB (PIDs 31001/31002/31005/31006/31009/31011) — used by netzbilanzd (NB) and invoicd (LF selbstausstellen). §14a ToU HT/NT. Zero I/O, no float money. Optional `bo4e` feature renders the InvoiceDocument as a rubo4e Rechnung.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Entgelte für dezentrale Erzeugung — §18 StromNEV, under Abschmelzung.
//!
//! §18 StromNEV pays the operator of a decentral generating plant for the
//! upstream network costs its feed-in avoids. The payment is being phased out by
//! Festlegung **GBK-25-02-1#1** (Große Beschlusskammer Energie, 17.02.2026):
//! the underlying vermiedene Kosten are cut in three steps and the payments end
//! entirely with 2028.
//!
//! ## The schedule, from the Tenor
//!
//! Tenorziffer 2 Satz 2 cuts the costs "in drei Stufen um a) 50 vom Hundert
//! beginnend am 01. Juli 2026, b) 50 von Hundert beginnend am 01. Januar 2027
//! c) und 75 vom Hundert beginnend am 01. Januar 2028"; Satz 3 states the
//! effect: "Die Kürzungen entsprechen einer jährlichen Abschmelzung von 25 %."
//!
//! | Period | Remaining factor | Annual average |
//! |---|---|---|
//! | to 30.06.2026 | 1.00 | 2026: 0.75 |
//! | 01.07.2026 – 31.12.2026 | 0.50 | |
//! | 2027 | 0.50 | 0.50 |
//! | 2028 | 0.25 | 0.25 |
//! | from 2029 | 0.00 | — |
//!
//! The two 50 % steps are not cumulative: the 2027 cut restates the same level
//! the July 2026 cut reached, which is what makes the *annual averages* fall by
//! 25 percentage points a year.
//!
//! ## EEG plants are excluded
//!
//! §18 Abs. 1 Satz 4 Nr. 1 StromNEV: a plant funded under the EEG receives no
//! Entgelt für dezentrale Erzeugung. Settling one is refused as an error, not
//! warned — the payment would be unlawful, and unlike a ceiling breach there is
//! no legitimate reading under which it goes out anyway.

use crate::rounding::RoundMoney;
use rust_decimal::Decimal;
use rust_decimal::dec;
use time::Date;

use crate::error::BillingError;
use crate::types::{
    BillingPositionKind, CalculationTrace, LegalReference, SettlementPeriod, SettlementPosition,
    SettlementResult, SettlementStatus, SettlementType, Sparte, TariffSource,
};

/// First day of the first cut (Tenorziffer 2 Satz 2 lit. a).
const STUFE_A: Date = time::macros::date!(2026 - 07 - 01);
/// First day of the second cut (lit. b).
const STUFE_B: Date = time::macros::date!(2027 - 01 - 01);
/// First day of the third cut (lit. c).
const STUFE_C: Date = time::macros::date!(2028 - 01 - 01);
/// First day with no payment at all.
const ENDE: Date = time::macros::date!(2029 - 01 - 01);

/// The Tenorziffer 2 schedule: each step's first day and the factor from it.
///
/// Written as the Tenor writes it — one row per lit., in order — so lit. b
/// carrying the same factor as lit. a is visible rather than inferred. That is
/// the non-compounding reading Satz 3 forces („eine jährliche Abschmelzung von
/// 25 %"); compounding would put 2027 at 0.25 and the annual averages at
/// 0.75 / 0.25 / 0.125.
const ABSCHMELZUNG: [(Date, Decimal); 4] = [
    (STUFE_A, dec!(0.50)),
    (STUFE_B, dec!(0.50)),
    (STUFE_C, dec!(0.25)),
    (ENDE, Decimal::ZERO),
];

/// The fraction of the vermiedene Kosten still payable on a given day.
///
/// GBK-25-02-1#1 Tenorziffer 2. The factor is a property of the *day the energy
/// was fed in*, so a settlement over a period that crosses a step must split the
/// period — which [`settle_dezentrale_einspeisung`] enforces rather than
/// averaging across the step.
#[must_use]
pub fn abschmelzfaktor(tag: Date) -> Decimal {
    ABSCHMELZUNG
        .iter()
        .rev()
        .find(|(ab, _)| tag >= *ab)
        .map_or(Decimal::ONE, |(_, faktor)| *faktor)
}

/// `true` when the factor changes inside the period.
#[must_use]
pub fn period_crosses_a_step(period: SettlementPeriod) -> bool {
    abschmelzfaktor(period.from()) != abschmelzfaktor(period.to())
}

/// Input for a §18 settlement — the DSO's payment to a decentral generator.
#[derive(Debug, Clone, serde::Serialize)]
pub struct DezentraleEinspeisungInput {
    /// The generating plant's metering location.
    pub malo_id: String,
    /// The paying Netzbetreiber.
    pub nb_mp_id: String,
    /// The plant operator being paid.
    pub anlagenbetreiber_mp_id: String,
    /// The delivery period.
    pub period: SettlementPeriod,
    /// Energy fed in during the period, in kWh.
    pub einspeisung_kwh: Decimal,
    /// The vermiedene Kosten of the upstream level, in ct/kWh, **before** the
    /// Abschmelzung — the engine applies the factor for the period.
    pub vermiedene_kosten_ct_per_kwh: Decimal,
    /// `true` when the plant is funded under the EEG.
    ///
    /// §18 Abs. 1 Satz 4 Nr. 1 StromNEV excludes such plants from the payment
    /// entirely; settling one is refused.
    pub ist_eeg_gefoerdert: bool,
    /// Price-sheet identifier for the trace, where one exists.
    pub tariff_sheet_id: Option<String>,
}

/// Settle the §18 payment for one plant and period.
///
/// The result is a payment *from* the Netzbetreiber *to* the plant operator, so
/// the position is negative from the NB's books — consistent with how a
/// Mehrmengen credit is signed elsewhere in this crate.
///
/// # Errors
///
/// - [`BillingError::InvalidInput`] for an EEG-funded plant (§18 Abs. 1 S. 4
///   Nr. 1 — the payment would be unlawful).
/// - [`BillingError::InvalidInput`] when the period crosses an Abschmelzung
///   step: the factor differs at its start and its end, so one settlement over
///   it would pay part of the energy at the wrong level. Split the period at
///   the step date.
/// - [`BillingError::InvalidInput`] for negative energy or a negative rate.
pub fn settle_dezentrale_einspeisung(
    input: &DezentraleEinspeisungInput,
) -> Result<SettlementResult, BillingError> {
    if input.ist_eeg_gefoerdert {
        return Err(BillingError::InvalidInput {
            reason: "an EEG-funded plant receives no Entgelt für dezentrale Erzeugung \
                     (§18 Abs. 1 Satz 4 Nr. 1 StromNEV)"
                .to_owned(),
        });
    }
    if input.einspeisung_kwh < Decimal::ZERO {
        return Err(BillingError::InvalidInput {
            reason: "einspeisung_kwh must be non-negative".to_owned(),
        });
    }
    if input.vermiedene_kosten_ct_per_kwh < Decimal::ZERO {
        return Err(BillingError::InvalidInput {
            reason: "vermiedene_kosten_ct_per_kwh must be non-negative".to_owned(),
        });
    }
    if period_crosses_a_step(input.period) {
        return Err(BillingError::InvalidInput {
            reason: format!(
                "the period {}{} crosses a GBK-25-02-1#1 Abschmelzung step; \
                 split it at the step date so each part is paid at its factor",
                input.period.from(),
                input.period.to()
            ),
        });
    }

    let faktor = abschmelzfaktor(input.period.from());
    let base_eur = input.vermiedene_kosten_ct_per_kwh / dec!(100);
    // Negative: the NB pays out, and the **rate** carries the sign. The energy
    // fed in is a metered fact and stays positive, and a position whose stated
    // quantity times its stated unit price is the opposite of its stated net is
    // one the recipient's own arithmetic contradicts.
    let reduced_eur = -(base_eur * faktor).round_kfm(6);
    let net_eur = crate::billing::pos_net(input.einspeisung_kwh, reduced_eur);

    let mut positions = Vec::new();
    let mut warnings = Vec::new();
    // Exempt from `ensure_berechenbar` (the AgNeS guard): the §18 payment has
    // its own, earlier sunset — GBK-25-02-1#1 ends it with 2028, and a 2029+
    // period settles to zero with the Info below. Nothing is ever priced under
    // lapsed rules here, so refusing on the Entgelt axis would only turn an
    // already-explicit "nothing is payable" into an error.
    crate::billing::warn_if_straddles_turnover(
        input.period.from(),
        input.period.to(),
        &mut warnings,
    );
    if faktor.is_zero() {
        warnings.push(crate::types::SettlementWarning {
            severity: crate::types::WarningSeverity::Info,
            code: "SECT18_ABGESCHMOLZEN",
            message: "the Entgelt für dezentrale Erzeugung is fully phased out for this \
                      period (GBK-25-02-1#1); nothing is payable"
                .to_owned(),
        });
    } else {
        positions.push(SettlementPosition {
            text: format!(
                "Entgelt für dezentrale Erzeugung ({} % nach Abschmelzung)",
                (faktor * dec!(100)).normalize()
            ),
            kind: BillingPositionKind::DezentraleEinspeisung,
            quantity: input.einspeisung_kwh.round_kfm(3),
            unit: crate::types::QuantityUnit::Kwh,
            unit_price_eur: reduced_eur,
            net_eur,
            spot_price_formula: None,
            trace: CalculationTrace {
                explanation: format!(
                    "{:.3} kWh × {:.6} EUR/kWh (= −{:.6} × {faktor} Abschmelzung) = {:.5} EUR \
                     payable to the plant operator",
                    input.einspeisung_kwh,
                    reduced_eur,
                    base_eur,
                    net_eur.abs()
                ),
                input_quantity: input.einspeisung_kwh,
                input_unit_price_eur: reduced_eur,
                gross_eur: net_eur,
                legal_refs: vec![
                    LegalReference::StromNev { paragraph: "§18" },
                    LegalReference::BnetzaDecision {
                        reference: "GBK-25-02-1#1",
                    },
                ],
                tariff_source: input
                    .tariff_sheet_id
                    .clone()
                    .map(|sheet_id| TariffSource::PublishedTariffSheet { sheet_id }),
                regulatory_reduction_factor: Some(faktor),
                rounding_note: Some("unit price to 6 dp; net to 5 dp"),
            },
        });
    }

    Ok(SettlementResult {
        malo_id: input.malo_id.clone(),
        sparte: Sparte::Strom,
        regime: crate::regulatory::RegulatoryRegime::for_period(
            input.period.from(),
            input.period.to(),
        ),
        settlement_type: SettlementType::DezentraleEinspeisung,
        status: SettlementStatus::Initial,
        korrektur_grund: None,
        period: input.period,
        sender_mp_id: input.nb_mp_id.clone(),
        recipient_mp_id: input.anlagenbetreiber_mp_id.clone(),
        total_eur: positions
            .iter()
            .map(|p| p.net_eur)
            .sum::<Decimal>()
            .round_kfm(2),
        // The Entgelt für dezentrale Einspeisung is consideration for a service
        // the Anlagenbetreiber renders to the network (§18 StromNEV), settled by
        // Gutschrift. It is not a supply of energy, so §13b never reaches it.
        steuer: crate::umsatzsteuer::steuerausweis(
            positions
                .iter()
                .map(|p| p.net_eur)
                .sum::<Decimal>()
                .round_kfm(2),
            crate::umsatzsteuer::Leistungsart::SonstigeLeistung,
            crate::umsatzsteuer::Wiederverkaeuferstatus::KEINER,
            input.period,
        )?,
        positions,
        warnings,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use time::macros::date;

    fn base(period: SettlementPeriod) -> DezentraleEinspeisungInput {
        DezentraleEinspeisungInput {
            malo_id: "51238696012".to_owned(),
            nb_mp_id: "9900357000004".to_owned(),
            anlagenbetreiber_mp_id: "9900012345678".to_owned(),
            period,
            einspeisung_kwh: dec!(10_000),
            vermiedene_kosten_ct_per_kwh: dec!(0.60),
            ist_eeg_gefoerdert: false,
            tariff_sheet_id: None,
        }
    }

    fn p(from: Date, to: Date) -> SettlementPeriod {
        SettlementPeriod::new(from, to).expect("valid period")
    }

    /// The Tenor's schedule, day by day at each boundary.
    #[test]
    fn the_tenor_schedule() {
        assert_eq!(abschmelzfaktor(date!(2026 - 06 - 30)), Decimal::ONE);
        assert_eq!(abschmelzfaktor(date!(2026 - 07 - 01)), dec!(0.50));
        assert_eq!(abschmelzfaktor(date!(2027 - 06 - 15)), dec!(0.50));
        assert_eq!(abschmelzfaktor(date!(2028 - 01 - 01)), dec!(0.25));
        assert_eq!(abschmelzfaktor(date!(2028 - 12 - 31)), dec!(0.25));
        assert_eq!(abschmelzfaktor(date!(2029 - 01 - 01)), Decimal::ZERO);
    }

    /// The annual averages fall by 25 points a year — the Tenor's own
    /// cross-check ("Die Kürzungen entsprechen einer jährlichen Abschmelzung
    /// von 25 %").
    #[test]
    fn the_annual_averages_fall_by_a_quarter() {
        // 2026: half the year at 1.00, half at 0.50.
        let h1 = abschmelzfaktor(date!(2026 - 03 - 01));
        let h2 = abschmelzfaktor(date!(2026 - 09 - 01));
        assert_eq!((h1 + h2) / dec!(2), dec!(0.75));
        assert_eq!(abschmelzfaktor(date!(2027 - 07 - 01)), dec!(0.50));
        assert_eq!(abschmelzfaktor(date!(2028 - 07 - 01)), dec!(0.25));
    }

    /// A pre-cut month pays the full rate; a 2028 month a quarter of it.
    #[test]
    fn the_factor_reaches_the_payment() {
        let full =
            settle_dezentrale_einspeisung(&base(p(date!(2026 - 01 - 01), date!(2026 - 01 - 31))))
                .expect("settles");
        // 10 000 kWh × 0.006 EUR = 60 EUR, paid out → negative.
        assert_eq!(full.total_eur, dec!(-60.00));

        let quarter =
            settle_dezentrale_einspeisung(&base(p(date!(2028 - 03 - 01), date!(2028 - 03 - 31))))
                .expect("settles");
        assert_eq!(quarter.total_eur, dec!(-15.00));
        assert_eq!(
            quarter.positions[0].trace.regulatory_reduction_factor,
            Some(dec!(0.25))
        );
    }

    /// **Invariant: the payment position multiplies out.**
    ///
    /// The §18 Entgelt is money the Netzbetreiber pays out, and the sign belongs
    /// to the rate rather than to the net: a position stating a positive
    /// quantity against a positive unit price with a negative net contradicts
    /// its own arithmetic, which `invoic-checker` reads as a 200 % error and
    /// refuses to dispatch.
    #[test]
    fn the_payment_position_states_a_negative_rate() {
        let r =
            settle_dezentrale_einspeisung(&base(p(date!(2026 - 01 - 01), date!(2026 - 01 - 31))))
                .expect("settles");
        let pos = &r.positions[0];
        assert_eq!(
            pos.quantity,
            dec!(10000),
            "the metered feed-in stays positive"
        );
        assert_eq!(pos.unit_price_eur, dec!(-0.006));
        assert_eq!(pos.net_eur, dec!(-60.00000));
        assert_eq!(pos.quantity * pos.unit_price_eur, pos.net_eur);
    }

    /// June–July 2026 crosses the first step and must be split, not averaged.
    #[test]
    fn a_period_across_a_step_is_refused() {
        let r =
            settle_dezentrale_einspeisung(&base(p(date!(2026 - 06 - 15), date!(2026 - 07 - 15))));
        assert!(matches!(r, Err(BillingError::InvalidInput { .. })));
    }

    /// §18 Abs. 1 Satz 4 Nr. 1: an EEG plant gets nothing, and settling one is
    /// an error rather than a zero — the payment would be unlawful.
    #[test]
    fn an_eeg_plant_is_refused() {
        let mut i = base(p(date!(2026 - 01 - 01), date!(2026 - 01 - 31)));
        i.ist_eeg_gefoerdert = true;
        assert!(matches!(
            settle_dezentrale_einspeisung(&i),
            Err(BillingError::InvalidInput { .. })
        ));
    }

    /// A period across the 2025/2026 Netzzugang turnover crosses no
    /// Abschmelzung step, so it settles — but it carries the same
    /// REGIME_TURNOVER_IN_PERIOD warning every other builder emits.
    #[test]
    fn a_period_across_the_netzzugang_turnover_warns() {
        let r =
            settle_dezentrale_einspeisung(&base(p(date!(2025 - 12 - 15), date!(2026 - 01 - 15))))
                .expect("no Abschmelzung step is crossed");
        assert!(
            r.warnings
                .iter()
                .any(|w| w.code == "REGIME_TURNOVER_IN_PERIOD"),
            "warnings: {:?}",
            r.warnings
        );
    }

    /// From 2029 nothing is payable: no position, an Info saying why.
    #[test]
    fn from_2029_nothing_is_payable() {
        let r =
            settle_dezentrale_einspeisung(&base(p(date!(2029 - 02 - 01), date!(2029 - 02 - 28))))
                .expect("settles to zero");
        assert!(r.positions.is_empty());
        assert_eq!(r.total_eur, Decimal::ZERO);
        assert!(r.warnings.iter().any(|w| w.code == "SECT18_ABGESCHMOLZEN"));
    }

    /// Tenorziffer 2 Satz 3 states the effect as „eine jährliche Abschmelzung
    /// von 25 %", which only holds if lit. b restates the level lit. a reached
    /// instead of compounding onto it. Compounding would put 2027 at 0.25 and
    /// the annual averages at 0.75 / 0.25 / 0.125.
    #[test]
    fn the_second_fifty_percent_step_restates_rather_than_compounds() {
        assert_eq!(abschmelzfaktor(STUFE_A), dec!(0.50));
        assert_eq!(
            abschmelzfaktor(STUFE_B),
            abschmelzfaktor(STUFE_A),
            "lit. b is the same level as lit. a"
        );
        assert_eq!(abschmelzfaktor(STUFE_C), dec!(0.25));
        assert_eq!(abschmelzfaktor(ENDE), Decimal::ZERO);
    }
}