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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
//! `BillingContext` — the immutable billing metadata passed to every provider.
//!
//! Separates *what we're billing* (quantities, products) from *how we're billing it*
//! (period, identifiers, invoice type, regulatory rates).

use crate::EuroAmount;
use crate::rates::RoundMoney;
use rust_decimal::Decimal;

use crate::rates::RegulatoryRates;

// ── Verbrauchshistorie ───────────────────────────────────────────────────────────

/// §40 Abs. 2 EnWG — Verbrauchshistorie (consumption history for invoice display).
///
/// German energy invoices must compare the billed period consumption against
/// the same period in the prior year and the national average for comparable
/// customers. This is an **invoice display requirement**, not a calculation input.
///
/// ## Legal basis
///
/// §40 Abs. 2 EnWG: “der tatsächliche Energieverbrauch sowie — soweit technisch möglich
/// und sinnvoll — ein Vergleich des aktuellen Energieverbrauchs des Letztverbrauchers mit
/// seinem Verbrauch im gleichen Zeitraum des Vorjahres … und dem Verbrauch einer
/// Vergleichsgruppe von Letztverbrauchern.”
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Verbrauchshistorie {
    /// Consumption in the same period of the prior year (kWh). §40 Abs. 2 Nr. 7 EnWG.
    #[serde(default)]
    pub vorjahr_kwh: Option<Decimal>,
    /// National average consumption for comparable customers (kWh). §40 Abs. 2 Nr. 8 EnWG.
    #[serde(default)]
    pub bundesdurchschnitt_kwh: Option<Decimal>,
    /// Description of the comparable customer group (e.g. `"2-Personen-Haushalt"`).
    #[serde(default)]
    pub kundengruppe: Option<String>,
}

// ── Vertragsinformationen ─────────────────────────────────────────────────────

/// §40 Abs. 1 EnWG — contract facts the invoice must state.
///
/// Vertragsdauer, Kündigungsfrist, the next possible Kündigungstermin and the
/// next Abrechnungstermin are invoice *contents*, not calculation inputs: they
/// change no amount, but an electricity or gas invoice without them is
/// incomplete under §40. Typed here so billingd can source them from vertragd
/// and the engine can emit them without either side inventing prose.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct Vertragsinformationen {
    /// Contract term as displayed, e.g. `"24 Monate"` or `"unbefristet"`.
    #[serde(default)]
    pub vertragsdauer: Option<String>,
    /// Notice period as displayed, e.g. `"6 Wochen zum Vertragsende"`.
    #[serde(default)]
    pub kuendigungsfrist: Option<String>,
    /// Next date the customer could terminate to.
    #[serde(default)]
    pub naechstmoeglicher_kuendigungstermin: Option<time::Date>,
    /// Next scheduled Abrechnungstermin.
    #[serde(default)]
    pub naechster_abrechnungstermin: Option<time::Date>,
}

/// §40 Abs. 2 EnWG — consumer information the invoice must state.
///
/// Nr. 1 (supplier identity and contact), Nr. 9 (rights in dispute
/// resolution, Schlichtungsstelle Energie per §111b EnWG), Nr. 10 (contact
/// data of the Verbraucherservice der Bundesnetzagentur) and Nr. 11
/// (Energieberatung contact). These change no amount, but a Letztverbraucher
/// invoice without them is incomplete under §40 Abs. 2.
///
/// [`Default`] carries the statutory public contact data — the
/// Schlichtungsstelle and BNetzA entries are fixed by law, not by operator —
/// so a bill can never silently lack the mandatory hints. The supplier
/// fields must be filled by the caller (billingd config).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Verbraucherinformationen {
    /// §40 Abs. 2 Nr. 1: supplier name as displayed on the bill.
    #[serde(default)]
    pub lieferant_name: Option<String>,
    /// §40 Abs. 2 Nr. 1: supplier postal address.
    #[serde(default)]
    pub lieferant_anschrift: Option<String>,
    /// §40 Abs. 2 Nr. 1: customer-service contact (hotline and/or e-mail).
    #[serde(default)]
    pub lieferant_kontakt: Option<String>,
    /// §40 Abs. 2 Nr. 9: dispute-resolution hint incl. Schlichtungsstelle
    /// Energie contact (§111b EnWG).
    pub schlichtungsstelle: String,
    /// §40 Abs. 2 Nr. 10: Verbraucherservice der Bundesnetzagentur contact.
    pub bnetza_verbraucherservice: String,
    /// §40 Abs. 2 Nr. 11: Energieberatung contact hint (Verbraucherzentrale).
    pub energieberatung: String,
    /// §40 Abs. 2 Nr. 12: supplier-switch hint incl. §41c price-comparison
    /// tools.
    pub wechselhinweis: String,
}

impl Default for Verbraucherinformationen {
    fn default() -> Self {
        Self {
            lieferant_name: None,
            lieferant_anschrift: None,
            lieferant_kontakt: None,
            schlichtungsstelle: "Bei Streitigkeiten können Sie die Schlichtungsstelle Energie e.V. \
                 anrufen (§111b EnWG): Friedrichstraße 133, 10117 Berlin, \
                 Tel. 030 2757240-0, info@schlichtungsstelle-energie.de, \
                 www.schlichtungsstelle-energie.de. Voraussetzung ist, dass der \
                 Lieferant Ihrer Beschwerde nicht binnen vier Wochen abgeholfen hat."
                .to_owned(),
            bnetza_verbraucherservice: "Verbraucherservice der Bundesnetzagentur für den Bereich Elektrizität \
                 und Gas: Postfach 8001, 53105 Bonn, Tel. 030 22480-500, \
                 verbraucherservice-energie@bnetza.de."
                .to_owned(),
            energieberatung: "Unabhängige Energieberatung erhalten Sie bei der \
                 Energieberatung der Verbraucherzentrale, www.verbraucherzentrale-energieberatung.de."
                .to_owned(),
            wechselhinweis: "Informationen zum Lieferantenwechsel und behördlich zugelassene \
                 Preisvergleichsinstrumente (§41c EnWG) finden Sie unter \
                 www.bundesnetzagentur.de."
                .to_owned(),
        }
    }
}

