energy-billing 0.11.0

Pure multi-product retail energy billing for German markets. STROM, GAS, WAERME, SOLAR, EEG, EINSPEISUNG, §14a WAERMEPUMPE/WALLBOX, HEMS, EMOBILITY, ENERGIEDIENSTLEISTUNG, §41a EPEX dynamic. Regulatory rates: §3 StromStG, §2 EnergieStG, BEHG CO₂. BO4E Rechnung JSON. Zero I/O, zero async, no float money.
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! `Invoice` — the aggregate root of every billing run.
//!
//! Collects all `BillingPosition` items from the `BillingEngine` providers,
//! computes totals, and can serialise to BO4E-compatible `Rechnung` JSON.

use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::Serialize;

use crate::context::BillingContext;
use crate::position::{BillingPosition, PositionCategory};

/// A completed invoice — the immutable result of `BillingEngine::bill()`.
///
/// ## Invariants
///
/// - `brutto_eur == netto_eur + mwst_eur` (within 0.001 EUR rounding tolerance)
/// - `zahlbetrag_eur == brutto_eur - abschlag_total_eur`
///
/// ## §40a EnWG — Kilowattstundenpreis
///
/// For electricity billing, call `kilowattstundenpreis_brutto_ct(kwh)` to obtain
/// the all-inclusive price per kWh required on every invoice.
///
/// ## Sign convention
///
/// - `netto_eur > 0` → customer owes the Lieferant (debit invoice)
/// - `netto_eur < 0` → Lieferant owes the customer (credit note / Gutschrift)
/// - `mwst_eur` always has the same sign as `netto_eur`
/// - `zahlbetrag_eur < 0` → refund due to customer (after Abschlag deduction)
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct Invoice {
    /// Billing metadata (period, IDs, invoice type, rates).
    pub context: BillingContext,

    /// All positions in declaration order.
    ///
    /// Debit positions have positive `net_eur`; credit positions have negative.
    /// `Abschlag` positions appear last (deducted from `zahlbetrag_eur` only).
    pub positions: Vec<BillingPosition>,

    /// Total net amount in EUR (Nettobetrag = commodity + grid + levies).
    ///
    /// This is the German Nettobetrag: it **includes** statutory per-unit levies
    /// (Stromsteuer, Energiesteuer, BEHG) but excludes MwSt.
    /// Does NOT include `Abschlag` deductions.
    pub netto_eur: Decimal,

    /// MwSt amount in EUR.
    pub mwst_eur: Decimal,

    /// Brutto total in EUR (Netto + MwSt).
    ///
    /// Before subtracting advance payments. `Abschlag` deductions are in
    /// `zahlbetrag_eur`.
    pub brutto_eur: Decimal,

    /// Total of advance payments (Abschläge) deducted on this invoice.
    ///
    /// Non-zero only for `InvoiceType::Final` with `ctx.abschlage` populated.
    pub abschlag_total_eur: Decimal,

    /// Amount actually due / refundable after Abschlag deduction (§41 EnWG).
    ///
    /// `zahlbetrag_eur = brutto_eur - abschlag_total_eur`
    ///
    /// - Positive → customer owes this balance
    /// - Negative → Lieferant refunds this amount to the customer
    pub zahlbetrag_eur: Decimal,

    /// Billing run identifier (from `BillingContext.billing_run_id`).
    ///
    /// `None` when the context did not specify a run ID (e.g. preview calls).
    /// Propagated to the Rechnung JSON as a `ZusatzAttribut` for audit trail.
    pub billing_run_id: Option<String>,
}

