energy-billing 0.20.0

Pure multi-product retail utility billing for German markets — Strom, Gas, Wärme, Wasser and the § 14a tariffs. Zero I/O, 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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//! Typed product definitions for the German retail energy market.
//!
//! The [`Product`] enum is the primary entry point. It deserializes directly from
//! `productd` product JSONB using the `"category"` discriminator field and provides
//! a [`Product::build_engine`] method to construct the matching `BillingEngine`.
//!
//! ## Architecture
//!
//! One typed struct per product category, each carrying only the fields its
//! category has. A flat input with every category's optional fields on it
//! cannot distinguish "not applicable" from "not supplied".
//!
//! ```text
//! Product::Strom(ElectricityProduct)           → ElectricityProvider / DynamicElectricityProvider
//! Product::Waermepumpe(ControllableLoadProduct) → ControllableLoadProvider (§14a)
//! Product::Wallbox(ControllableLoadProduct)     → ControllableLoadProvider (§14a)
//! Product::Gas(GasProduct)                      → GasProvider
//! Product::Waerme(HeatProduct)                  → HeatProvider
//! Product::Wasser(WaterProduct)                 → WaterProvider (Trinkwasser + Abwasser)
//! Product::Solar(SolarProduct)                  → SolarProvider
//! Product::Eeg(EegProduct)                      → EegProvider
//! Product::Einspeisung(EinspeisungProduct)       → EinspeisungProvider
//! Product::Hems(HemsProduct)                    → HemsProvider
//! Product::Emobility(EmobilityProduct)           → EmobilityProvider
//! Product::Energiedienstleistung(ServiceProduct) → ServiceProvider
//! Product::Sharing(SharingProduct)               → ElectricityProvider + EnergyShareProvider
//! ```
//!
//! ## Deserializing from `productd` JSONB
//!
//! ```rust
//! use energy_billing::Product;
//!
//! let json = r##"{"category":"STROM","arbeitspreis_ct_per_kwh":"28.5"}"##;
//! let product: Product = serde_json::from_str(json).unwrap();
//! assert!(matches!(product, Product::Strom(_)));
//! ```

use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};

// ── ISO date serde helper ─────────────────────────────────────────────────────

mod date_option_serde {
    use serde::{Deserialize, Deserializer, Serializer};
    use time::Date;
    use time::macros::format_description;

    const FORMAT: &[time::format_description::FormatItem<'static>] =
        format_description!("[year]-[month]-[day]");

    pub fn serialize<S: Serializer>(date: &Option<Date>, s: S) -> Result<S::Ok, S::Error> {
        match date {
            Some(d) => s.serialize_some(&d.format(FORMAT).map_err(serde::ser::Error::custom)?),
            None => s.serialize_none(),
        }
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Date>, D::Error> {
        let opt: Option<String> = Option::deserialize(d)?;
        match opt {
            None => Ok(None),
            Some(s) => Date::parse(&s, FORMAT)
                .map(Some)
                .map_err(serde::de::Error::custom),
        }
    }
}

// ── EnergieQuellen ────────────────────────────────────────────────────────────

/// §42 EnWG Abs. 2 Nr. 2 — typed energy source mix for invoice disclosure.
///
/// Replaces the legacy free-text energiemix string with structured data for
/// CO₂ label generation, HKN traceability, and BO4E Energiemix generation.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct EnergieQuellen {
    #[serde(default)]
    pub erneuerbar_pct: Decimal,
    #[serde(default)]
    pub nuclear_pct: Option<Decimal>,
    #[serde(default)]
    pub fossil_pct: Option<Decimal>,
    /// Specific CO₂ emissions g/kWh — mandatory on electricity invoices (§42 Abs. 2 Nr. 2 EnWG).
    pub co2_g_per_kwh: Decimal,
    #[serde(default)]
    pub hkn_certified: bool,
    #[serde(default)]
    pub hkn_country: Option<String>,
    #[serde(default)]
    pub beschreibung: Option<String>,
}

// ── SeasonalPriceOverride ─────────────────────────────────────────────────────

/// One seasonal price band (Saisontarif). Months wrap: from_month=10, to_month=3 → Oct–Mar.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SeasonalPriceOverride {
    pub from_month: u8,
    pub to_month: u8,
    #[serde(default)]
    pub arbeitspreis_ct_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub gas_arbeitspreis_ct_per_kwh_hs: Option<Decimal>,
    #[serde(default)]
    pub label: Option<String>,
}

impl SeasonalPriceOverride {
    #[must_use]
    pub fn contains_month(&self, month: u8) -> bool {
        if self.from_month <= self.to_month {
            month >= self.from_month && month <= self.to_month
        } else {
            month >= self.from_month || month <= self.to_month
        }
    }
}

// ── BlockTierInput ────────────────────────────────────────────────────────────

/// One tier in a block/graduated tariff (Blocktarif / Staffelpreis).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BlockTierInput {
    /// Upper bound (kWh). None = open-ended last tier.
    pub bis_kwh: Option<Decimal>,
    pub preis_ct_per_kwh: Decimal,
}

// ── IndexedPriceConfig ────────────────────────────────────────────────────────

/// Indexed price for B2B contracts (§41 EnWG Sonderkundenvertrag).
///
/// Effective = base_ct + spread_ct + (index_value × factor_ct_per_unit).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct IndexedPriceConfig {
    pub base_ct_per_kwh: Decimal,
    pub spread_ct_per_kwh: Decimal,
    pub index_name: String,
    pub index_value: Option<Decimal>,
    pub factor_ct_per_unit: Decimal,
}