/// The party the invoice is addressed to — § 14 Abs. 4 Nr. 1 UStG's
/// *Leistungsempfänger*, EN 16931's BG-7 buyer.
///
/// # Why this is on the context
///
/// The engine prices a Marktlokation; it holds no customer master. So it used
/// to name the recipient by the **MaLo alone** — a `Geschaeftspartner` carrying
/// one `mako:externe_kunden_id` ZusatzAttribut and no name, no address. That is
/// not a document § 14 UStG describes, and a BO4E consumer reading the stored
/// `Rechnung` found no recipient at all, while the *same* invoice's EN 16931
/// model carried the customer in full because the caller supplied it on a
/// separate channel.
///
/// One source now: the caller that resolves the customer puts it here, and both
/// maps read it. `None` still works — the document then names the
/// Marktlokation, which is the documented degradation for an uncontracted MaLo
/// rather than a failed run — but it is now the same degradation on both sides.
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rechnungsempfaenger {
    /// The addressee as printed — an organisation name or a person's full name.
    #[serde(default)]
    pub name: Option<String>,
    /// Street and house number.
    #[serde(default)]
    pub line1: Option<String>,
    /// Postcode.
    #[serde(default)]
    pub post_code: Option<String>,
    /// Town.
    #[serde(default)]
    pub city: Option<String>,
    /// ISO 3166-1 alpha-2. Absent is read as `DE`.
    #[serde(default)]
    pub country: Option<String>,
    /// USt-IdNr., where the customer has one (BT-48).
    #[serde(default)]
    pub vat_id: Option<String>,
}

impl Rechnungsempfaenger {
    /// Is there enough here to name a recipient at all?
    ///
    /// A recipient with no name is not one: the fallback that names the
    /// Marktlokation is more honest than an empty BT-44.
    #[must_use]
    pub fn names_somebody(&self) -> bool {
        self.name.as_deref().is_some_and(|n| !n.trim().is_empty())
    }
}

// ── InvoiceType ───────────────────────────────────────────────────────────────

/// Whether this is an initial invoice, a correction, a cancellation, or a final settlement.
///
/// German energy suppliers frequently perform:
/// ```text
/// Initial invoice  →  Correction (corrected meter reading)
///                  →  Cancellation (full reversal)
///                  →  Final (annual Schlussabrechnung)
/// ```
///
/// ## § 147 AO / GoBD compliance
///
/// Corrections must reference the original invoice ID for the 3-year audit trail.
/// Cancellations reverse the original to EUR 0.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum InvoiceType {
    /// Standard billing run (Abschlagsrechnung, periodic invoice).
    Initial,

    /// Credit note (Gutschrift) — outgoing payment to a third party.
    ///
    /// Used for:
    /// - EEG feed-in settlement (payment to generator)
    /// - EINSPEISUNG Direktvermarktung settlement
    /// - Reverse-charge scenarios
    ///
    /// `rechnungsart` = `"GUTSCHRIFT"`
    CreditNote,

    /// Correction superseding an earlier invoice (§ 147 AO / GoBD).
    ///
    /// The original invoice must be referenced in the accounting system.
    /// The net effect is: `original + correction = corrected total`.
    Correction {
        /// ID of the original invoice this corrects.
        original_invoice_id: String,
        /// Human-readable reason (for audit trail).
        reason: Option<String>,
    },

    /// Full reversal of an earlier invoice (Stornorechnung).
    ///
    /// All positions are sign-inverted to bring the original to EUR 0.
    Cancellation {
        /// ID of the original invoice being cancelled.
        original_invoice_id: String,
    },

    /// Annual final settlement (Schlussabrechnung / Jahresabrechnung).
    ///
    /// Reconciles advance payments against measured consumption.
    /// Include paid Abschläge in `BillingContext::abschlage` — they will be
    /// deducted from `Invoice::zahlbetrag_eur`.
    Final,

    /// Advance payment request (Abschlagsrechnung).
    ///
    /// Use this for **estimated** periodic billing where no final meter reading
    /// is available yet. The customer pays on account; the annual settlement
    /// (`InvoiceType::Final`) reconciles the difference.
    ///
    /// BO4E `rechnungsart` = `"ABSCHLAGSRECHNUNG"`
    ///
    /// ## Distinction from `Initial`
    ///
    /// `Initial` represents billing for **actual metered consumption** — it maps
    /// to `"RECHNUNG"`. `AdvancePayment` represents **estimated advance payments**
    /// that will be settled annually.
    AdvancePayment,

    /// Partial delivery invoice (Teilrechnung) for incomplete supply periods.
    ///
    /// Used when a customer switches supplier mid-period, moves in/out, or when a
    /// meter replacement creates a split period. The departing or arriving supplier
    /// issues a Teilrechnung for the exact days of actual supply.
    ///
    /// ## Legal basis
    ///
    /// §41 EnWG Abs. 1: the invoice must cover the actual supply period.
    /// StromGVV §17 / GasGVV §14: Lieferungsende is billed on the day of change.
    ///
    /// `rechnungsart` = `"TEILRECHNUNG"`
    PartialInvoice,
}

impl InvoiceType {
    /// The typed BO4E [`Rechnungstyp`](rubo4e::current::Rechnungstyp), where the
    /// BO4E vocabulary has a value:
    ///
    /// | `InvoiceType` | BO4E `rechnungstyp` |
    /// |---|---|
    /// | `Initial` | `ENDKUNDENRECHNUNG` |
    /// | `AdvancePayment` | `ABSCHLAGSRECHNUNG` |
    /// | `Final` | `ABSCHLUSSRECHNUNG` (Schlussrechnung) |
    /// | `PartialInvoice` | `ZWISCHENRECHNUNG` (mid-period settlement) |
    /// | `CreditNote` / `Correction` / `Cancellation` | `None` |
    ///
    /// The three `None` cases have no BO4E Rechnungstyp; they are carried by
    /// `istStorno`, `originalRechnungsnummer` and the `rechnungsart`
    /// ZusatzAttribut on the emitted Rechnung.
    #[must_use]
    #[cfg(feature = "bo4e")]
    pub fn rechnungstyp(&self) -> Option<rubo4e::current::Rechnungstyp> {
        use rubo4e::current::Rechnungstyp as R;
        match self {
            Self::Initial => Some(R::Endkundenrechnung),
            Self::AdvancePayment => Some(R::Abschlagsrechnung),
            Self::Final => Some(R::Abschlussrechnung),
            Self::PartialInvoice => Some(R::Zwischenrechnung),
            Self::CreditNote | Self::Correction { .. } | Self::Cancellation { .. } => None,
        }
    }