impl Invoice {
    /// Assemble an `Invoice` from a flat list of positions.
    ///
    /// Separates Tax and Abschlag positions from all others:
    /// - `netto_eur` = sum of non-Tax, non-Abschlag positions
    /// - `mwst_eur`  = sum of Tax positions
    /// - `brutto_eur` = netto + mwst
    /// - `abschlag_total_eur` = sum of Abschlag positions
    /// - `zahlbetrag_eur` = brutto - abschlag_total_eur
    #[must_use]
    pub fn from_positions(context: BillingContext, positions: Vec<BillingPosition>) -> Self {
        let netto_eur: Decimal = positions
            .iter()
            .filter(|p| {
                p.category != PositionCategory::Tax && p.category != PositionCategory::Abschlag
            })
            .map(|p| p.net_eur)
            .sum();
        let mwst_eur: Decimal = positions
            .iter()
            .filter(|p| p.category == PositionCategory::Tax)
            .map(|p| p.net_eur)
            .sum();
        let brutto_eur = netto_eur + mwst_eur;
        let abschlag_total_eur: Decimal = positions
            .iter()
            .filter(|p| p.category == PositionCategory::Abschlag)
            .map(|p| p.net_eur.abs())
            .sum();
        let zahlbetrag_eur = brutto_eur - abschlag_total_eur;
        let billing_run_id = context.billing_run_id.clone();
        Self {
            context,
            positions,
            netto_eur,
            mwst_eur,
            brutto_eur,
            abschlag_total_eur,
            zahlbetrag_eur,
            billing_run_id,
        }
    }

    /// Sum of `net_eur` for positions carrying the given tag.
    #[must_use]
    pub fn total_by_tag(&self, tag: &str) -> Decimal {
        BillingPosition::total_by_tag(&self.positions, tag)
    }