impl IndexedPriceConfig {
    #[must_use]
    pub fn effective_ct_per_kwh(&self) -> Option<Decimal> {
        let idx = self.index_value?;
        Some(self.base_ct_per_kwh + self.spread_ct_per_kwh + idx * self.factor_ct_per_unit)
    }

    #[must_use]
    pub fn position_description(&self) -> String {
        match self.index_value {
            Some(v) => format!(
                "Arbeitspreis {} ({:.4} + {:.4} + {:.4}\u{d7}{:.4}\u{202f}ct/kWh)",
                self.index_name,
                self.base_ct_per_kwh,
                self.spread_ct_per_kwh,
                self.factor_ct_per_unit,
                v,
            ),
            None => format!(
                "Arbeitspreis {} (Indexwert nicht verf\u{fc}gbar)",
                self.index_name
            ),
        }
    }
}

/// The § 9 Abs. 1 Nr. 3 StromStG Kleinanlage-Befreiung — the default treatment
/// of a rooftop solar supply.
fn solar_stromsteuer_default() -> crate::steuer::StromsteuerTarif {
    crate::steuer::StromsteuerTarif::Befreiung {
        grund: crate::steuer::StromsteuerBefreiung::Kleinanlage,
    }
}

// ── Per-category product structs ──────────────────────────────────────────────

/// STROM electricity product.
///
/// Used by `ElectricityProvider` (static) and `DynamicElectricityProvider`
/// (§41a, when `dynamic_epex = true`). Also the base for `ControllableLoadProduct`
/// and `SharingProduct` via `#[serde(flatten)]`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ElectricityProduct {
    #[serde(default)]
    pub product_code: Option<String>,
    #[serde(default)]
    pub grundpreis_ct_per_day: Option<Decimal>,
    #[serde(default)]
    pub arbeitspreis_ct_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub arbeitspreis_ht_ct_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub arbeitspreis_nt_ct_per_kwh: Option<Decimal>,
    /// Tariff register annotation (e.g. "Eintarif", "Zweitarif").
    #[serde(default)]
    pub register_count: Option<serde_json::Value>,
    /// RLM demand charge (ct/kW/month). §41 EnWG large commercial.
    #[serde(default)]
    pub leistungspreis_strom_ct_per_kw_month: Option<Decimal>,
    /// Block/graduated tariff tiers. Overrides arbeitspreis_ct_per_kwh when set.
    #[serde(default)]
    pub block_tiers: Option<Vec<BlockTierInput>>,
    /// B2B indexed price (Phelix Base, EEX etc.) — §41 EnWG Sonderkundenvertrag.
    #[serde(default)]
    pub indexed_price: Option<IndexedPriceConfig>,
    #[serde(default)]
    pub seasonal_prices: Option<Vec<SeasonalPriceOverride>>,
    /// true → §41a EPEX Spot per-interval billing. Requires iMSys (§41a Abs. 1 EnWG).
    #[serde(default)]
    pub dynamic_epex: bool,
    /// Price floor for §41a (ct/kWh). None = full market exposure.
    #[serde(default)]
    pub dynamic_epex_floor_ct_kwh: Option<Decimal>,
    /// Price ceiling for §41a (ct/kWh) — a contractual consumer-protection cap on
    /// the spot component. None = uncapped. Applied after the floor, so a plant
    /// with both bills the spot price clamped into `[floor, cap]`.
    #[serde(default)]
    pub dynamic_epex_cap_ct_kwh: Option<Decimal>,
    /// § 41a Arbeitspreis-Aufschlag (ct/kWh) — the supplier's margin on top of
    /// the clamped spot price. Distinct from `auf_abschlag_ct_per_kwh`, which
    /// is the static path's Rabatt/Aufschlag line.
    #[serde(default)]
    pub dynamic_aufschlag_ct_per_kwh: Option<Decimal>,
    /// Label of the price series the § 41a Arbeitspreis is formed from, as
    /// stated on the invoice — `productd`'s `dyn_source` column
    /// (e.g. `"EPEX Spot Day-Ahead"`). Defaults to EPEX day-ahead.
    #[serde(default)]
    pub dynamic_price_source: Option<String>,
    #[serde(default)]
    pub auf_abschlag_ct_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub auf_abschlag_eur_per_month: Option<Decimal>,
    /// One-time Neukunden-/Sofortbonus (EUR, gross of the customer's credit).
    /// Credited on the invoice whose product carries it (usually the first or the
    /// Jahresabrechnung) as a Preisnachlass (§17 UStG Entgeltminderung).
    #[serde(default)]
    pub sofortbonus_eur: Option<Decimal>,
    /// Annual Treuebonus (EUR/year), pro-rated to the billed days and credited as
    /// a Preisnachlass (§17 UStG Entgeltminderung).
    #[serde(default)]
    pub treuebonus_eur_per_year: Option<Decimal>,
    /// MSB Grundgebühr bundled on retail invoice (ct/day). §41 EnWG.
    #[serde(default)]
    pub msb_gebuehr_ct_per_day: Option<Decimal>,
    /// How the Stromsteuer applies: Regelsatz, § 9 Abs. 1 Steuerbefreiung, or
    /// § 9 Abs. 2/3 ermäßigter Satz. See [`crate::steuer`] — a
    /// **Steuerentlastung** (§ 9a/§ 9b/§ 9c StromStG) is not one of these and
    /// belongs in `steuerentlastungen`.
    #[serde(default)]
    pub stromsteuer_tarif: crate::steuer::StromsteuerTarif,
    /// Reliefs the *customer* may claim afterwards at the Hauptzollamt. They do
    /// not change a single amount on this invoice; each renders one
    /// informational note so the customer knows what it carried.
    #[serde(default)]
    pub steuerentlastungen: Vec<crate::steuer::Steuerentlastung>,
    #[serde(default)]
    pub mwst_rate_override: Option<Decimal>,
    #[serde(default)]
    pub stromsteuer_ct_per_kwh_override: Option<Decimal>,
    /// Price guarantee end date — invoice display only (§41 Abs. 1 Nr. 4 EnWG).
    #[serde(default, with = "date_option_serde")]
    pub preisgarantie_bis: Option<time::Date>,
    #[serde(default)]
    pub minimum_invoice_eur_brutto: Option<Decimal>,
    /// Plant capacity (kWp) — informational (prosumer plant size / MaStR). Does
    /// not affect the consumption VAT rate: a retail supply is standard-rated
    /// even where the customer runs their own PV (§12 Abs. 3 UStG covers the PV
    /// system supply, not the electricity).
    #[serde(default)]
    pub anlage_kwp: Option<Decimal>,
    /// §42 EnWG typed energy source mix (CO₂ label).
    #[serde(default)]
    pub energiequellen: Option<EnergieQuellen>,
    /// EEG Gutschrift EUR pass-through — set at bill-time from einsd, not stored in productd.
    #[serde(default)]
    pub eeg_gutschrift_eur: Option<Decimal>,
    /// The feed-in operator has elected the Kleinunternehmerregelung (§19 UStG)
    /// → the `eeg_gutschrift_eur` credit carries 0 % USt.
    ///
    /// The feed-in is a **separate supply** from the consumption billed here and
    /// is governed by the operator's own USt status (`einspeiser.ust_status`).
    /// Without this, the credit nets against the standard-rate base and
    /// understates the supplier's output VAT on the consumption supply by 19 %
    /// of the credit. Does not affect the consumption positions.
    #[serde(default)]
    pub eeg_gutschrift_kleinunternehmer_19_ustg: bool,
}