    /// Process-level Rechnungsart label (mako vocabulary, superset of BO4E).
    ///
    /// Emitted as the `rechnungsart` ZusatzAttribut for invoice types the BO4E
    /// `Rechnungstyp` enum cannot express losslessly.
    #[must_use]
    pub fn rechnungsart(&self) -> &'static str {
        match self {
            Self::Initial => "RECHNUNG",
            Self::AdvancePayment => "ABSCHLAGSRECHNUNG",
            Self::CreditNote => "GUTSCHRIFT",
            Self::Correction { .. } => "KORREKTURRECHNUNG",
            Self::Cancellation { .. } => "STORNORECHNUNG",
            Self::Final => "SCHLUSSRECHNUNG",
            Self::PartialInvoice => "TEILRECHNUNG",
        }
    }

    /// Returns the original invoice ID for corrections and cancellations.
    #[must_use]
    pub fn original_invoice_id(&self) -> Option<&str> {
        match self {
            Self::Correction {
                original_invoice_id,
                ..
            }
            | Self::Cancellation {
                original_invoice_id,
            } => Some(original_invoice_id),
            _ => None,
        }
    }

    /// `true` when this invoice reverses all positions of the original.
    #[must_use]
    pub fn is_reversal(&self) -> bool {
        matches!(self, Self::Cancellation { .. })
    }

    /// `true` when this document discharges the advances the context carries.
    ///
    /// § 40 Abs. 1 EnWG makes the settling invoice itemise and deduct each
    /// advance payment. An [`AdvancePayment`](Self::AdvancePayment) is the
    /// document that *collects* one, so it discharges none: netting the
    /// advances already paid against it would reduce the very request that asks
    /// for the next.
    #[must_use]
    pub fn settles_advances(&self) -> bool {
        !matches!(self, Self::AdvancePayment)
    }
}

#[allow(clippy::derivable_impls)]
impl Default for InvoiceType {
    fn default() -> Self {
        Self::Initial
    }
}

// ── CustomerKategorie ─────────────────────────────────────────────────────────

/// Customer category for the delivery point.
///
/// Determines applicable tariff categories, regulatory exemptions, and invoice
/// disclosure requirements. Affects Stromsteuer (§9 Nr. 1 StromStG industrial
/// exemption threshold), Preisangabenverordnung, and §41 EnWG disclosure depth.
///
/// ## Legal basis
///
/// - §2 Nr. 4 StromStG — definition of "Unternehmen des produzierenden Gewerbes"
/// - § 12 StromNZV / §14 NAV — RLM metering thresholds
/// - §41 Abs. 1 EnWG — invoice disclosure requirements vary by customer type
/// - Grundversorgung (StromGVV) vs. Sondervertrag — different contract law
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CustomerKategorie {
    /// Household customer (Haushaltskunde, §2 Nr. 25 EnWG).
    ///
    /// B2C. StromGVV / GasGVV apply. §40 EnWG Kilowattstundenpreis mandatory.
    /// Invoice must include Verbrauchshistorie (§40 Abs. 2 EnWG).
    #[default]
    Haushalt,

    /// Small commercial customer (Gewerbekunde, not a household but not RLM-obligated).
    ///
    /// B2B < 100 MWh/year. StromGVV / GasGVV still apply in most cases.
    /// May be on SLP or transitioning to iMSys.
    Gewerbe,

    /// Industrial / large commercial customer (Sonderkunde).
    ///
    /// B2B ≥ 100 MWh/year electricity (§ 12 StromNZV), RLM mandatory.
    /// Sondervertrag, not Grundversorgung. Eligible for §9 Nr. 1–3 StromStG
    /// industrial exemption, KWKG Selbstbehaltsgrenze, and capacity pricing.
    Industrie,

    /// Agricultural customer (Landwirtschaft).
    ///
    /// Special BEHG/Energiesteuer treatment may apply for agricultural use.
    /// §2 Abs. 1 Nr. 4 UStG (7% reduced VAT on certain agricultural inputs).
    Landwirtschaft,

    /// Public authority / public transport (öffentliche Einrichtung).
    ///
    /// May qualify for Konzessionsabgabe exemption (§2 Abs. 7 KAV).
    OeffentlicheEinrichtung,
}

impl CustomerKategorie {
    /// Whether this customer category typically uses SLP billing.
    #[must_use]
    pub fn is_slp_customer(self) -> bool {
        matches!(self, Self::Haushalt | Self::Gewerbe)
    }

    /// Whether the annual Verbrauchshistorie (§40 Abs. 2 EnWG) applies.
    ///
    /// Mandatory for household customers (B2C). Recommended for Gewerbe.
    /// Not required for industrial / RLM customers.
    #[must_use]
    pub fn requires_verbrauchshistorie(self) -> bool {
        matches!(self, Self::Haushalt)
    }

    /// Whether the §40 EnWG Kilowattstundenpreis must appear on the invoice.
    ///
    /// Mandatory for all non-RLM electricity customers.
    #[must_use]
    pub fn requires_kilowattstundenpreis(self) -> bool {
        !matches!(self, Self::Industrie)
    }
}

// ── AbschlagDeduction ─────────────────────────────────────────────────────────

/// An advance payment (Abschlag) previously collected from the customer.
///
/// Include these in `BillingContext::abschlage` for `InvoiceType::Final`
/// (Jahresabrechnung) to deduct prior payments from the final amount due.
///
/// ## §41 EnWG
///
/// The annual final settlement must show each advance payment date and amount
/// so the customer can verify the reconciliation.
///
/// ## §14 Abs. 5 Satz 2 UStG
///
/// An Endrechnung must deduct the advances **and the tax attributable to them**
/// ("die vereinnahmten Teilentgelte und die auf sie entfallenden Steuerbeträge"),
/// so each advance carries the rate it was invoiced at. A gross total alone
/// cannot express that, which is why [`ust_satz`](Self::ust_satz) is not
/// optional: an advance collected at 19 % and one collected at 7 % deduct
/// different amounts of tax from the same gross sum.
///
/// [`betrag_eur`](Self::betrag_eur) is the **gross** amount the customer paid;
/// the net and the tax it contains are derived from it by
/// [`netto_eur`](Self::netto_eur) and [`ust_eur`](Self::ust_eur).
///
/// ## Example
///
/// A customer paying EUR 120/month → 12 × EUR 120 = EUR 1 440 in advances.
/// If consumption bill = EUR 1 600, Zahlbetrag = EUR 160 (balance due).
/// If consumption bill = EUR 1 300, Zahlbetrag = EUR -140 (refund).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AbschlagDeduction {
    /// Payment date (shown on the invoice for §41 EnWG compliance).
    pub datum: time::Date,
    /// Gross EUR amount already paid (positive = customer paid this amount).
    pub betrag_eur: Decimal,
    /// VAT rate contained in `betrag_eur`, as a fraction — `0.19` for 19 %.
    ///
    /// This is the rate the *advance* was invoiced at, which is not necessarily
    /// the rate on the final invoice: a rate change mid-year leaves earlier
    /// advances at the old rate.
    pub ust_satz: Decimal,
    /// Optional description shown on invoice (e.g. `"Abschlag März 2026"`).
    #[serde(default)]
    pub beschreibung: Option<String>,
}