    /// Positions carrying the given tag.
    pub fn positions_by_tag<'a>(
        &'a self,
        tag: &'a str,
    ) -> impl Iterator<Item = &'a BillingPosition> {
        self.positions.iter().filter(move |p| p.has_tag(tag))
    }

    /// Validate the arithmetic invariants.
    ///
    /// Panics with a diagnostic if any invariant is violated (tolerance: 0.001 EUR).
    pub fn assert_valid(&self) {
        let expected = self.netto_eur + self.mwst_eur;
        let diff = (self.brutto_eur - expected).abs();
        assert!(
            diff < dec!(0.001),
            "Invoice invariant violated: netto {:.5} + mwst {:.5} = {:.5} != brutto {:.5}",
            self.netto_eur,
            self.mwst_eur,
            expected,
            self.brutto_eur
        );
        let zahlbetrag_expected = self.brutto_eur - self.abschlag_total_eur;
        let zdiff = (self.zahlbetrag_eur - zahlbetrag_expected).abs();
        assert!(
            zdiff < dec!(0.001),
            "Invoice invariant violated: zahlbetrag {:.5} != brutto {:.5} - abschlag {:.5}",
            self.zahlbetrag_eur,
            self.brutto_eur,
            self.abschlag_total_eur,
        );
    }

    /// §40a EnWG — all-inclusive Kilowattstundenpreis (ct/kWh) for display on invoice.
    ///
    /// §40a Abs. 1 EnWG requires that every electricity invoice shows the total
    /// all-inclusive price per kilowatt-hour (Gesamtbetrag je Kilowattstunde),
    /// inclusive of all energy charges, grid charges, levies, and taxes.
    ///
    /// Returns `None` when `total_kwh == 0` (avoid division by zero).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // 500 kWh total, brutto EUR 198.50 → 39.70 ct/kWh
    /// let ct = invoice.kilowattstundenpreis_brutto_ct(dec!(500)).unwrap();
    /// assert_eq!(ct.round_dp(2), dec!(39.70));
    /// ```
    #[must_use]
    pub fn kilowattstundenpreis_brutto_ct(&self, total_kwh: Decimal) -> Option<Decimal> {
        if total_kwh <= Decimal::ZERO {
            return None;
        }
        // brutto_eur / kWh × 100 → ct/kWh
        Some((self.brutto_eur / total_kwh * dec!(100)).round_dp(4))
    }

    /// Produce a BO4E-compatible `Rechnung` JSONB for `accountingd` ingestion.
    ///
    /// ## Rechnungsdatum
    ///
    /// Set to `period_to` (last day of the billing period). The library is pure
    /// and has no concept of "today". Callers that need a different issue date
    /// should mutate the returned JSON.
    ///
    /// ## Zahlungsziel
    ///
    /// `period_to + 14 days` — standard German energy retail practice.
    /// Override in the returned JSON for contract-specific payment terms.
    #[must_use]
    pub fn to_rechnung_json(&self) -> serde_json::Value {
        let ctx = &self.context;
        let pos_json: Vec<serde_json::Value> = self
            .positions
            .iter()
            .enumerate()
            .map(|(i, p)| {
                serde_json::json!({
                    "_typ": "RECHNUNGSPOSITION",
                    "positionsnummer": i + 1,
                    "positionstext": p.description,
                    "rechtlicheGrundlage": p.legal_basis,
                    "positionsMenge": {
                        "_typ": "MENGE",
                        "wert": p.quantity.to_string(),
                        "einheit": p.unit
                    },
                    "einzelpreis": {
                        "_typ": "PREIS",
                        "wert": p.unit_price_eur.to_string(),
                        "einheit": "EUR"
                    },
                    "gesamtpreis": {
                        "_typ": "BETRAG",
                        "wert": p.net_eur.to_string(),
                        "waehrung": "EUR"
                    },
                    "positionstyp": p.tags.first().map(String::as_str).unwrap_or("POSITION"),
                    "kategorie": format!("{:?}", p.category),
                })
            })
            .collect();

        let zahlungsziel = ctx.period_to + time::Duration::days(14);

        // Collect ZusatzAttribute from info positions tagged "gasqualitaet"
        let mut zusatz_attribute: Vec<serde_json::Value> = self
            .positions
            .iter()
            .filter(|p| p.has_tag("gasqualitaet") && p.category == PositionCategory::Info)
            .map(|p| {
                serde_json::json!({
                    "_typ": "ZUSATZ_ATTRIBUT",
                    "name": "gasqualitaet",
                    "wert": p.legal_basis.as_deref().unwrap_or("")
                })
            })
            .collect();

        // §41 Abs. 1 Nr. 8 + §42 EnWG — Energiemix (fuel/source mix on invoice)
        if let Some(mix) = &ctx.energiemix {
            zusatz_attribute.push(serde_json::json!({
                "_typ": "ZUSATZ_ATTRIBUT",
                "name": "energiemix",
                "wert": mix
            }));
        }

        // §41 EnWG Abs. 1 Nr. 3 — Verbrauchshistorie summary as ZusatzAttribut
        if let Some(vh) = &ctx.verbrauchshistorie {
            if let Some(vj) = vh.vorjahr_kwh {
                zusatz_attribute.push(serde_json::json!({
                    "_typ": "ZUSATZ_ATTRIBUT",
                    "name": "verbrauchVorjahr",
                    "wert": vj.to_string()
                }));
            }
            if let Some(avg) = vh.bundesdurchschnitt_kwh {
                zusatz_attribute.push(serde_json::json!({
                    "_typ": "ZUSATZ_ATTRIBUT",
                    "name": "verbrauchBundesdurchschnitt",
                    "wert": avg.to_string()
                }));
            }
        }

        // Audit trail: billing run ID for ERP reconciliation and duplicate detection.
        if let Some(run_id) = &self.billing_run_id {
            zusatz_attribute.push(serde_json::json!({
                "_typ": "ZUSATZ_ATTRIBUT",
                "name": "billingRunId",
                "wert": run_id
            }));
        }

        // §40a EnWG Abs. 1 — Kilowattstundenpreis (all-inclusive total price per kWh).
        // Compute from brutto_eur / billable kWh. Use total eligible kWh from positions.
        let total_kwh_positions: Decimal = self
            .positions
            .iter()
            .filter(|p| {
                p.category == PositionCategory::Commodity
                    && (p.has_tag("strom") || p.has_tag("arbeitspreis"))
                    && p.unit == "kWh"
                    && p.quantity > Decimal::ZERO
            })
            .map(|p| p.quantity)
            .sum();
        let kilowattstundenpreis_ct = if total_kwh_positions > Decimal::ZERO {
            self.kilowattstundenpreis_brutto_ct(total_kwh_positions)
        } else {
            None
        };

        serde_json::json!({
            "_typ": "RECHNUNG",
            "rechnungsnummer": ctx.rechnungsnummer,
            "rechnungsart": ctx.invoice_type.rechnungsart(),
            "rechnungsdatum": ctx.period_to.to_string(),  // deterministic: no now()
            "originalRechnungsId": ctx.invoice_type.original_invoice_id(),
            "marktlokationsId": ctx.malo_id,
            "zaehlerIdLieferstelle": ctx.zaehler_id,
            "herausgeber": {
                "_typ": "MARKTTEILNEHMER",
                "marktpartnercode": ctx.lf_mp_id
            },
            // §41 Abs. 1 Nr. 5 EnWG — Netzbetreiber identification (mandatory on energy invoices).
            // Identifies the network operator providing grid access at the delivery point.
            "netzbetreiber": ctx.nb_mp_id.as_deref().map(|id| serde_json::json!({
                "_typ": "MARKTTEILNEHMER",
                "marktpartnercode": id
            })),
            "vertragsId": ctx.contract_id,
            "rechnungsperiode": {
                "_typ": "ZEITRAUM",
                "startdatum": ctx.period_from.to_string(),
                "enddatum": ctx.period_to.to_string()
            },
            "rechnungspositionen": pos_json,
            "zusatzAttribute": if zusatz_attribute.is_empty() { serde_json::Value::Null } else { serde_json::json!(zusatz_attribute) },
            "gesamtnetto":  { "_typ": "BETRAG", "wert": self.netto_eur.to_string(),  "waehrung": "EUR" },
            "gesamtsteuer": { "_typ": "BETRAG", "wert": self.mwst_eur.to_string(),   "waehrung": "EUR" },
            "gesamtbrutto": { "_typ": "BETRAG", "wert": self.brutto_eur.to_string(), "waehrung": "EUR" },
            "abschlagTotal": if self.abschlag_total_eur > Decimal::ZERO { serde_json::json!({ "_typ": "BETRAG", "wert": self.abschlag_total_eur.to_string(), "waehrung": "EUR" }) } else { serde_json::Value::Null },
            "zahlbetrag": { "_typ": "BETRAG", "wert": self.zahlbetrag_eur.to_string(), "waehrung": "EUR" },
            // §40a EnWG Abs. 1 Satz 2 — Gesamtbetrag je Kilowattstunde (all-inclusive ct/kWh).
            // Only set when consumption positions exist (electricity commodity kWh known).
            "kilowattstundenpreisGesamt": kilowattstundenpreis_ct.map(|ct| serde_json::json!({
                "_typ": "PREIS",
                "wert": ct.to_string(),
                "einheit": "ct/kWh",
                "bezugswert": "KWH",
                "rechtlicheGrundlage": "§40a EnWG"
            })),
            // §40b EnWG — Strukturierte Preisvergleichsdaten für Vergleichsportale.
            // Enables price comparison portals (e.g. Verivox, Check24, BNetzA tools)
            // to ingest tariff structure from the invoice machine-readably.
            "preisvergleichsdaten": {
                "_typ": "PREISVERGLEICH",
                "grundpreisEurProJahr": self.positions.iter()
                    .filter(|p| p.has_tag("commodity") && p.unit == "Tage")
                    .map(|p| p.unit_price_eur * dec!(365))
                    .next()
                    .map(|eur_year| serde_json::json!({ "_typ": "BETRAG", "wert": eur_year.to_string(), "waehrung": "EUR" })),
                "arbeitspreisCtProKwh": self.positions.iter()
                    .filter(|p| (p.has_tag("strom") || p.has_tag("gas")) && p.category == crate::position::PositionCategory::Commodity && p.unit.starts_with("kWh"))
                    .map(|p| (p.unit_price_eur * dec!(100)).round_dp(4))
                    .next()
                    .map(|ct| ct.to_string()),
                "gesamtpreisCtProKwh": kilowattstundenpreis_ct.map(|ct| ct.to_string()),
                "rechtlicheGrundlage": "§40b EnWG"
            },
            "rechnungsempfaenger": {
                "_typ": "MARKTTEILNEHMER",
                "externeKundenId": ctx.malo_id
            },
            "zahlungsziel": zahlungsziel.to_string()
        })
    }

    /// Produce a typed BO4E `Rechnung` object.
    ///
    /// Requires the `bo4e` feature:
    /// ```toml
    /// energy-billing = { features = ["bo4e"] }
    /// ```
    ///
    /// The BO4E `Rechnung` struct is the canonical representation for:
    /// - ERP system ingestion
    /// - XRechnung/ZUGFeRD 3.x generation
    /// - BO4E schema validation
    ///
    /// ## Field mapping
    ///
    /// | `Invoice` | `rubo4e::Rechnung` |
    /// |---|---|
    /// | `billing_run_id` | `id` |
    /// | `context.rechnungsnummer` | `rechnungsnummer` |
    /// | `context.invoice_type` | `rechnungstyp` + `ist_storno` + `original_rechnungsnummer` |
    /// | `context.period_from/to` | `rechnungsperiode` |
    /// | `netto_eur` | `gesamtnetto.wert` |
    /// | `mwst_eur` | `gesamtsteuer.wert` |
    /// | `brutto_eur` | `gesamtbrutto.wert` |
    /// | `zahlbetrag_eur` | `zu_zahlen.wert` |
    /// | `context.lf_mp_id` | `rechnungsersteller.rollencodenummer` |
    /// | `context.nb_mp_id` | `netzbetreiber.rollencodenummer` |
    /// | `billing_run_id` | `zusatz_attribute["billingRunId"]` |
    /// Produce a typed BO4E `Rechnung` object from this invoice.
    ///
    /// Requires the `bo4e` feature: `energy-billing = { features = ["bo4e"] }`.
    ///
    /// The resulting `rubo4e::current::Rechnung` can be serialized to canonical BO4E
    /// JSON, used for XRechnung/ZUGFeRD generation, or validated against the BO4E schema.
    ///
    /// LF MP-ID and NB MP-ID are placed in `zusatz_attribute` for now (the proper
    /// BO4E mapping via `Geschaeftspartner.rollencodenummer` requires a full
    /// counterparty record not available here).
    #[cfg(feature = "bo4e")]
    #[must_use]
    pub fn to_bo4e_rechnung(&self) -> rubo4e::current::Rechnung {
        use rubo4e::current::{
            Betrag, Rechnung, Rechnungstyp, Waehrungscode, Zeitraum, ZusatzAttribut,
        };

        let ctx = &self.context;

        // Map InvoiceType → Rechnungstyp + storno flag + original reference
        let (rechnungstyp, ist_storno, original_rechnungsnummer) = match &ctx.invoice_type {
            crate::context::InvoiceType::Initial => {
                (Some(Rechnungstyp::Turnusrechnung), None, None)
            }
            crate::context::InvoiceType::AdvancePayment => {
                (Some(Rechnungstyp::Abschlagsrechnung), None, None)
            }
            crate::context::InvoiceType::Final => {
                (Some(Rechnungstyp::Abschlussrechnung), None, None)
            }
            crate::context::InvoiceType::PartialInvoice => {
                (Some(Rechnungstyp::Zwischenrechnung), None, None)
            }
            crate::context::InvoiceType::CreditNote => {
                (Some(Rechnungstyp::Turnusrechnung), Some(false), None)
            }
            crate::context::InvoiceType::Cancellation {
                original_invoice_id,
            } => (None, Some(true), Some(original_invoice_id.clone())),
            crate::context::InvoiceType::Correction {
                original_invoice_id,
                ..
            } => (
                Some(Rechnungstyp::Turnusrechnung),
                None,
                Some(original_invoice_id.clone()),
            ),
        };

        // Helper: EUR monetary amount
        let eur = |wert: Decimal| Betrag {
            id: None,
            typ: None,
            version: None,
            waehrung: Some(Waehrungscode::Eur),
            wert: Some(wert),
            zusatz_attribute: None,
            _additional: Default::default(),
        };

        // ZusatzAttribute carry identifiers and audit metadata
        let mut attrs: Vec<ZusatzAttribut> = vec![ZusatzAttribut {
            name: Some("lf_mp_id".to_owned()),
            wert: Some(serde_json::json!(ctx.lf_mp_id)),
            _additional: Default::default(),
        }];
        if let Some(nb) = &ctx.nb_mp_id {
            attrs.push(ZusatzAttribut {
                name: Some("nb_mp_id".to_owned()),
                wert: Some(serde_json::json!(nb)),
                _additional: Default::default(),
            });
        }
        if let Some(run_id) = &self.billing_run_id {
            attrs.push(ZusatzAttribut {
                name: Some("billingRunId".to_owned()),
                wert: Some(serde_json::json!(run_id)),
                _additional: Default::default(),
            });
        }
        if let Some(malo) = Some(&ctx.malo_id).filter(|s| !s.is_empty()) {
            attrs.push(ZusatzAttribut {
                name: Some("malo_id".to_owned()),
                wert: Some(serde_json::json!(malo)),
                _additional: Default::default(),
            });
        }

        Rechnung {
            id: self.billing_run_id.clone(),
            rechnungsnummer: Some(ctx.rechnungsnummer.clone()),
            rechnungstyp,
            ist_storno,
            original_rechnungsnummer,
            rechnungsperiode: Some(Zeitraum {
                startdatum: Some(ctx.period_from),
                enddatum: Some(ctx.period_to),
                ..Default::default()
            }),
            gesamtnetto: Some(eur(self.netto_eur)),
            gesamtsteuer: Some(eur(self.mwst_eur)),
            gesamtbrutto: Some(eur(self.brutto_eur)),
            zu_zahlen: Some(eur(self.zahlbetrag_eur)),
            faelligkeitsdatum: Some(ctx.period_to + time::Duration::days(14)),
            zusatz_attribute: Some(attrs),
            ..Default::default()
        }
    }

    /// Merge two invoices for adjacent billing periods (e.g. Tarifwechsel mid-period).
    ///
    /// Positions from `self` appear first, then `other`. Totals are re-summed.
    /// Tax layers are **not** re-applied — each invoice was already taxed independently
    /// for its sub-period.
    ///
    /// Uses the context from `self` (billing period, IDs) for the merged invoice.
    /// `other.context.period_to` is used to update the effective period end.
    ///
    /// ## Equivalent to `billing::merge_period_documents`
    ///
    /// This function applies the same logic as `billing::merge_period_documents` but
    /// operates directly on `Invoice` without requiring a `BillingDocument` conversion.
    ///
    /// ## Use case — Tarifwechsel (price change mid-period)
    ///
    /// ```rust,ignore
    /// // Old tariff: Jan 1–14
    /// let inv_old = old_engine.bill(ctx_jan1_14, &quantities_old)?;
    /// // New tariff: Jan 15–31
    /// let inv_new = new_engine.bill(ctx_jan15_31, &quantities_new)?;
    /// // Combined January invoice
    /// let merged = inv_old.merge(inv_new);
    /// ```
    #[must_use]
    pub fn merge(self, other: Invoice) -> Invoice {
        let mut ctx = self.context;
        // Extend period to cover both sub-periods
        if other.context.period_to > ctx.period_to {
            ctx.period_to = other.context.period_to;
        }
        let mut positions = self.positions;
        positions.extend(other.positions);
        Invoice::from_positions(ctx, positions)
    }

    /// Proportionally split this invoice across N recipients.
    ///
    /// Uses `billing::proportional_split` for **penny-correct** arithmetic:
    /// the sum of all recipient totals equals `self.brutto_eur` exactly.
    ///
    /// ## Use cases
    ///
    /// - B2B building: split a shared transformer fee by tenant floor area
    /// - Portfolio billing: allocate a shared network cost across sub-accounts
    /// - GGV cost sharing: divide a building's common-parts energy cost
    ///
    /// ## Arguments
    ///
    /// - `fractions`: allocation fractions per recipient. Do NOT need to sum to 1.0;
    ///   they are normalised internally by `billing::proportional_split`.
    /// - `contexts`: one `BillingContext` per recipient (must match `fractions.len()`).
    ///   Each recipient gets their own rechnungsnummer, malo_id, etc.
    ///
    /// ## Errors
    ///
    /// Returns `Err` when `fractions.len() != contexts.len()` or `fractions` is empty.
    pub fn allocate_proportionally(
        self,
        fractions: &[Decimal],
        contexts: Vec<crate::context::BillingContext>,
    ) -> Result<Vec<Invoice>, billing::BillingError> {
        if fractions.len() != contexts.len() || fractions.is_empty() {
            return Err(billing::BillingError::InvalidInput {
                reason: format!(
                    "fractions.len() ({}) must equal contexts.len() ({})",
                    fractions.len(),
                    contexts.len()
                ),
            });
        }

        let n = fractions.len();
        let mut recipient_positions: Vec<Vec<crate::position::BillingPosition>> =
            (0..n).map(|_| Vec::new()).collect();

        for pos in &self.positions {
            // Split this position's net_eur across recipients using penny-correct split.
            // billing::proportional_split requires non-negative total; handle sign separately.
            let (abs_eur, sign) = if pos.net_eur < Decimal::ZERO {
                (-pos.net_eur, -Decimal::ONE)
            } else {
                (pos.net_eur, Decimal::ONE)
            };
            let splits = billing::proportional_split(abs_eur, fractions, 5)?;
            for (i, split_abs) in splits.iter().enumerate() {
                let split_amount = sign * split_abs;
                // Adjust quantity proportionally where it makes sense.
                let split_qty = if pos.quantity.is_zero() || fractions.len() <= 1 {
                    pos.quantity
                } else {
                    let total_frac: Decimal = fractions.iter().sum();
                    if total_frac.is_zero() {
                        pos.quantity
                    } else {
                        (pos.quantity * fractions[i] / total_frac).round_dp(4)
                    }
                };
                let mut split_pos = pos.clone();
                split_pos.net_eur = split_amount;
                split_pos.quantity = split_qty;
                recipient_positions[i].push(split_pos);
            }
        }

        Ok(recipient_positions
            .into_iter()
            .zip(contexts)
            .map(|(positions, ctx)| Invoice::from_positions(ctx, positions))
            .collect())
    }
}