/// §14a EnWG controllable load — WAERMEPUMPE / WALLBOX.
///
/// Extends `ElectricityProduct` (via `#[serde(flatten)]`) with §14a Steuerungsrabatt
/// fields. `ControllableLoadProvider` delegates standard electricity billing to
/// `ElectricityProvider` then appends the §14a credit positions.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ControllableLoadProduct {
    #[serde(flatten)]
    pub base: ElectricityProduct,
    /// §14a **Modul 2** — prozentuale Reduzierung des NNE-Arbeitspreises,
    /// carried here as the resulting per-kWh credit (ct/kWh).
    ///
    /// The reduction attaches to the controllable device's own metered energy,
    /// which is why Modul 2 requires separate metering. It is the **alternative
    /// form of the base module**, so it excludes Modul 1
    /// (`MODUL1_AND_MODUL2`), and it takes no Modul 3
    /// (`MODUL2_AND_MODUL3`) — each pairing would reduce the same network usage
    /// twice.
    #[serde(default)]
    pub sect14a_modul2_nne_reduktion_ct_per_kwh: Option<Decimal>,

    /// §14a **Modul 3** — zeitvariables Netzentgelt (BK8-22/010-A), from 01.04.2025.
    ///
    /// Three Tarifstufen, not two: Hochtarif, Standardtarif and Niedertarif,
    /// each a NNE rate in ct/kWh published by the Netzbetreiber. All three must
    /// be set together; the matching band energies arrive on
    /// [`crate::Sect14aModul3Verbrauch`]. When Modul 3 is billed, the flat NNE
    /// Arbeitspreis from `GridInput` must be left unset — the bands *replace*
    /// it, and setting both raises `MODUL3_AND_FLAT_NNE`.
    #[serde(default)]
    pub sect14a_modul3_nne_ht_ct_per_kwh: Option<Decimal>,
    /// §14a Modul 3 Standardtarif rate. See `sect14a_modul3_nne_ht_ct_per_kwh`.
    #[serde(default)]
    pub sect14a_modul3_nne_st_ct_per_kwh: Option<Decimal>,
    /// §14a Modul 3 Niedertarif rate. See `sect14a_modul3_nne_ht_ct_per_kwh`.
    #[serde(default)]
    pub sect14a_modul3_nne_nt_ct_per_kwh: Option<Decimal>,
    /// §14a Steuerungsentschädigung per kWh of dimmed energy (ct/kWh).
    ///
    /// Compensation for an actual Steuerungseingriff — **not** one of the three
    /// BK8-22/010-A modules, which are all rate reductions rather than payments
    /// for a dispatch that happened.
    #[serde(default)]
    pub sect14a_steuerungsentschaedigung_ct_per_kwh: Option<Decimal>,
    /// §14a **Modul 1** — pauschale Reduzierung des Netzentgelts, published by
    /// the Netzbetreiber as a flat annual amount (EUR/year).
    ///
    /// BK8-22/010-A fixes it nationwide as `80 EUR + 3 750 kWh × Arbeitspreis im
    /// Standardtarif × 0,2`, which lands between 110 and 190 EUR/year depending
    /// on the Netzbetreiber. There is no per-kW component: the reduction is the
    /// same whatever the steuerbare Leistung, which is precisely why it needs
    /// no additional metering and is the default where the connection holder
    /// makes no choice. It **may be combined with Modul 3**.
    #[serde(default)]
    pub sect14a_modul1_pauschale_eur_per_year: Option<Decimal>,
    /// §14a Steuerungsentschädigung as an annual capacity rate (EUR/kW/year),
    /// pro-rated by the hours actually dimmed. Not a BK8-22/010-A module.
    #[serde(default)]
    pub sect14a_steuerungsentschaedigung_eur_per_kw_year: Option<Decimal>,
}