impl AbschlagDeduction {
    /// The net amount contained in the gross payment (Herausrechnung).
    ///
    /// `betrag_eur / (1 + ust_satz)`, rounded to cents. Returns the gross
    /// unchanged when the rate is zero, so a zero-rated advance needs no
    /// special-casing at the call site.
    #[must_use]
    pub fn netto_eur(&self) -> Decimal {
        if self.ust_satz.is_zero() {
            return self.betrag_eur;
        }
        (self.betrag_eur / (Decimal::ONE + self.ust_satz)).round_kfm(2)
    }

    /// The tax contained in the gross payment.
    ///
    /// Derived as `betrag_eur - netto_eur` rather than `netto × rate`, so that
    /// net and tax always re-sum to the gross the customer actually paid.
    #[must_use]
    pub fn ust_eur(&self) -> Decimal {
        self.betrag_eur - self.netto_eur()
    }

    /// Project into a [`billing::AdvancePayment`] carrying this advance's own tax.
    ///
    /// This is the structure EN 16931's flat BT-113 cannot hold and that
    /// §14 Abs. 5 Satz 2 UStG requires on a settling invoice. It mirrors the
    /// ZUGFeRD / Factur-X EXTENDED group `SpecifiedAdvancePayment` (BG-X-45).
    ///
    /// The category is derived from the rate: a positive rate is a standard-rated
    /// advance, a zero rate a zero-rated one. An advance under reverse charge
    /// (§13b UStG) is not expressible this way and is not produced here — such a
    /// supply carries no advance tax to deduct.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Arithmetic`](crate::EngineError::Arithmetic) if
    /// the amounts overflow [`EuroAmount`].
    pub fn to_advance_payment(&self) -> Result<billing::AdvancePayment, crate::EngineError> {
        let category = if self.ust_satz.is_zero() {
            billing::TaxCategory::ZeroRated
        } else {
            billing::TaxCategory::Standard
        };
        let entry = billing::TaxBreakdownEntry::new(
            category,
            self.ust_satz,
            EuroAmount::checked_from_decimal(self.netto_eur())?,
            EuroAmount::checked_from_decimal(self.ust_eur())?,
        );
        let advance =
            billing::AdvancePayment::new(vec![entry])?.with_received_on(self.datum.to_string());
        Ok(match &self.beschreibung {
            Some(r) => advance.with_reference(r.clone()),
            None => advance,
        })
    }
}

// ── SettlementForm ────────────────────────────────────────────────────────────

/// How a settling invoice accounts for advances the customer already paid.
///
/// Both shapes are lawful and both are in use; they differ in what the document
/// shows, not in what the customer ends up paying.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SettlementForm {
    /// **Endrechnung** — invoice the whole supply, then deduct the advances and
    /// the tax contained in them (§14 Abs. 5 Satz 2 UStG).
    ///
    /// Totals and the VAT breakdown describe the full period; only the amount
    /// payable shrinks. Deducting the advances but *not* their tax is the failure
    /// this form has to avoid: under UStAE 14.8 Abs. 10 the issuer then owes the
    /// tax shown plus the advance-related portion again under §14c Abs. 1 — the
    /// same tax twice.
    #[default]
    Endrechnung,

    /// **Restrechnung** — invoice only the remainder; the advances are not listed.
    ///
    /// Structurally simpler, and what the BMF recommends for e-invoices (Schreiben
    /// v. 15.10.2024, Rn. 48), because EN 16931's core profiles have nowhere to
    /// carry per-advance tax. The taxable base is the residual per rate rather
    /// than the full supply.
    Restrechnung,
}

// ── BillingPeriod ─────────────────────────────────────────────────────────────

/// A validated billing period — first and last day, both inclusive.
///
/// The constructor refuses `from > to`, so an inverted period is
/// unrepresentable everywhere downstream: no provider, no pro-rata helper,
/// no JSON assembly ever needs to re-check the ordering.
///
/// Deserialization runs through the same validation
/// (`#[serde(try_from = …)]`), so a period arriving over the wire holds the
/// same invariant as one built in code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(try_from = "PeriodEndpoints", into = "PeriodEndpoints")]
pub struct BillingPeriod {
    from: time::Date,
    to: time::Date,
}

/// Serde carrier for [`BillingPeriod`] — validation happens in `TryFrom`.
#[derive(serde::Serialize, serde::Deserialize)]
struct PeriodEndpoints {
    from: time::Date,
    to: time::Date,
}

impl TryFrom<PeriodEndpoints> for BillingPeriod {
    type Error = crate::EngineError;
    fn try_from(p: PeriodEndpoints) -> Result<Self, Self::Error> {
        Self::new(p.from, p.to)
    }
}

impl From<BillingPeriod> for PeriodEndpoints {
    fn from(p: BillingPeriod) -> Self {
        Self {
            from: p.from,
            to: p.to,
        }
    }
}

impl BillingPeriod {
    /// Build a period from first and last day (both inclusive).
    ///
    /// # Errors
    ///
    /// [`EngineError::InvalidPeriod`](crate::EngineError::InvalidPeriod) when `from > to`.
    pub fn new(from: time::Date, to: time::Date) -> Result<Self, crate::EngineError> {
        if from > to {
            return Err(crate::EngineError::InvalidPeriod { from, to });
        }
        Ok(Self { from, to })
    }

    /// First day of the period (inclusive).
    #[must_use]
    pub const fn from(self) -> time::Date {
        self.from
    }

    /// Last day of the period (inclusive).
    #[must_use]
    pub const fn to(self) -> time::Date {
        self.to
    }

    /// Number of calendar days, inclusive of both endpoints. Always ≥ 1.
    #[must_use]
    pub fn days(self) -> i64 {
        (self.to - self.from).whole_days() + 1
    }

    /// Whether the given date falls inside the period.
    #[must_use]
    pub fn contains(self, date: time::Date) -> bool {
        self.from <= date && date <= self.to
    }
}

impl Default for BillingPeriod {
    /// Placeholder single-day period at `Date::MIN` — used only by
    /// `BillingContext::default()`. Always set an explicit period before
    /// billing.
    fn default() -> Self {
        Self {
            from: time::Date::MIN,
            to: time::Date::MIN,
        }
    }
}

impl std::fmt::Display for BillingPeriod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}..{}", self.from, self.to)
    }
}

// ── Vertragsart ───────────────────────────────────────────────────────────────