// ── Correction / Storno helpers ───────────────────────────────────────────────

/// Produce a Korrekturrechnung (correction invoice) JSON from a stored Rechnung JSON.
///
/// Used when the original `Invoice` object is not available (only the stored JSON).
/// Negates all monetary amounts and sets correction identity fields.
///
/// ## When to use
///
/// - `post_correction` handler: original invoice is loaded from `billing_records`,
///   only `rechnung_json` is available, not the original `Invoice` struct.
///
/// ## What this produces
///
/// - `rechnungsart` → `"KORREKTURRECHNUNG"` (or `"STORNORECHNUNG"` for full cancellations)
/// - `istOriginal` → `false`
/// - `originalRechnungsnummer` → the original invoice number
/// - All `wert` monetary fields → sign-negated
///
/// ## Moved from `handlers.rs`
///
/// Previously `negate_rechnung_json()` in `billingd/src/handlers.rs`. Moved here
/// so the library owns all sign-negation logic for invoices.
pub fn negate_rechnung_json_for_correction(
    original: &serde_json::Value,
    original_rechnungsnummer: &str,
    new_rechnungsnummer: &str,
) -> serde_json::Value {
    let mut corrected = original.clone();
    if let Some(obj) = corrected.as_object_mut() {
        obj.insert("istOriginal".to_owned(), serde_json::json!(false));
        obj.insert(
            "originalRechnungsnummer".to_owned(),
            serde_json::json!(original_rechnungsnummer),
        );
        obj.insert(
            "rechnungsnummer".to_owned(),
            serde_json::json!(new_rechnungsnummer),
        );
        obj.insert(
            "rechnungsart".to_owned(),
            serde_json::json!("KORREKTURRECHNUNG"),
        );

        negate_betrag_in_obj(obj, "gesamtbrutto");
        negate_betrag_in_obj(obj, "gesamtnetto");
        negate_betrag_in_obj(obj, "gesamtsteuer");
        negate_betrag_in_obj(obj, "abschlagTotal");
        negate_betrag_in_obj(obj, "zahlbetrag");

        if let Some(serde_json::Value::Array(positionen)) = obj.get_mut("rechnungspositionen") {
            for pos in positionen.iter_mut() {
                if let Some(pos_obj) = pos.as_object_mut() {
                    negate_betrag_in_obj(pos_obj, "gesamtpreis");
                    if let Some(serde_json::Value::Object(ep)) = pos_obj.get_mut("einzelpreis") {
                        negate_wert_field(ep);
                    }
                }
            }
        }
    }
    corrected
}

fn negate_betrag_in_obj(obj: &mut serde_json::Map<String, serde_json::Value>, key: &str) {
    if let Some(serde_json::Value::Object(betrag)) = obj.get_mut(key) {
        negate_wert_field(betrag);
    }
}

fn negate_wert_field(obj: &mut serde_json::Map<String, serde_json::Value>) {
    if let Some(v) = obj.get("wert") {
        let negated = match v {
            serde_json::Value::String(s) => s
                .parse::<Decimal>()
                .ok()
                .map(|d| serde_json::json!((-d).to_string())),
            serde_json::Value::Number(n) => n.as_f64().map(|f| serde_json::json!(-f)),
            _ => None,
        };
        if let Some(neg) = negated {
            obj.insert("wert".to_owned(), neg);
        }
    }
}