/// Natural gas supply product — GAS (SLP / RLM / B2B indexed).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct GasProduct {
    #[serde(default)]
    pub product_code: Option<String>,
    #[serde(default)]
    pub gas_grundpreis_ct_per_day: Option<Decimal>,
    #[serde(default)]
    pub gas_arbeitspreis_ct_per_kwh_hs: Option<Decimal>,
    /// RLM demand charge (ct/kW/month) for large gas customers. §41 EnWG.
    #[serde(default)]
    pub gas_leistungspreis_ct_per_kw_month: Option<Decimal>,
    /// B2B indexed gas price (TTF, NCG, GASPOOL) — §41 EnWG Sonderkundenvertrag.
    #[serde(default)]
    pub gas_indexed_price: Option<IndexedPriceConfig>,
    #[serde(default)]
    pub seasonal_prices: Option<Vec<SeasonalPriceOverride>>,
    /// How the Energiesteuer applies: Regelsatz, or steuerfreie Verwendung
    /// against an Erlaubnis nach § 24 Abs. 2 EnergieStG. See [`crate::steuer`].
    ///
    /// §§ 53a and 54 EnergieStG are **Steuerentlastungen** the customer claims
    /// afterwards, not exemptions at supply — they belong in
    /// `steuerentlastungen`.
    #[serde(default)]
    pub energiesteuer_tarif: crate::steuer::EnergiesteuerTarif,
    /// Reliefs the *customer* may claim afterwards at the Hauptzollamt. Render
    /// as notes; they change no amount on this invoice.
    #[serde(default)]
    pub steuerentlastungen: Vec<crate::steuer::Steuerentlastung>,
    #[serde(default)]
    pub auf_abschlag_ct_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub auf_abschlag_eur_per_month: Option<Decimal>,
    #[serde(default)]
    pub mwst_rate_override: Option<Decimal>,
    #[serde(default)]
    pub energiesteuer_gas_ct_per_kwh_override: Option<Decimal>,
    #[serde(default)]
    pub behg_gas_ct_per_kwh_override: Option<Decimal>,
    #[serde(default, with = "date_option_serde")]
    pub preisgarantie_bis: Option<time::Date>,
    #[serde(default)]
    pub minimum_invoice_eur_brutto: Option<Decimal>,
}

/// District heating / Fernwärme product — WAERME.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HeatProduct {
    #[serde(default)]
    pub product_code: Option<String>,
    #[serde(default)]
    pub waerme_grundpreis_eur_per_month: Option<Decimal>,
    /// Annual capacity charge (EUR/kW/year). Pro-rated per billing period.
    #[serde(default)]
    pub waerme_leistungspreis_eur_per_kw_year: Option<Decimal>,
    /// Monthly capacity charge alternative (EUR/kW/month).
    #[serde(default)]
    pub waerme_leistungspreis_eur_per_kw_month: Option<Decimal>,
    #[serde(default)]
    pub waerme_arbeitspreis_ct_per_kwh: Option<Decimal>,
    /// AVBFernwärmeV §24 Abs. 4 Preisänderungsklausel — the Arbeitspreis is
    /// index-linked (fuel/wage/market indices). When set it resolves the effective
    /// Arbeitspreis and takes precedence over the static `waerme_arbeitspreis_ct_per_kwh`.
    #[serde(default)]
    pub waerme_indexed_price: Option<IndexedPriceConfig>,
    /// Wärmeplanungsgesetz §14 renewable share (0.0–1.0). Mandatory disclosure.
    ///
    /// Disclosure only — it does **not** change the VAT rate. District heating is
    /// standard-rated (19 %); the 7 % on gas/Fernwärme was the temporary §28 Abs. 5/6
    /// UStG crisis measure (01.10.2022–31.03.2024), resolved period-aware by
    /// [`crate::rates::mwst_rate_for_gas_waerme_period`], not by renewable share.
    #[serde(default)]
    pub waerme_erneuerbar_anteil_pct: Option<Decimal>,
    /// CO₂ cost passed through on the heat supply, in ct/kWh_th.
    ///
    /// **CO2KostAufG § 3** obliges the supplier to state the CO₂ cost it
    /// actually bore on a Wärmelieferung, and § 5 makes that statement part of
    /// the Abrechnung. The rate is *not* the gas BEHG rate: the heat generator's
    /// fuel mix and conversion losses sit between the two, so it is a property
    /// of the heat product and the operator states it.
    ///
    /// `None` leaves the position off. `Some(0)` is how a fully renewable
    /// network says it bears none, and still prints the § 5 statement.
    #[serde(default)]
    pub waerme_co2_kosten_ct_per_kwh: Option<Decimal>,
    /// Specific CO₂ emissions of the delivered heat in g/kWh — the
    /// CO2KostAufG § 3 Abs. 2 figure the cost statement is derived from.
    /// Disclosure only.
    #[serde(default)]
    pub waerme_co2_emission_g_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub mwst_rate_override: Option<Decimal>,
    #[serde(default)]
    pub minimum_invoice_eur_brutto: Option<Decimal>,
}