/// The contractual regime the delivery runs under — drives which invoice
/// disclosures and period limits apply.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Vertragsart {
    /// Freely negotiated supply contract (§41 EnWG). The default.
    #[default]
    Sondervertrag,

    /// Grundversorgung (§36 EnWG, StromGVV/GasGVV): the published Allgemeine
    /// Preise apply, termination per §20 StromGVV/GasGVV is two weeks.
    /// Emitted as the `vertragsart` ZusatzAttribut so the invoice states the
    /// regime the prices come from.
    Grundversorgung,

    /// Ersatzversorgung (§38 EnWG): the fallback supply when energy is drawn
    /// without an assignable contract. Ends by law after **three months** at
    /// the latest (§ 38 Abs. 4 EnWG) — the engine refuses to bill a
    /// longer Ersatzversorgung period, because such a supply cannot exist.
    Ersatzversorgung,
}

impl Vertragsart {
    /// The label emitted as the `vertragsart` ZusatzAttribut.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Sondervertrag => "SONDERVERTRAG",
            Self::Grundversorgung => "GRUNDVERSORGUNG",
            Self::Ersatzversorgung => "ERSATZVERSORGUNG",
        }
    }
}

// ── BillingContext ────────────────────────────────────────────────────────────

/// Immutable billing metadata — the *context* for one invoice generation run.
///
/// Every [`BillingProvider`][crate::BillingProvider] receives a reference to
/// the same `BillingContext` so all positions share identical period, party IDs,
/// and regulatory rates.
///
/// ## New in this version
///
/// - `vertragsbeginn` / `vertragsende` — enables automatic pro-rata billing
///   when a contract starts or ends mid-period
/// - `zaehler_id` — §41 EnWG Zählernummer on invoice
/// - `abschlage` — advance payments deducted in `Invoice::zahlbetrag_eur`
///   (required for `InvoiceType::Final` / Jahresabrechnung)
///
/// ## Example
///
/// ```rust
/// use energy_billing::{AbschlagDeduction, BillingContext, BillingPeriod, InvoiceType, RegulatoryRates};
/// use time::macros::date;
/// use rust_decimal::dec;
///
/// let ctx = BillingContext {
///     malo_id: "51238696012".to_owned(),
///     lf_mp_id: "9900000000001".to_owned(),
///     rechnungsnummer: "R2026-001".to_owned(),
///     period: BillingPeriod::new(date!(2026-01-01), date!(2026-12-31)).unwrap(),
///     invoice_type: InvoiceType::Final,
///     regulatory_rates: RegulatoryRates::default(),
///     contract_id: None,
///     abschlage: vec![
///         AbschlagDeduction {
///             datum: date!(2026-01-15),
///             betrag_eur: dec!(120.00),
///             ust_satz: dec!(0.19),
///             beschreibung: Some("Abschlag Januar 2026".to_owned()),
///         },
///     ],
///     ..Default::default()
/// };
/// assert_eq!(ctx.total_abschlage_eur(), dec!(120.00));
/// ```
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct BillingContext {
    /// 11-digit Marktlokations-ID of the delivery point.
    pub malo_id: String,

    /// BDEW/DVGW Codenummer of the Lieferant (invoice issuer).
    pub lf_mp_id: String,

    /// Invoice number (Rechnungsnummer) — unique per invoice.
    ///
    /// Operator's responsibility to ensure uniqueness. Recommended format:
    /// `{prefix}-{year}-{sequence}` (e.g. `"INV-2026-000001"`).
    pub rechnungsnummer: String,

    /// The billing period — validated, `from > to` unrepresentable.
    pub period: BillingPeriod,

    /// Invoice type: initial, correction, cancellation, or final settlement.
    pub invoice_type: InvoiceType,

    /// The contractual regime — Sondervertrag, Grundversorgung, or
    /// Ersatzversorgung. Emitted as the `vertragsart` ZusatzAttribut; an
    /// Ersatzversorgung period longer than three months blocks the run
    /// (§ 38 Abs. 4 EnWG).
    #[serde(default)]
    pub vertragsart: Vertragsart,

    /// How advances are accounted for on a settling invoice.
    ///
    /// Only consulted when `abschlage` is non-empty. See [`SettlementForm`].
    #[serde(default)]
    pub settlement_form: SettlementForm,

    /// The VAT rate a `minimum_invoice_eur_brutto` top-up is agreed at.
    ///
    /// The Mindestbetrag is a contractual charge, not a statutory one, so the
    /// contract names its rate. `None` uses the period's standard rate — right
    /// for a single-rate invoice and wrong for a mixed one, where the gross-up
    /// otherwise misses the configured minimum by the rate difference.
    #[serde(default)]
    pub minimum_invoice_mwst_rate: Option<Decimal>,

    /// Statutory levy rates (Stromsteuer, Energiesteuer, BEHG, MwSt).
    ///
    /// Sourced from `billingd.toml [rates]` — never hardcoded in the library.
    pub regulatory_rates: RegulatoryRates,

    /// The day the invoice is issued — the day it reaches the customer.
    ///
    /// `None` keeps the library clock-free and falls back to the period end.
    /// A caller that has a clock should set it, because two statutory facts
    /// hang off the issue date and neither is measurable from the period:
    ///
    /// - **§ 40c Abs. 1 EnWG** makes the amount due at the earliest **two weeks
    ///   after the payment request reaches the customer**. Counting from the
    ///   period end instead meant a catch-up run or a late Schlussrechnung
    ///   issued an invoice that was *already overdue on arrival*, which the
    ///   dunning downstream then acted on.
    /// - § 14 Abs. 4 Nr. 3 UStG wants the actual Ausstellungsdatum.
    #[serde(default)]
    pub issue_date: Option<time::Date>,

    /// The party the invoice is addressed to. See [`Rechnungsempfaenger`].
    ///
    /// `None` names the Marktlokation instead, which is the documented
    /// degradation for a MaLo with no contract on file.
    #[serde(default)]
    pub rechnungsempfaenger: Option<Rechnungsempfaenger>,

    /// Optional contract reference (for LF internal use / ERP routing).
    #[serde(default)]
    pub contract_id: Option<String>,

    /// Contract start date (§41 EnWG).
    ///
    /// When set AND `period_from < vertragsbeginn`, `billing_days_fraction()`
    /// returns a value < 1.0 for pro-rata first-month billing.
    #[serde(default)]
    pub vertragsbeginn: Option<time::Date>,

    /// Contract end date.
    ///
    /// When set AND `period_to > vertragsende`, `billing_days_fraction()`
    /// returns a value < 1.0 for pro-rata last-month billing.
    #[serde(default)]
    pub vertragsende: Option<time::Date>,

    /// Zählernummer (§41 EnWG — mandatory on electricity invoices).
    ///
    /// Appears on the invoice as an informational line item.
    #[serde(default)]
    pub zaehler_id: Option<String>,

    /// Advance payments to deduct from the final invoice (Jahresabrechnung).
    ///
    /// Used exclusively with `InvoiceType::Final`. Each entry produces an
    /// `Abschlag` deduction line in `Invoice::zahlbetrag_eur`.
    ///
    /// The German retail practice: monthly advance payments are collected
    /// throughout the year; the annual settlement debits/credits the difference.
    #[serde(default)]
    pub abschlage: Vec<AbschlagDeduction>,

    /// §40 Abs. 2 EnWG — Verbrauchshistorie for invoice display.
    ///
    /// When set, appears as informational ZusatzAttribute in the Rechnung JSON
    /// showing the customer's consumption history vs. prior year and average.
    #[serde(default)]
    pub verbrauchshistorie: Option<Verbrauchshistorie>,

    /// §40 Abs. 1 EnWG contract facts, emitted as ZusatzAttribute.
    #[serde(default)]
    pub vertragsinformationen: Option<Vertragsinformationen>,

    /// §40 Abs. 2 EnWG — consumer information (supplier contact,
    /// Schlichtungsstelle, BNetzA Verbraucherservice, Energieberatung,
    /// Wechselhinweis). `None` falls back to
    /// [`Verbraucherinformationen::default`] at render time — the statutory
    /// hints are never omitted from a Rechnung.
    pub verbraucherinformationen: Option<Verbraucherinformationen>,

    /// §42 EnWG — Stromkennzeichnung, structured.
    ///
    /// Fuel-mix percentages, the specific CO₂ emissions (§42 Abs. 2 Nr. 2 —
    /// mandatory on every electricity invoice), and HKN certification. Emitted
    /// as the `stromkennzeichnung` ZusatzAttribut with the structure intact;
    /// prose belongs in [`crate::tariff::EnergieQuellen::beschreibung`].
    ///
    /// Structured rather than a free-text `energiemix` string, which cannot
    /// carry the CO₂ figure the law names explicitly.
    #[serde(default)]
    pub energiequellen: Option<crate::tariff::EnergieQuellen>,

    /// Minimum invoice amount (brutto) in EUR.
    ///
    /// When set and the computed `brutto_eur < minimum_invoice_eur_brutto`, the
    /// engine adds a `Mindestbetrag` position to reach the minimum.
    ///
    /// Set from `TariffInput.minimum_invoice_eur_brutto` by the service layer
    /// (`billingd`) when building the billing context.
    ///
    /// ## Use case
    ///
    /// B2B contracts with a minimum annual consumption commitment
    /// (Mindestabnahmeverpflichtung). The customer pays at least this amount
    /// per billing period regardless of actual consumption.
    #[serde(default)]
    pub minimum_invoice_eur_brutto: Option<Decimal>,

    /// BDEW-Codenummer of the Netzbetreiber (§41 EnWG — mandatory on invoices).
    ///
    /// German energy invoices must identify the network operator who provides
    /// the grid infrastructure at the delivery point (§41 Abs. 1 Nr. 5 EnWG).
    /// This appears as `"netzbetreiber"."marktpartnercode"` in the Rechnung JSON.
    ///
    /// When `None`, the `netzbetreiber` field is omitted from the invoice JSON.
    /// For full §41 EnWG compliance on retail electricity/gas invoices, always set this.
    #[serde(default)]
    pub nb_mp_id: Option<String>,

    /// Unique billing run identifier for audit trail and duplicate detection.
    ///
    /// When set, propagated to `Invoice.billing_run_id` and included in the
    /// Rechnung JSON as a `ZusatzAttribut` under key `"billingRunId"`.
    ///
    /// Use a UUID v4 generated by `billingd` at invoice time to correlate the
    /// database record (`billing_records.id`) with calculation outputs.
    #[serde(default)]
    pub billing_run_id: Option<String>,

    /// Customer category — drives regulatory exemptions and invoice disclosure.
    ///
    /// | Category | SLP | Verbrauchshistorie | §40 kWh-Preis |
    /// |---|---|---|---|
    /// | `Haushalt` | ✅ | Mandatory | Mandatory |
    /// | `Gewerbe` | ✅ | Recommended | Mandatory |
    /// | `Industrie` | ❌ (RLM) | — | — |
    /// | `Landwirtschaft` | ✅ | Recommended | Mandatory |
    /// | `OeffentlicheEinrichtung` | ✅/❌ | — | Mandatory |
    ///
    /// Defaults to `Haushalt` — always set explicitly for B2B customers.
    #[serde(default)]
    pub kundenkategorie: CustomerKategorie,

    /// §13b UStG reverse charge (Steuerschuldnerschaft des Leistungsempfängers).
    ///
    /// Set `true` when the customer is a **Stromwiederverkäufer** (electricity/gas
    /// reseller, §13b Abs. 2 Nr. 5 lit. b UStG): the whole supply is invoiced net
    /// and the recipient owes the VAT. The engine then marks every supply position
    /// reverse-charge before the MwSt pass, so the `MwStProvider` charges no VAT and
    /// the EN 16931 tax breakdown carries an `AE` subtotal instead of `S`/`Z`.
    /// Defaults to `false` (normal Steuerschuldnerschaft des Leistenden).
    #[serde(default)]
    pub reverse_charge: bool,
}