/// Legal regime of the Abwasser charge — decides the USt treatment.
///
/// Over 90 % of German municipalities levy wastewater as a public-law fee
/// (Gebühr per KAG-Satzung), which is a hoheitliche Leistung outside the
/// scope of USt. Privatised operators charge a privatrechtliches Entgelt at
/// the 19 % Regelsteuersatz instead.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AbwasserRegime {
    /// Öffentlich-rechtliche Gebühr (KAG-Satzung) — no USt.
    #[default]
    PublicLawFee,
    /// Privatrechtliches Entgelt — 19 % USt.
    PrivateLawCharge,
}

/// Municipal drinking-water / wastewater product — WASSER.
///
/// Water is not a MaKo commodity — there is no market-communication regime,
/// no EDIFACT, no BNetzA. The category exists for multi-utility (Stadtwerke)
/// deployments that bill water alongside energy on the same platform:
///
/// - **Trinkwasser** (AVBWasserV / municipal statute): Grundpreis +
///   Mengenpreis, always at the ermäßigter USt-Satz of 7 %
///   (§12 Abs. 2 Nr. 1 UStG, Anlage 2 Nr. 34 — water is a foodstuff).
/// - **Abwasser** (gesplittete Abwassergebühr, mandated by case law —
///   VGH Baden-Württemberg, 11.03.2010): Schmutzwasser per m³ on the
///   Frischwassermaßstab minus metered Absetzungen, plus
///   Niederschlagswasser per m² of sealed surface per year.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WaterProduct {
    #[serde(default)]
    pub product_code: Option<String>,
    /// Trinkwasser Grundpreis (Systempreis, typically by meter size) in EUR/month.
    #[serde(default)]
    pub wasser_grundpreis_eur_per_month: Option<Decimal>,
    /// Trinkwasser Mengenpreis in EUR/m³ (7 % USt).
    #[serde(default)]
    pub wasser_mengenpreis_eur_per_m3: Option<Decimal>,
    /// Schmutzwassergebühr in EUR/m³ (Frischwassermaßstab minus Absetzungen).
    #[serde(default)]
    pub schmutzwasser_eur_per_m3: Option<Decimal>,
    /// Niederschlagswassergebühr in EUR per m² sealed surface per **year**.
    #[serde(default)]
    pub niederschlagswasser_eur_per_m2_year: Option<Decimal>,
    /// USt treatment of the Abwasser positions. Trinkwasser is always 7 %.
    #[serde(default)]
    pub abwasser_regime: AbwasserRegime,
    /// Override for the Trinkwasser USt rate (edge cases only).
    #[serde(default)]
    pub mwst_rate_override: Option<Decimal>,
}

/// Solar PV / Eigenverbrauch / §42b EnWG GGV / §21 Abs. 3 EEG Mieterstrom product — SOLAR.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SolarProduct {
    #[serde(default)]
    pub product_code: Option<String>,
    #[serde(default)]
    pub solar_arbeitspreis_ct_per_kwh: Option<Decimal>,
    /// Grid remainder rate for §42b EnWG GGV hybrid billing (ct/kWh).
    ///
    /// In GGV (Gemeinschaftliche Gebäudeversorgung) billing, some consumption
    /// comes from the building's PV plant (charged at `solar_arbeitspreis_ct_per_kwh`)
    /// and the remainder comes from the grid (charged at this rate).
    ///
    /// When not set, `solar_arbeitspreis_ct_per_kwh` is used as fallback.
    #[serde(default)]
    pub arbeitspreis_ct_per_kwh: Option<Decimal>,
    /// § 42a Abs. 4 EnWG — the Grundversorgungs-Arbeitspreis (ct/kWh) the
    /// Mieterstrompreis is capped against.
    ///
    /// A Mieterstromvertrag may charge at most **90 %** of the ortsüblichen
    /// Grundversorgungstarifs. Set this and the provider refuses a
    /// `solar_arbeitspreis_ct_per_kwh` above the cap.
    ///
    /// The **Mieterstromzuschlag (§ 21 Abs. 3 EEG 2023)** deliberately has no
    /// field here: it is the *Anlagenbetreiber's* claim against the
    /// *Netzbetreiber*, settled by `eeg-billing`'s `TenantElectricity` scheme,
    /// not a surcharge on the tenant.
    #[serde(default)]
    pub grundversorgung_arbeitspreis_ct_per_kwh: Option<Decimal>,
    /// §42b EnWG GGV community energy discount (ct/kWh).
    #[serde(default)]
    pub gemeinschaft_rabatt_ct_per_kwh: Option<Decimal>,
    /// How the Stromsteuer applies to the solar supply.
    ///
    /// Defaults to the **§ 9 Abs. 1 Nr. 3 StromStG** Kleinanlage-Befreiung,
    /// which is what a rooftop Mieterstrom or GGV supply is: an installation up
    /// to 2 MW, delivered by its operator to Letztverbraucher drawing *im
    /// räumlichen Zusammenhang* (lit. b) or self-consumed (lit. a). The invoice
    /// states the ground rather than merely omitting the levy — § 9 Abs. 4
    /// conditions the exemption on the customer's Erlaubnis.
    ///
    /// Set `{"art": "REGEL"}` where the supply does not qualify: an installation
    /// over 2 MW, or delivery beyond the räumlicher Zusammenhang.
    #[serde(default = "solar_stromsteuer_default")]
    pub stromsteuer_tarif: crate::steuer::StromsteuerTarif,
    /// Plant capacity (kWp) — informational (MaStR / §48 EEG size class).
    #[serde(default)]
    pub anlage_kwp: Option<Decimal>,
    /// Operator has elected the Kleinunternehmerregelung (§19 UStG) → the feed-in
    /// Gutschrift carries 0 % USt. An election, not a function of plant size.
    #[serde(default)]
    pub kleinunternehmer_19_ustg: bool,
    #[serde(default)]
    pub mwst_rate_override: Option<Decimal>,
    #[serde(default)]
    pub minimum_invoice_eur_brutto: Option<Decimal>,
}