impl BillingContext {
    /// First day of the billing period (inclusive).
    #[must_use]
    pub const fn period_from(&self) -> time::Date {
        self.period.from()
    }

    /// Last day of the billing period (inclusive).
    #[must_use]
    pub const fn period_to(&self) -> time::Date {
        self.period.to()
    }

    /// The day the invoice is issued: [`Self::issue_date`], else the period end.
    #[must_use]
    pub fn ausstellungsdatum(&self) -> time::Date {
        match self.issue_date {
            Some(d) => d,
            None => self.period.to(),
        }
    }

    /// The day payment falls due — two weeks after issue.
    ///
    /// § 40c Abs. 1 EnWG: due at the earliest two weeks after the payment
    /// request reaches the customer. Measured from the **issue** date, so an
    /// invoice for an old period does not arrive already overdue.
    #[must_use]
    pub fn faelligkeitsdatum(&self) -> time::Date {
        self.ausstellungsdatum()
            .saturating_add(time::Duration::days(14))
    }

    /// Number of calendar days in the billing period.
    ///
    /// Used for Grundpreis (daily rate × days) and pro-rata calculations.
    #[must_use]
    pub fn days(&self) -> i64 {
        self.period.days()
    }

    /// Pro-rata fraction of the billing period actually billable.
    ///
    /// Returns `None` when the full period is billable (no pro-rata applies).
    /// Returns `Some(fraction)` where `0 < fraction < 1` when:
    /// - `vertragsbeginn` falls within the period (late contract start)
    /// - `vertragsende` falls within the period (early contract end)
    ///
    /// ## §41 EnWG — pro-rata billing
    ///
    /// First and last billing periods are prorated to the actual contract days.
    ///
    /// # Example
    ///
    /// ```rust
    /// use energy_billing::{BillingContext, BillingPeriod, InvoiceType, RegulatoryRates};
    /// use time::macros::date;
    ///
    /// let ctx = BillingContext {
    ///     period: BillingPeriod::new(date!(2026-01-01), date!(2026-01-31)).unwrap(),
    ///     vertragsbeginn: Some(date!(2026-01-16)), // contract started mid-month
    ///     ..Default::default()
    /// };
    /// let frac = ctx.billing_days_fraction().unwrap();
    /// // 16 billable days out of 31: ≈ 0.516
    /// assert!(frac > rust_decimal::dec!(0.50) && frac < rust_decimal::dec!(0.55));
    /// ```
    #[must_use]
    pub fn billing_days_fraction(&self) -> Option<Decimal> {
        let period_days = self.days();
        if period_days <= 0 {
            return None;
        }

        // Effective start: max(period_from, vertragsbeginn)
        let effective_from = match self.vertragsbeginn {
            Some(vb) if vb > self.period_from() => vb,
            _ => self.period_from(),
        };

        // Effective end: min(period_to, vertragsende)
        let effective_to = match self.vertragsende {
            Some(ve) if ve < self.period_to() => ve,
            _ => self.period_to(),
        };

        let billable = (effective_to - effective_from).whole_days() + 1;
        if billable <= 0 {
            return None;
        }
        if billable >= period_days {
            return None; // full period, no pro-rata
        }

        let frac = Decimal::from(billable) / Decimal::from(period_days);
        Some(frac.round_kfm(6))
    }

    /// Total advance payments included in this context.
    ///
    /// For `InvoiceType::Final`, this equals the amount deducted from
    /// `Invoice::zahlbetrag_eur`.
    #[must_use]
    pub fn total_abschlage_eur(&self) -> Decimal {
        self.abschlage.iter().map(|a| a.betrag_eur).sum()
    }

    /// Return `(active_days, total_days)` for use with `billing::prorate` /
    /// `billing::prorate_amount`.
    ///
    /// - `total_days` = calendar days in the billing period (`days()`)
    /// - `active_days` = billable days after clipping to `vertragsbeginn` /
    ///   `vertragsende`
    ///
    /// When no pro-rata applies (full period billable), `active_days == total_days`.
    /// When the period would yield zero billable days, returns `(0, total_days)`.
    ///
    /// ## Example — Grundpreis pro-rata
    ///
    /// ```rust
    /// # use energy_billing::{BillingContext, BillingPeriod};
    /// # use time::macros::date;
    /// let ctx = BillingContext {
    ///     period: BillingPeriod::new(date!(2026-01-01), date!(2026-01-31)).unwrap(),
    ///     vertragsbeginn: Some(date!(2026-01-16)),
    ///     ..Default::default()
    /// };
    /// let (active, total) = ctx.prorate_days();
    /// assert_eq!(total, 31);
    /// assert_eq!(active, 16); // Jan 16–31
    /// ```
    #[must_use]
    pub fn prorate_days(&self) -> (u32, u32) {
        let total = self.days().max(0) as u32;
        if total == 0 {
            return (0, 1);
        }
        // Effective start: max(period_from, vertragsbeginn)
        let effective_from = self
            .vertragsbeginn
            .filter(|&vb| vb > self.period_from())
            .unwrap_or(self.period_from());
        // Effective end: min(period_to, vertragsende)
        let effective_to = self
            .vertragsende
            .filter(|&ve| ve < self.period_to())
            .unwrap_or(self.period_to());
        let active = ((effective_to - effective_from).whole_days() + 1).max(0) as u32;
        (active.min(total), total)
    }

    /// The active contract window inside the billing period.
    ///
    /// `(from, to)` clipped by `vertragsbeginn` / `vertragsende`, inclusive.
    /// Returns `None` when the contract does not overlap the period at all.
    #[must_use]
    pub fn active_window(&self) -> Option<(time::Date, time::Date)> {
        let from = self
            .vertragsbeginn
            .filter(|&vb| vb > self.period_from())
            .unwrap_or(self.period_from());
        let to = self
            .vertragsende
            .filter(|&ve| ve < self.period_to())
            .unwrap_or(self.period_to());
        (from <= to).then_some((from, to))
    }

    /// The billed period expressed in **months**, for EUR/month rates.
    ///
    /// Each calendar month contributes `billed days ÷ that month's length`, so
    /// January 1–31 is exactly `1`, a full year is exactly `12`, and a
    /// mid-month move-in gets the fraction of the month it actually occupied —
    /// none of which `days ÷ 30.4375` produces (it makes a billed January
    /// 1.0185 months, and a leap year 12.0164).
    ///
    /// Clipped to the active contract window, like every other periodic charge.
    #[must_use]
    pub fn billed_months(&self) -> rust_decimal::Decimal {
        use rust_decimal::Decimal;
        let Some((from, to)) = self.active_window() else {
            return Decimal::ZERO;
        };
        let mut months = Decimal::ZERO;
        let mut cursor = from;
        while cursor <= to {
            let len = time::util::days_in_month(cursor.month(), cursor.year());
            let month_end = time::Date::from_calendar_date(cursor.year(), cursor.month(), len)
                .expect("last day of the month is a valid date");
            let slice_end = month_end.min(to);
            let days = (slice_end - cursor).whole_days() + 1;
            months += Decimal::from(days) / Decimal::from(len);
            let Some(next) = month_end.next_day() else {
                break;
            };
            cursor = next;
        }
        months
    }