/// EEG feed-in Gutschrift — LF pays generator. Category: EEG.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct EegProduct {
    #[serde(default)]
    pub product_code: Option<String>,
    #[serde(default)]
    pub eeg_verguetungssatz_ct_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub eeg_marktpraemie_ct_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub eeg_managementpraemie_ct_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub kwkg_zuschlag_ct_per_kwh: Option<Decimal>,
    /// Plant capacity (kWp) — informational (MaStR / §48 EEG size class).
    #[serde(default)]
    pub anlage_kwp: Option<Decimal>,
    /// Operator has elected the Kleinunternehmerregelung (§19 UStG) → 0 % USt on
    /// the feed-in Gutschrift. An election, not a function of plant size.
    #[serde(default)]
    pub kleinunternehmer_19_ustg: bool,
    #[serde(default)]
    pub mwst_rate_override: Option<Decimal>,
}

/// Direktvermarktung feed-in — LF as market premium payer. Category: EINSPEISUNG.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct EinspeisungProduct {
    #[serde(default)]
    pub product_code: Option<String>,
    #[serde(default)]
    pub marktwert_ct_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub vermarktungsgebuehr_ct_per_kwh: Option<Decimal>,
    /// Operator has elected the Kleinunternehmerregelung (§19 UStG) → 0 % USt on
    /// the feed-in Gutschrift. An election, not a function of plant size.
    #[serde(default)]
    pub kleinunternehmer_19_ustg: bool,
    #[serde(default)]
    pub mwst_rate_override: Option<Decimal>,
}

/// Home Energy Management System subscription. Category: HEMS.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HemsProduct {
    #[serde(default)]
    pub product_code: Option<String>,
    #[serde(default)]
    pub hems_subscription_eur_per_month: Option<Decimal>,
    #[serde(default)]
    pub hems_optimization_event_eur: Option<Decimal>,
    #[serde(default)]
    pub hems_readout_event_eur: Option<Decimal>,
    #[serde(default)]
    pub mwst_rate_override: Option<Decimal>,
}

/// EV charging CPO/EMSP. Category: EMOBILITY.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct EmobilityProduct {
    #[serde(default)]
    pub product_code: Option<String>,
    #[serde(default)]
    pub emobility_service_fee_eur: Option<Decimal>,
    #[serde(default)]
    pub emobility_kwh_price_ct: Option<Decimal>,
    #[serde(default)]
    pub emobility_session_fee_eur: Option<Decimal>,
    #[serde(default)]
    pub emobility_roaming_fee_eur: Option<Decimal>,
    #[serde(default)]
    pub mwst_rate_override: Option<Decimal>,
}

/// Energy services subscription. Category: ENERGIEDIENSTLEISTUNG.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ServiceProduct {
    #[serde(default)]
    pub product_code: Option<String>,
    #[serde(default)]
    pub service_fee_eur: Option<Decimal>,
    #[serde(default)]
    pub service_event_price_eur: Option<Decimal>,
    #[serde(default)]
    pub mwst_rate_override: Option<Decimal>,
}

/// §42c EnWG community energy sharing. Category: SHARING.
///
/// Bills the full grid consumption via `ElectricityProvider` (base), then
/// credits the allocated community generation via `EnergyShareProvider`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SharingProduct {
    #[serde(flatten)]
    pub electricity: ElectricityProduct,
    /// Community sharing credit rate (ct/kWh) applied to allocated community kWh.
    #[serde(default)]
    pub sharing_credit_ct_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub sharing_description: Option<String>,
}

// ── Product enum ──────────────────────────────────────────────────────────────

/// Typed product dispatch enum — primary entry point for `energy-billing`.
///
/// Deserializes from `productd` JSONB via the `"category"` field.
///
/// ```rust
/// use energy_billing::Product;
/// let json = r##"{"category":"STROM","arbeitspreis_ct_per_kwh":"28.5"}"##;
/// let p: Product = serde_json::from_str(json).unwrap();
/// assert!(matches!(p, Product::Strom(_)));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "category")]
pub enum Product {
    #[serde(rename = "STROM")]
    Strom(ElectricityProduct),
    #[serde(rename = "WAERMEPUMPE")]
    Waermepumpe(ControllableLoadProduct),
    #[serde(rename = "WALLBOX")]
    Wallbox(ControllableLoadProduct),
    #[serde(rename = "GAS")]
    Gas(GasProduct),
    #[serde(rename = "WAERME")]
    Waerme(HeatProduct),
    #[serde(rename = "WASSER")]
    Wasser(WaterProduct),
    #[serde(rename = "SOLAR")]
    Solar(SolarProduct),
    #[serde(rename = "EEG")]
    Eeg(EegProduct),
    #[serde(rename = "EINSPEISUNG")]
    Einspeisung(EinspeisungProduct),
    #[serde(rename = "HEMS")]
    Hems(HemsProduct),
    #[serde(rename = "EMOBILITY")]
    Emobility(EmobilityProduct),
    #[serde(rename = "ENERGIEDIENSTLEISTUNG")]
    Energiedienstleistung(ServiceProduct),
    #[serde(rename = "SHARING")]
    Sharing(SharingProduct),
}

impl Product {
    /// Product category string matching the productd JSONB `"category"` field.
    #[must_use]
    pub fn category_str(&self) -> &'static str {
        match self {
            Self::Strom(_) => "STROM",
            Self::Waermepumpe(_) => "WAERMEPUMPE",
            Self::Wallbox(_) => "WALLBOX",
            Self::Gas(_) => "GAS",
            Self::Waerme(_) => "WAERME",
            Self::Wasser(_) => "WASSER",
            Self::Solar(_) => "SOLAR",
            Self::Eeg(_) => "EEG",
            Self::Einspeisung(_) => "EINSPEISUNG",
            Self::Hems(_) => "HEMS",
            Self::Emobility(_) => "EMOBILITY",
            Self::Energiedienstleistung(_) => "ENERGIEDIENSTLEISTUNG",
            Self::Sharing(_) => "SHARING",
        }
    }

    /// Product code from productd (for ERP routing / audit trail).
    #[must_use]
    pub fn product_code(&self) -> Option<&str> {
        match self {
            Self::Strom(p) => p.product_code.as_deref(),
            Self::Waermepumpe(p) | Self::Wallbox(p) => p.base.product_code.as_deref(),
            Self::Gas(p) => p.product_code.as_deref(),
            Self::Waerme(p) => p.product_code.as_deref(),
            Self::Wasser(p) => p.product_code.as_deref(),
            Self::Solar(p) => p.product_code.as_deref(),
            Self::Eeg(p) => p.product_code.as_deref(),
            Self::Einspeisung(p) => p.product_code.as_deref(),
            Self::Hems(p) => p.product_code.as_deref(),
            Self::Emobility(p) => p.product_code.as_deref(),
            Self::Energiedienstleistung(p) => p.product_code.as_deref(),
            Self::Sharing(p) => p.electricity.product_code.as_deref(),
        }
    }

    /// The §42 EnWG Stromkennzeichnung declared on this product, if any.
    ///
    /// Electricity variants only — §42 is an electricity-disclosure duty. The
    /// service copies this onto the `BillingContext` so it reaches the invoice.
    #[must_use]
    pub fn energiequellen(&self) -> Option<&EnergieQuellen> {
        match self {
            Self::Strom(p) => p.energiequellen.as_ref(),
            Self::Waermepumpe(p) | Self::Wallbox(p) => p.base.energiequellen.as_ref(),
            _ => None,
        }
    }

    /// Minimum invoice amount (brutto EUR) for B2B Mindestabnahme contracts.
    #[must_use]
    pub fn minimum_invoice_eur_brutto(&self) -> Option<Decimal> {
        match self {
            Self::Strom(p) => p.minimum_invoice_eur_brutto,
            Self::Waermepumpe(p) | Self::Wallbox(p) => p.base.minimum_invoice_eur_brutto,
            Self::Gas(p) => p.minimum_invoice_eur_brutto,
            Self::Waerme(p) => p.minimum_invoice_eur_brutto,
            Self::Solar(p) => p.minimum_invoice_eur_brutto,
            _ => None,
        }
    }

    /// Build a `BillingEngine` configured for this product.
    ///
    /// ```rust
    /// use energy_billing::{Product, GridInput, RegulatoryRates};
    /// let json = r##"{"category":"STROM","arbeitspreis_ct_per_kwh":"30.0"}"##;
    /// let p: Product = serde_json::from_str(json).unwrap();
    /// let engine = p.build_engine(&GridInput::default(), &RegulatoryRates::default());
    /// ```
    #[must_use]
    pub fn build_engine(
        &self,
        grid: &crate::quantities::GridInput,
        rates: &crate::rates::RegulatoryRates,
    ) -> crate::engine::BillingEngine {
        use crate::engine::BillingEngine;
        use crate::providers::{
            ControllableLoadProvider, DynamicElectricityProvider, EegProvider, EinspeisungProvider,
            ElectricityProvider, EmobilityProvider, EnergyShareProvider, GasProvider, HeatProvider,
            HemsProvider, MwStProvider, ServiceProvider, SolarProvider, WaterProvider,
        };

        match self {
            Self::Strom(p) => {
                let mwst = rates.effective_mwst_electricity(p);
                if p.dynamic_epex {
                    BillingEngine::new()
                        .add(DynamicElectricityProvider::new(p.clone(), grid.clone()))
                        .add(MwStProvider::new(mwst))
                } else {
                    BillingEngine::new()
                        .add(ElectricityProvider::new(p.clone(), grid.clone()))
                        .add(MwStProvider::new(mwst))
                }
            }
            Self::Waermepumpe(p) | Self::Wallbox(p) => {
                let mwst = rates.effective_mwst_electricity(&p.base);
                BillingEngine::new()
                    .add(ControllableLoadProvider::new(p.clone(), grid.clone()))
                    .add(MwStProvider::new(mwst))
            }
            Self::Gas(p) => {
                let mwst = p.mwst_rate_override.unwrap_or(rates.mwst_rate);
                BillingEngine::new()
                    .add(GasProvider::new(p.clone(), grid.clone()))
                    .add(MwStProvider::new(mwst))
            }
            Self::Waerme(p) => {
                // District heating is standard-rated. The 7 % on gas/Fernwärme was
                // the temporary §28 Abs. 5/6 UStG window (01.10.2022–31.03.2024) —
                // `rates.mwst_rate` is already period-aware (billingd sets it via
                // `mwst_rate_for_gas_waerme_period`); there is NO permanent reduced
                // rate for renewable heat (§12 Abs. 2 Nr. 1 UStG covers Anlage-2
                // goods, not district heating).
                let mwst = p.mwst_rate_override.unwrap_or(rates.mwst_rate);
                BillingEngine::new()
                    .add(HeatProvider::new(p.clone()))
                    .add(MwStProvider::new(mwst))
            }
            Self::Wasser(p) => {
                // Trinkwasser is 7 % (§12 Abs. 2 Nr. 1 UStG); the provider sets
                // explicit per-position rates, so the engine default only backs
                // up positions that somehow lack one.
                let mwst = p.mwst_rate_override.unwrap_or(rust_decimal::dec!(0.07));
                BillingEngine::new()
                    .add(WaterProvider::new(p.clone()))
                    .add(MwStProvider::new(mwst))
            }
            Self::Solar(p) => {
                let mwst = rates.effective_mwst_solar(p);
                BillingEngine::new()
                    .add(SolarProvider::new(p.clone()))
                    .add(MwStProvider::new(mwst))
            }
            Self::Eeg(p) => {
                let mwst = rates.effective_mwst_eeg(p);
                BillingEngine::new()
                    .add(EegProvider::new(p.clone()))
                    .add(MwStProvider::new(mwst))
            }
            Self::Einspeisung(p) => {
                // §19 UStG Kleinunternehmer → 0 % on the feed-in Gutschrift.
                let mwst = if let Some(r) = p.mwst_rate_override {
                    r
                } else if p.kleinunternehmer_19_ustg {
                    rust_decimal::Decimal::ZERO
                } else {
                    rates.mwst_rate
                };
                BillingEngine::new()
                    .add(EinspeisungProvider::new(p.clone()))
                    .add(MwStProvider::new(mwst))
            }
            Self::Hems(p) => {
                let mwst = p.mwst_rate_override.unwrap_or(rates.mwst_rate);
                BillingEngine::new()
                    .add(HemsProvider::new(p.clone()))
                    .add(MwStProvider::new(mwst))
            }
            Self::Emobility(p) => {
                let mwst = p.mwst_rate_override.unwrap_or(rates.mwst_rate);
                BillingEngine::new()
                    .add(EmobilityProvider::new(p.clone()))
                    .add(MwStProvider::new(mwst))
            }
            Self::Energiedienstleistung(p) => {
                let mwst = p.mwst_rate_override.unwrap_or(rates.mwst_rate);
                BillingEngine::new()
                    .add(ServiceProvider::new(p.clone()))
                    .add(MwStProvider::new(mwst))
            }
            Self::Sharing(p) => {
                let mwst = rates.effective_mwst_electricity(&p.electricity);
                BillingEngine::new()
                    .add(ElectricityProvider::new(
                        p.electricity.clone(),
                        grid.clone(),
                    ))
                    .add(EnergyShareProvider::new(p.clone()))
                    .add(MwStProvider::new(mwst))
            }
        }
    }
}

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

    #[test]
    fn product_strom_roundtrip() {
        let json = r#"{"category":"STROM","arbeitspreis_ct_per_kwh":"28.5","grundpreis_ct_per_day":"8.0"}"#;
        let p: Product = serde_json::from_str(json).unwrap();
        match &p {
            Product::Strom(e) => {
                assert_eq!(e.arbeitspreis_ct_per_kwh, Some(rust_decimal::dec!(28.5)));
            }
            _ => panic!("expected Strom"),
        }
        let json2 = serde_json::to_string(&p).unwrap();
        let p2: Product = serde_json::from_str(&json2).unwrap();
        assert_eq!(p.category_str(), p2.category_str());
    }

    #[test]
    fn product_waermepumpe_flattens_electricity_base() {
        let json = r#"{"category":"WAERMEPUMPE","arbeitspreis_ct_per_kwh":"20.0","sect14a_modul2_nne_reduktion_ct_per_kwh":"1.5"}"#;
        let p: Product = serde_json::from_str(json).unwrap();
        match p {
            Product::Waermepumpe(c) => {
                assert_eq!(
                    c.base.arbeitspreis_ct_per_kwh,
                    Some(rust_decimal::dec!(20.0))
                );
                assert_eq!(
                    c.sect14a_modul2_nne_reduktion_ct_per_kwh,
                    Some(rust_decimal::dec!(1.5))
                );
            }
            _ => panic!("expected Waermepumpe"),
        }
    }

    #[test]
    fn product_gas_roundtrip() {
        let json = r#"{"category":"GAS","gas_arbeitspreis_ct_per_kwh_hs":"7.5","gas_grundpreis_ct_per_day":"5.0"}"#;
        let p: Product = serde_json::from_str(json).unwrap();
        match p {
            Product::Gas(g) => {
                assert_eq!(
                    g.gas_arbeitspreis_ct_per_kwh_hs,
                    Some(rust_decimal::dec!(7.5))
                );
            }
            _ => panic!("expected Gas"),
        }
    }

    #[test]
    fn product_unknown_category_errors() {
        let json = r#"{"category":"UNKNOWN_PRODUCT","foo":1}"#;
        assert!(serde_json::from_str::<Product>(json).is_err());
    }
}