    /// The billed period expressed in **years**, for EUR/year rates.
    ///
    /// Leap-aware: each calendar year contributes `billed days ÷ that year's
    /// length`, so 2024 divides by 366 and 2025 by 365.
    #[must_use]
    pub fn billed_years(&self) -> rust_decimal::Decimal {
        use rust_decimal::Decimal;
        let Some((from, to)) = self.active_window() else {
            return Decimal::ZERO;
        };
        let mut years = Decimal::ZERO;
        let mut cursor = from;
        while cursor <= to {
            let len = time::util::days_in_year(cursor.year());
            let year_end = time::Date::from_calendar_date(cursor.year(), time::Month::December, 31)
                .expect("31 December is a valid date");
            let slice_end = year_end.min(to);
            let days = (slice_end - cursor).whole_days() + 1;
            years += Decimal::from(days) / Decimal::from(len);
            let Some(next) = year_end.next_day() else {
                break;
            };
            cursor = next;
        }
        years
    }
}

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

    fn ctx(from: time::Date, to: time::Date) -> BillingContext {
        BillingContext {
            period: BillingPeriod::new(from, to).expect("period"),
            ..Default::default()
        }
    }

    /// The property `days ÷ 30.4375` cannot have: calendar-aligned periods come
    /// out exact.
    #[test]
    fn calendar_aligned_periods_are_exact() {
        assert_eq!(
            ctx(date!(2026 - 01 - 01), date!(2026 - 01 - 31)).billed_months(),
            dec!(1)
        );
        assert_eq!(
            ctx(date!(2026 - 02 - 01), date!(2026 - 02 - 28)).billed_months(),
            dec!(1)
        );
        assert_eq!(
            ctx(date!(2026 - 01 - 01), date!(2026 - 12 - 31)).billed_months(),
            dec!(12)
        );
        // …in a leap year too, where 366 ÷ 30.4375 would be 12.0246.
        assert_eq!(
            ctx(date!(2024 - 01 - 01), date!(2024 - 12 - 31)).billed_months(),
            dec!(12)
        );
        assert_eq!(
            ctx(date!(2024 - 01 - 01), date!(2024 - 12 - 31)).billed_years(),
            dec!(1)
        );
    }

    /// A mid-month move-in pays for the part of that month it occupied.
    #[test]
    fn a_partial_month_is_that_months_own_fraction() {
        // 16–31 January = 16 of 31 days.
        let c = BillingContext {
            period: BillingPeriod::new(date!(2026 - 01 - 01), date!(2026 - 01 - 31)).unwrap(),
            vertragsbeginn: Some(date!(2026 - 01 - 16)),
            ..Default::default()
        };
        assert_eq!(c.billed_months(), dec!(16) / dec!(31));
        // …and February's 13 days are 13/28, not 13/30.4375.
        let c = ctx(date!(2026 - 02 - 16), date!(2026 - 02 - 28));
        assert_eq!(c.billed_months(), dec!(13) / dec!(28));
    }

    /// A contract that ended before the period began bills nothing.
    #[test]
    fn a_closed_contract_bills_no_months() {
        let c = BillingContext {
            period: BillingPeriod::new(date!(2026 - 03 - 01), date!(2026 - 03 - 31)).unwrap(),
            vertragsende: Some(date!(2026 - 02 - 10)),
            ..Default::default()
        };
        assert_eq!(c.active_window(), None);
        assert_eq!(c.billed_months(), rust_decimal::Decimal::ZERO);
        assert_eq!(c.billed_years(), rust_decimal::Decimal::ZERO);
    }
}

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

    fn ctx(period_to: time::Date, issue: Option<time::Date>) -> BillingContext {
        BillingContext {
            period: BillingPeriod::new(date!(2026 - 01 - 01), period_to).expect("period"),
            issue_date: issue,
            ..Default::default()
        }
    }

    #[test]
    fn without_a_clock_the_period_end_stands_in_for_the_issue_date() {
        // The library is pure; a caller with no clock still gets a document.
        let c = ctx(date!(2026 - 01 - 31), None);
        assert_eq!(c.ausstellungsdatum(), date!(2026 - 01 - 31));
        assert_eq!(c.faelligkeitsdatum(), date!(2026 - 02 - 14));
    }

    #[test]
    fn the_due_date_runs_from_the_issue_date_not_the_period_end() {
        // § 40c Abs. 1 EnWG measures the two weeks from when the payment
        // request reaches the customer, so a catch-up run billing an old period
        // must date the Fälligkeit from the issue date. Measuring from the
        // period end would deliver a document overdue on arrival, and the
        // dunning downstream would act on it.
        let c = ctx(date!(2026 - 01 - 31), Some(date!(2026 - 06 - 10)));
        assert_eq!(c.ausstellungsdatum(), date!(2026 - 06 - 10));
        assert_eq!(c.faelligkeitsdatum(), date!(2026 - 06 - 24));
        assert!(
            c.faelligkeitsdatum() > c.ausstellungsdatum(),
            "an invoice is never due before it is issued"
        );
    }
}

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

    fn base_ctx() -> BillingContext {
        BillingContext {
            period: BillingPeriod::new(date!(2026 - 01 - 01), date!(2026 - 01 - 31)).unwrap(),
            ..Default::default()
        }
    }

    #[test]
    fn days_full_january() {
        assert_eq!(base_ctx().days(), 31);
    }

    #[test]
    fn billing_days_fraction_no_pro_rata_returns_none() {
        assert!(base_ctx().billing_days_fraction().is_none());
    }

    #[test]
    fn billing_days_fraction_mid_month_start() {
        let ctx = BillingContext {
            vertragsbeginn: Some(date!(2026 - 01 - 16)),
            ..base_ctx()
        };
        let frac = ctx.billing_days_fraction().unwrap();
        // billable: Jan 16..31 = 16 days out of 31
        let expected = Decimal::from(16) / Decimal::from(31);
        assert_eq!(frac, expected.round_kfm(6));
    }

    #[test]
    fn billing_days_fraction_mid_month_end() {
        let ctx = BillingContext {
            vertragsende: Some(date!(2026 - 01 - 15)),
            ..base_ctx()
        };
        let frac = ctx.billing_days_fraction().unwrap();
        // billable: Jan 01..15 = 15 days out of 31
        let expected = Decimal::from(15) / Decimal::from(31);
        assert_eq!(frac, expected.round_kfm(6));
    }

    #[test]
    fn total_abschlage_sums_correctly() {
        let ctx = BillingContext {
            abschlage: vec![
                AbschlagDeduction {
                    datum: date!(2026 - 01 - 15),
                    betrag_eur: dec!(100.00),
                    ust_satz: dec!(0.19),
                    beschreibung: None,
                },
                AbschlagDeduction {
                    datum: date!(2026 - 02 - 15),
                    betrag_eur: dec!(120.00),
                    ust_satz: dec!(0.19),
                    beschreibung: None,
                },
            ],
            ..base_ctx()
        };
        assert_eq!(ctx.total_abschlage_eur(), dec!(220.00));
    }
}