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
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
//! `Quantities` — all metered quantities for one billing period.
//!
//! The single container for all product meter data. Replaces positional
//! parameters passed to each `calculate_*` function.

use crate::rates::RoundMoney;
use rust_decimal::Decimal;
use std::collections::HashMap;
use time::OffsetDateTime;

// ── Meter input types ─────────────────────────────────────────────────────────

/// Metering mode of the delivery point (§3/§ 12 StromNZV, §41a EnWG).
///
/// Determines billing granularity, permissible tariff types, and substitution
/// rules for missing interval data.
///
/// | Mode | Annual consumption | Billing basis | §41a dynamic tariff |
/// |---|---|---|---|
/// | `Slp` | < 100 MWh/year | Standard load profile (estimated) | ✗ |
/// | `Rlm` | ≥ 100 MWh/year | Registered 15-min values | ✗ |
/// | `Imsys` | ≥ 6 MWh/year (§31 MsbG) | Smart Meter Gateway | ✓ |
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, Default)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum MeteringMode {
    /// Standard load profile (SLP) — estimated annual consumption billing.
    /// Typical for residential and small commercial customers (< 100 MWh/year).
    #[default]
    Slp,
    /// Registrierende Leistungsmessung (RLM) — measured 15-minute interval billing.
    /// Required for customers ≥ 100 MWh/year (§ 12 StromNZV, §14 NAV).
    Rlm,
    /// Intelligentes Messsystem (iMSys) — Smart Meter Gateway.
    /// Enables §41a EnWG dynamic tariffs. Required for > 6 MWh/year (§31 MsbG).
    Imsys,
}

/// How the meter reading on the invoice was obtained.
///
/// **§ 40 Abs. 2 Nr. 6 EnWG** requires a consumption invoice to state the
/// opening and closing readings, the consumption derived from them, *and* "die
/// Art, wie der Zählerstand ermittelt wurde". The third of those is a distinct
/// duty: a customer reading an invoice has to be able to tell a remote read-out
/// from a self-reported figure from an estimate, because what they can do about
/// a wrong number differs in each case.
///
/// `is_estimated` alone cannot carry it — it distinguishes an estimate from
/// everything else and says nothing about what "everything else" was.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Ablesungsart {
    /// Not stated. The invoice then omits the Nr. 6 sentence — which is a gap
    /// in the data, not a shape the statute permits, so `billingd` warns.
    #[default]
    Unbekannt,
    /// Ferngelesen — read out over the iMSys/Smart-Meter-Gateway.
    Fernauslesung,
    /// Read on site by the Messstellenbetreiber or their agent.
    Abgelesen,
    /// Self-reported by the customer (Selbstablesung).
    Kundenselbstablesung,
    /// Estimated under § 40a Abs. 2 EnWG, or an Ersatzwert taken over under
    /// § 40a Abs. 1 Satz 1 Nr. 1 EnWG.
    Rechnerisch,
}

impl Ablesungsart {
    /// The wording that goes on the invoice, or `None` when unstated.
    #[must_use]
    pub const fn label(self) -> Option<&'static str> {
        match self {
            Self::Unbekannt => None,
            Self::Fernauslesung => Some("ferngelesen"),
            Self::Abgelesen => Some("abgelesen durch den Messstellenbetreiber"),
            Self::Kundenselbstablesung => Some("Selbstablesung durch den Kunden"),
            Self::Rechnerisch => Some("rechnerisch ermittelt (Schätzung)"),
        }
    }

    /// `true` when the figure is not a measured reading.
    #[must_use]
    pub const fn is_estimate(self) -> bool {
        matches!(self, Self::Rechnerisch)
    }
}

/// Electricity meter data for one billing period.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct MeterInput {
    /// Total energy in kWh (Arbeitsmenge).
    #[serde(default)]
    pub arbeitsmenge_kwh: Decimal,
    /// High-tariff energy in kWh (HT, for Zweitarif). `None` = single tariff.
    #[serde(default)]
    pub arbeitsmenge_ht_kwh: Option<Decimal>,
    /// Low-tariff energy in kWh (NT, for Zweitarif). `None` = single tariff.
    #[serde(default)]
    pub arbeitsmenge_nt_kwh: Option<Decimal>,
    /// Peak demand in kW (Spitzenleistung, § 12 StromNZV).
    #[serde(default)]
    pub spitzenleistung_kw: Option<Decimal>,
    /// §14a EnWG: hours the controllable device was under NB management.
    #[serde(default)]
    pub steuerung_stunden: Option<Decimal>,
    /// Zählernummer (§41 EnWG — mandatory on electricity invoices).
    ///
    /// When set, appears as an informational position on the invoice.
    /// Overrides `BillingContext::zaehler_id` for this specific meter.
    #[serde(default)]
    pub zaehlernummer: Option<String>,
    /// Zählerstand at the start of the billing period.
    ///
    /// §41 EnWG: billing invoices must show the meter reading at period start.
    #[serde(default)]
    pub zaehlerstand_von: Option<Decimal>,
    /// Zählerstand at the end of the billing period.
    ///
    /// §41 EnWG: billing invoices must show the meter reading at period end.
    #[serde(default)]
    pub zaehlerstand_bis: Option<Decimal>,

    /// Metering mode — SLP, RLM, or iMSys (Smart Meter).
    ///
    /// Used to validate tariff compatibility (§41a requires `Imsys`) and to
    /// label estimated readings correctly on the invoice.
    #[serde(default)]
    pub metering_mode: MeteringMode,

    /// § 40 Abs. 2 Nr. 6 EnWG — how the reading was obtained.
    ///
    /// See also [`MeterInput::billable_kwh`], which is what decides whether
    /// there is any consumption to price.
    ///
    /// Stated on the invoice beside the readings themselves. `Rechnerisch`
    /// implies [`Self::is_estimated`]; the two are kept separate because a
    /// caller that knows only "this is an estimate" can still say so.
    #[serde(default)]
    pub ablesungsart: Ablesungsart,

    /// `true` when the consumption figure is an estimate rather than a reading —
    /// either a § 40a Abs. 2 EnWG Verbrauchsschätzung or an Ersatzwert the
    /// Messstellenbetreiber formed and passed on under § 40a Abs. 1 Satz 1
    /// Nr. 1 EnWG.
    ///
    /// § 40a Abs. 2 Satz 3 EnWG has the invoice state the estimate, the ground
    /// that makes it admissible and the factors behind it „unter ausdrücklichem
    /// und optisch besonders hervorgehobenem Hinweis".
    #[serde(default)]
    pub is_estimated: bool,

    /// `true` when the meter was replaced during this billing period (Zählerwechsel).
    ///
    /// When set, `zaehlerstand_von` / `zaehlerstand_bis` may relate to different
    /// meter serial numbers. The invoice must note the meter exchange.
    #[serde(default)]
    pub zaehler_replaced: bool,

    /// Share of the billing period covered by billable readings, 0–100.
    ///
    /// A sum over the readings that did arrive says nothing about the ones that
    /// did not: a month delivered up to the 3rd sums to a plausible Arbeitsmenge
    /// and bills as a complete month. Below 100 the invoice rests in part on a
    /// § 40a Abs. 2 EnWG Verbrauchsschätzung, which the document has to say so
    /// prominently — the `MENGE_UNVOLLSTAENDIG` finding carries that.
    ///
    /// `None` when the source states no coverage.
    #[serde(default)]
    pub coverage_pct: Option<Decimal>,
}

impl MeterInput {
    /// The consumption there is to price, in kWh.
    ///
    /// `arbeitsmenge_kwh` where it is stated, otherwise the HT/NT registers.
    /// A Zweitarif caller may legitimately supply only the split — the total is
    /// its sum, not an independent fact — and gating the whole Arbeitspreis
    /// block on the total alone billed such a customer nothing for their
    /// electricity while still charging them the Stromsteuer.
    #[must_use]
    pub fn billable_kwh(&self) -> Decimal {
        if self.arbeitsmenge_kwh > Decimal::ZERO {
            return self.arbeitsmenge_kwh;
        }
        self.arbeitsmenge_ht_kwh.unwrap_or(Decimal::ZERO)
            + self.arbeitsmenge_nt_kwh.unwrap_or(Decimal::ZERO)
    }
}

/// Gas meter data for one billing period.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct GasMeterInput {
    /// Share of the billing period covered by billable readings, 0–100.
    ///
    /// See [`MeterInput::coverage_pct`].
    #[serde(default)]
    pub coverage_pct: Option<Decimal>,
    /// Volume at meter conditions (m³).
    pub messung_qm3: Decimal,
    /// Calorific value (Brennwert Ho/Hs) in kWh/m³.
    #[serde(default)]
    pub brennwert_kwh_per_qm3: Option<Decimal>,
    /// Volume conversion factor (Zustandszahl, dimensionless).
    #[serde(default)]
    pub zustandszahl: Option<Decimal>,
    /// Pre-computed kWh_Hs (takes precedence over Brennwert × Zustandszahl).
    #[serde(default)]
    pub kwh_hs: Option<Decimal>,
    /// Gas quality annotation (e.g. `"H_GAS"`, `"L_GAS"`, `"H2_BLEND"`).
    /// Informational only — billing always uses the measured Brennwert.
    #[serde(default)]
    pub gasqualitaet: Option<String>,
    /// Peak demand in kW (Spitzenleistung) for RLM gas billing.
    ///
    /// Required when `TariffInput::gas_leistungspreis_ct_per_kw_month` is set.
    /// Applicable to large gas customers with RLM metering (> 1.5 GWh/year).
    #[serde(default)]
    pub spitzenleistung_kw: Option<Decimal>,
    /// Zählernummer (§40 Abs. 2 Nr. 6 EnWG — meter identity on the bill).
    /// Overrides `BillingContext::zaehler_id` for this meter.
    #[serde(default)]
    pub zaehlernummer: Option<String>,
    /// Meter reading at period start, in m³ (§40 Abs. 2 Nr. 6 EnWG).
    #[serde(default)]
    pub zaehlerstand_von: Option<Decimal>,
    /// Meter reading at period end, in m³ (§40 Abs. 2 Nr. 6 EnWG).
    #[serde(default)]
    pub zaehlerstand_bis: Option<Decimal>,
    /// § 40 Abs. 2 Nr. 6 EnWG — how the reading was obtained.
    #[serde(default)]
    pub ablesungsart: Ablesungsart,
    /// Reading is an estimate / Ersatzwert (§ 40a Abs. 2 EnWG).
    /// Must be prominently labeled on the bill; the customer may demand a
    /// correction once a real reading arrives.
    #[serde(default)]
    pub is_estimated: bool,
}

/// Reason a metered water volume did not reach the sewer.
///
/// Absetzungen reduce the **Schmutzwasser** volume only (Frischwassermaßstab:
/// every m³ of drinking water counts as sewage unless proven otherwise via a
/// calibrated deduction meter) — the Trinkwasser delivery itself is always
/// billed in full.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AbsetzungsGrund {
    /// Garden irrigation via Gartenwasserzähler.
    Gartenwasser,
    /// Water carried away in products or processes (Schleppwasser).
    Schleppwasser,
    /// Evaporation losses (e.g. cooling towers).
    Verdunstung,
    /// Water bound in production output.
    Produktionswasser,
    /// Other municipally recognised deduction.
    Sonstige,
}

impl AbsetzungsGrund {
    /// German label for position texts.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Gartenwasser => "Gartenwasser",
            Self::Schleppwasser => "Schleppwasser",
            Self::Verdunstung => "Verdunstung",
            Self::Produktionswasser => "Produktionswasser",
            Self::Sonstige => "sonstige Absetzung",
        }
    }
}

/// One metered non-discharged water volume (Absetzung).
///
/// Municipal statutes require a separately installed, calibrated meter
/// (geeichter Absetzungszähler) for each deduction.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Absetzung {
    /// Metered volume in m³.
    pub m3: Decimal,
    /// Why the volume never reached the sewer.
    pub grund: AbsetzungsGrund,
}

/// Water / wastewater meter and property data (WASSER).
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct WasserMeterInput {
    /// Drinking water delivered in m³ — the basis for the Trinkwasser
    /// Mengenpreis **and** (minus Absetzungen) the Schmutzwasser volume.
    #[serde(default)]
    pub frischwasser_m3: Decimal,
    /// Metered non-discharged volumes, deducted from Schmutzwasser only.
    #[serde(default)]
    pub absetzungen: Vec<Absetzung>,
    /// Sealed surface area (m²) draining into the sewer — the
    /// Niederschlagswasser base of the gesplittete Abwassergebühr.
    #[serde(default)]
    pub versiegelte_flaeche_m2: Option<Decimal>,
    /// Pro-rata months (defaults to 1 = one full billing month).
    #[serde(default)]
    pub months: Option<Decimal>,
}

impl WasserMeterInput {
    /// Total metered Absetzung volume in m³.
    #[must_use]
    pub fn absetzung_total_m3(&self) -> Decimal {
        self.absetzungen.iter().map(|a| a.m3).sum()
    }
}

/// District heat meter data.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct WaermeMeterInput {
    /// Thermal energy delivered (kWh_th).
    #[serde(default)]
    pub kwh_waerme: Decimal,
    /// Peak demand in kW (for Leistungspreis billing).
    #[serde(default)]
    pub spitzenleistung_kw: Option<Decimal>,
    /// Pro-rata months (defaults to 1 = one full billing month).
    #[serde(default)]
    pub months: Option<Decimal>,
}

/// Solar / Eigenverbrauch / Mieterstrom / GGV meter data.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct SolarMeterInput {
    /// Metered self-consumption or locally delivered kWh.
    pub eigenverbrauch_kwh: Decimal,
}

// ── GGV Nutzungsplan ──────────────────────────────────────────────────────────

/// §42b EnWG — One entry in the GGV Nutzungsplan (tenant allocation table).
///
/// The Nutzungsplan distributes the plant's PV generation among participating
/// building occupants (Teilnehmer). Each entry maps one Marktlokation (tenant
/// delivery point) to its allocation fraction.
///
/// ## Legal basis
///
/// §42b Abs. 1 EEG 2023 (Solarpaket I): the Lieferant must maintain a Nutzungsplan
/// for the duration of the GGV contract. The sum of all fractions must equal 1.0.
///
/// ## Storage
///
/// Stored as `ggv_nutzungsplan JSONB` on `eeg_anlagen` (migration 0009).
/// Deserialize with `serde_json::from_value::<Vec<GgvNutzungsplanEntry>>(...)`.
///
/// ## Example
///
/// ```rust
/// use energy_billing::GgvNutzungsplanEntry;
/// use rust_decimal::dec;
///
/// let plan = vec![
///     GgvNutzungsplanEntry { malo_id: "51238696012".into(), fraction: dec!(0.45) },
///     GgvNutzungsplanEntry { malo_id: "51238696012".into(), fraction: dec!(0.35) },
///     GgvNutzungsplanEntry { malo_id: "51238696799".into(), fraction: dec!(0.20) },
/// ];
/// let total: rust_decimal::Decimal = plan.iter().map(|e| e.fraction).sum();
/// assert_eq!(total, dec!(1.0));
/// ```
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct GgvNutzungsplanEntry {
    /// 11-digit Marktlokations-ID of the tenant delivery point.
    pub malo_id: String,

    /// Fraction of PV generation allocated to this tenant (0.0 < fraction ≤ 1.0).
    ///
    /// The sum of all fractions in the Nutzungsplan must equal exactly 1.0.
    /// Validate with `GgvNutzungsplan::validate()` before billing.
    pub fraction: Decimal,
}

/// §42b EnWG — GGV Nutzungsplan (complete tenant allocation table).
///
/// Wraps the list of entries and provides validation and allocation computation.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GgvNutzungsplan(pub Vec<GgvNutzungsplanEntry>);

impl GgvNutzungsplan {
    /// Validate that all fractions are positive and sum to 1.0 (within 0.001 tolerance).
    ///
    /// Returns `Err` with a diagnostic message if validation fails.
    pub fn validate(&self) -> Result<(), String> {
        use rust_decimal::dec;
        if self.0.is_empty() {
            return Err("GGV Nutzungsplan must have at least one entry".to_owned());
        }
        for e in &self.0 {
            if e.fraction <= Decimal::ZERO {
                return Err(format!(
                    "GGV Nutzungsplan: fraction for {} must be > 0, got {}",
                    e.malo_id, e.fraction
                ));
            }
        }
        let total: Decimal = self.0.iter().map(|e| e.fraction).sum();
        let diff = (total - Decimal::ONE).abs();
        if diff > dec!(0.001) {
            return Err(format!(
                "GGV Nutzungsplan: fractions sum to {total}, must be 1.0 (±0.001)"
            ));
        }
        Ok(())
    }

    /// Validate that the plan allocates PV to exactly `tenants`, no more and no
    /// less.
    ///
    /// Fractions summing to 1.0 says nothing about *who* they cover: a plan that
    /// omits a tenant is internally consistent, and the omitted tenant silently
    /// falls out of the allocation — billed as if their whole consumption were
    /// self-consumed solar, with no grid residual and no Stromsteuer. §42b Abs. 1
    /// EEG 2023 requires the Nutzungsplan to cover the community for the duration
    /// of the contract, so a mismatch is a configuration error, not a default.
    ///
    /// A MaLo appearing twice is also rejected: the allocation is keyed on the
    /// MaLo, so a duplicate entry loses one of the two shares.
    pub fn validate_covers<'a>(
        &self,
        tenants: impl IntoIterator<Item = &'a str>,
    ) -> Result<(), String> {
        use std::collections::BTreeSet;
        let mut planned: BTreeSet<&str> = BTreeSet::new();
        for e in &self.0 {
            if !planned.insert(e.malo_id.as_str()) {
                return Err(format!(
                    "GGV Nutzungsplan: MaLo {} appears more than once",
                    e.malo_id
                ));
            }
        }
        let tenants: BTreeSet<&str> = tenants.into_iter().collect();
        let missing: Vec<&str> = tenants.difference(&planned).copied().collect();
        if !missing.is_empty() {
            return Err(format!(
                "GGV Nutzungsplan: no entry for {} — every tenant must be allocated \
                 (§42b Abs. 1 EEG 2023)",
                missing.join(", ")
            ));
        }
        let extra: Vec<&str> = planned.difference(&tenants).copied().collect();
        if !extra.is_empty() {
            return Err(format!(
                "GGV Nutzungsplan: {} is allocated PV but is not a tenant of this run",
                extra.join(", ")
            ));
        }
        Ok(())
    }

    /// Allocate a generation quantity proportionally among tenants.
    ///
    /// Returns `(malo_id, allocated_kwh)` pairs.
    ///
    /// Uses `billing::proportional_split` (Largest-Remainder / Hamilton method) —
    /// guarantees `Σ(allocated_kwh) == total_kwh` with each tenant within
    /// ±0.001 kWh of their exact share. No single entry absorbs all rounding error.
    ///
    /// # Errors
    ///
    /// [`crate::error::EngineError::NutzungsplanSharesInvalid`] when the shares do not sum to
    /// one closely enough for the split to distribute the whole generation. The
    /// shares are caller-supplied — a plan entered as percentages sums to 100 —
    /// so this is a configuration error the caller must see, not an arithmetic
    /// failure to absorb.
    pub fn allocate(
        &self,
        total_kwh: Decimal,
    ) -> Result<Vec<(String, Decimal)>, crate::EngineError> {
        if self.0.is_empty() || total_kwh <= Decimal::ZERO {
            return Ok(vec![]);
        }
        let fractions: Vec<Decimal> = self.0.iter().map(|e| e.fraction).collect();
        // billing::proportional_split uses Largest-Remainder (Hamilton) method:
        // scale=3 → 0.001 kWh resolution.
        let parts = billing::proportional_split(total_kwh, &fractions, 3).map_err(|_| {
            crate::EngineError::NutzungsplanSharesInvalid {
                sum: fractions.iter().copied().sum(),
            }
        })?;
        Ok(self
            .0
            .iter()
            .zip(parts)
            .map(|(e, kwh)| (e.malo_id.clone(), kwh))
            .collect())
    }
}

/// EEG feed-in settlement meter data (simplified LF view).
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct EegMeterInput {
    /// Total kWh fed into the grid during the billing period.
    pub einspeisung_kwh: Decimal,
    /// kWh during negative-EPEX hours (§51 EEG suspension).
    #[serde(default)]
    pub kwh_during_negative_epex: Option<Decimal>,
}

/// HEMS (Home Energy Management System) subscription usage.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct HemsMeterInput {
    /// Billing months (for monthly subscription fee).
    #[serde(default)]
    pub months: Option<Decimal>,
    /// Number of optimisation events.
    #[serde(default)]
    pub optimization_events: Option<u32>,
    /// Number of smart-meter readout events.
    #[serde(default)]
    pub readout_events: Option<u32>,
}

/// E-Mobility CPO/EMSP usage data.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct EmobilityMeterInput {
    #[serde(default)]
    pub months: Option<Decimal>,
    #[serde(default)]
    pub kwh_charged: Option<Decimal>,
    #[serde(default)]
    pub sessions: Option<u32>,
    #[serde(default)]
    pub roaming_sessions: Option<u32>,
}

/// Energiedienstleistung service usage.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct ServiceMeterInput {
    #[serde(default)]
    pub months: Option<Decimal>,
    #[serde(default)]
    pub event_count: Option<u32>,
    #[serde(default)]
    pub event_price_eur: Option<Decimal>,
}

/// One interval for §41a dynamic tariff billing.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DynamicInterval {
    /// Interval start (UTC).
    #[serde(with = "time::serde::rfc3339")]
    pub timestamp_utc: OffsetDateTime,
    /// Energy in kWh for this interval.
    pub kwh: Decimal,
}

// ── §41a Abs. 6 — Annual savings comparison ───────────────────────────────────

/// §41a Abs. 6 EnWG — Annual savings comparison for dynamic tariff customers.
///
/// Lieferanten must provide dynamic tariff customers with an annual statement
/// of how much they saved (or paid more) compared to a reference fixed tariff.
///
/// ## Legal basis
///
/// §41a Abs. 6 EnWG: „Der Lieferant hat dem Letztverbraucher jährlich mitzuteilen,
/// wie viel er durch die dynamische Preiskomponente im Vergleich zu einem
/// Standardtarif eingespart oder mehr ausgegeben hat."
///
/// ## Usage
///
/// Compute via [`Sect41aAnnualComparison::compute`] and set in [`Quantities`].
/// `DynamicElectricityProvider` renders it as an informational position on the
/// annual invoice.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Sect41aAnnualComparison {
    /// kWh consumed under the dynamic tariff in the comparison period.
    pub actual_kwh: Decimal,
    /// Total amount paid under the dynamic tariff (EUR brutto, inclusive of MwSt).
    pub actual_eur_brutto: Decimal,
    /// Reference fixed-price (ct/kWh, brutto) for the annual comparison.
    ///
    /// Typically the customer's previous fixed tariff or the operator's standard
    /// product price at time of dynamic tariff contract start.
    pub reference_price_ct_per_kwh: Decimal,
    /// What the customer would have paid at the reference price (EUR brutto).
    pub reference_eur_brutto: Decimal,
    /// EUR difference: positive = saved money, negative = paid more.
    pub savings_eur: Decimal,
}

impl Sect41aAnnualComparison {
    /// Compute the annual comparison from actual totals and a reference price.
    #[must_use]
    pub fn compute(
        actual_kwh: Decimal,
        actual_eur_brutto: Decimal,
        reference_price_ct_per_kwh: Decimal,
    ) -> Self {
        use rust_decimal::dec;
        let reference_eur_brutto =
            (actual_kwh * reference_price_ct_per_kwh / dec!(100)).round_kfm(2);
        let savings_eur = (reference_eur_brutto - actual_eur_brutto).round_kfm(2);
        Self {
            actual_kwh,
            actual_eur_brutto,
            reference_price_ct_per_kwh,
            reference_eur_brutto,
            savings_eur,
        }
    }
}

// ── Grid pass-through costs ───────────────────────────────────────────────────

/// Grid infrastructure charges sourced from `marktd` or supplied directly.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct GridInput {
    // ── Strom ─────────────────────────────────────────────────────────────────
    #[serde(default)]
    pub nne_grundpreis_eur_per_year: Option<Decimal>,
    #[serde(default)]
    pub nne_arbeitspreis_ct_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub nne_leistungspreis_eur_per_kw_year: Option<Decimal>,
    #[serde(default)]
    pub ka_ct_per_kwh: Option<Decimal>,
    // ── Gas ───────────────────────────────────────────────────────────────────
    #[serde(default)]
    pub gas_nne_grundpreis_eur_per_year: Option<Decimal>,
    #[serde(default)]
    pub gas_nne_arbeitspreis_ct_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub gas_ka_ct_per_kwh: Option<Decimal>,
    #[serde(default)]
    pub gas_bilanzierungsumlage_ct_per_kwh: Option<Decimal>,
}

// ── EnergyShareMeterInput ─────────────────────────────────────────────────────

/// §42c EnWG Energy Sharing — metered allocation for one community participant.
///
/// Populated by `billingd` from the participant's virtual meter (Summenzeitreihe)
/// computed by `edmd` using the community's `AggregationRule::GgvConstantAllocation`
/// or `GgvProportionalAllocation` (same infrastructure as §42b EnWG GGV).
///
/// ## §42c EnWG vs §42b EnWG GGV
///
/// | | §42b EnWG GGV (Solarpaket I) | §42c Energiegemeinschaft |
/// |---|---|---|
/// | Scope | Building community | Grid area (0.4 kV) |
/// | Participants | Tenants in same building | Up to 100 members |
/// | Plant size | No limit | ≤ 500 kW total |
/// | Metering | Building meter | Smart meter (iMSys) mandatory |
/// | LF billing | via SolarProvider | via EnergyShareProvider |
///
/// ## Billing model
///
/// The LF bills the full grid consumption (via `ElectricityProvider`) and then
/// credits the sharing allocation (via `EnergyShareProvider`) at the contracted
/// rate — typically below the retail tariff and above the wholesale price.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct EnergyShareMeterInput {
    /// kWh allocated from the community energy pool to this participant.
    ///
    /// Computed from the community's total generation and this participant's
    /// allocation fraction (`GgvConstantAllocation.fraction` or proportional ratio).
    /// Limited to the participant's actual consumption (§42c cap clause).
    pub allocated_kwh: Decimal,

    /// Total generation from the community's shared plant (kWh).
    ///
    /// Rendered as an informational position: a participant cannot check their
    /// own allocation without the total it was taken from.
    #[serde(default)]
    pub total_plant_generation_kwh: Option<Decimal>,

    /// Participant's allocation fraction (0.0–1.0).
    ///
    /// Rendered as an informational position — the other half of the same
    /// check: fraction × total should be the allocated kWh, and a participant
    /// who can see both can verify it.
    #[serde(default)]
    pub allocation_fraction: Option<Decimal>,

    /// The community's own identifier, as the operator runs it.
    ///
    /// Rendered on the invoice so a participant in more than one arrangement
    /// can tell which credit belongs to which. **Not** a statutory registration
    /// number: § 42c EnWG contains no BNetzA/Marktstammdatenregister
    /// registration duty for the community.
    #[serde(default)]
    pub gemeinschaft_id: Option<String>,
}

// ── Apportioning a period total across the legs of a split period ─────────────

/// How one leg of a split billing period takes its share of a period total.
///
/// A period is billed in legs wherever a Tarifwechsel or a statutory rate
/// boundary falls inside it, and each leg is priced at its own tariff and its
/// own rates. A quantity the caller states **once for the whole period** then
/// has to reach them: charged in full on every leg it is billed once per leg,
/// and charged in full on one it prices the whole period at that leg's tariff.
///
/// mako apportions it by **calendar days**. The legs of a period are
/// consecutive and non-overlapping, so their day counts are the only ratio
/// available without a second reading, and a standing-charge-plus-consumption
/// supply is what the day ratio describes. It is an apportionment and not a
/// measurement: a caller holding real per-leg readings supplies those instead,
/// and a caller that cannot is told so rather than having a reading invented
/// for it — [`Quantities`] carries no per-leg register values.
///
/// Additive quantities — kWh, m³, months, event counts — are apportioned. A
/// figure that is not a sum over the period's days is carried whole: a peak
/// demand is the highest interval of the period and is the highest interval of
/// whichever leg contains it, a sealed surface is a property of the premises,
/// and a unit price is a price.
///
/// The shares are split with [`billing::proportional_split`]
/// (Largest-Remainder), so the legs of a period sum back to the caller's total
/// exactly rather than to it plus a rounding residue.
#[derive(Debug, Clone)]
pub struct DayApportionment {
    /// Days per leg, in order.
    days: Vec<Decimal>,
    /// Which leg this apportionment speaks for.
    index: usize,
}

/// Decimals kept when apportioning a quantity: 0.001 kWh / m³ / month.
const QUANTITY_SCALE: u32 = 3;

impl DayApportionment {
    /// The apportionment for leg `index` of a period whose legs run `days` days.
    ///
    /// Falls back to [`Self::whole`] when the shape cannot be apportioned —
    /// no legs, an out-of-range index, or a period of no days at all — so a
    /// caller never has to choose between a panic and a silently dropped
    /// quantity.
    #[must_use]
    pub fn new(days: &[u32], index: usize) -> Self {
        let total: u64 = days.iter().map(|d| u64::from(*d)).sum();
        if index >= days.len() || total == 0 {
            return Self::whole();
        }
        Self {
            days: days.iter().map(|d| Decimal::from(*d)).collect(),
            index,
        }
    }

    /// The period is one leg: every total belongs to it unchanged.
    #[must_use]
    pub fn whole() -> Self {
        Self {
            days: vec![Decimal::ONE],
            index: 0,
        }
    }

    /// Whether this apportionment leaves every total untouched.
    #[must_use]
    pub fn is_whole(&self) -> bool {
        self.days.len() <= 1
    }

    /// This leg's share of `total`, rounded to `scale` decimals.
    #[must_use]
    pub fn share(&self, total: Decimal, scale: u32) -> Decimal {
        if self.is_whole() || total.is_zero() {
            return total;
        }
        let sum: Decimal = self.days.iter().copied().sum();
        let last = self.days.len() - 1;
        // `proportional_split` requires shares that sum to exactly one, and a
        // day count rarely divides evenly; the last leg absorbs the residue.
        let mut fractions: Vec<Decimal> = self.days.iter().map(|d| *d / sum).collect();
        let head: Decimal = fractions[..last].iter().copied().sum();
        fractions[last] = Decimal::ONE - head;
        // A quantity is non-negative, but a correction run can carry a negative
        // one; the sign is lifted out and re-applied, which is exact.
        let negative = total < Decimal::ZERO;
        let magnitude = if negative { -total } else { total };
        let part = billing::proportional_split(magnitude, &fractions, scale)
            .ok()
            .and_then(|parts| parts.get(self.index).copied())
            .unwrap_or_else(|| crate::rates::round_money(magnitude * fractions[self.index], scale));
        if negative { -part } else { part }
    }

    /// This leg's share of an additive quantity — kWh, m³ or months.
    #[must_use]
    pub fn quantity(&self, total: Decimal) -> Decimal {
        self.share(total, QUANTITY_SCALE)
    }

    /// This leg's share of an optional additive quantity.
    #[must_use]
    pub fn opt_quantity(&self, total: Option<Decimal>) -> Option<Decimal> {
        total.map(|t| self.quantity(t))
    }

    /// This leg's share of a countable number of events.
    ///
    /// Split at scale 0: half an optimisation event does not exist, and the
    /// legs still sum back to the events the caller reported.
    #[must_use]
    pub fn count(&self, total: u32) -> u32 {
        use rust_decimal::prelude::ToPrimitive as _;
        self.share(Decimal::from(total), 0)
            .to_u32()
            .unwrap_or(total)
    }

    /// This leg's share of an optional countable number of events.
    #[must_use]
    pub fn opt_count(&self, total: Option<u32>) -> Option<u32> {
        total.map(|t| self.count(t))
    }
}

impl WaermeMeterInput {
    /// This leg's share of a Fernwärme period total.
    ///
    /// The delivered heat and the month count are sums over the period's days.
    /// The Spitzenleistung is not: it is the highest interval of the period,
    /// and the leg that contains it has the same peak the whole period has —
    /// while the Leistungspreis it feeds is already pro-rated by `months`.
    #[must_use]
    pub fn apportioned(&self, a: &DayApportionment) -> Self {
        Self {
            kwh_waerme: a.quantity(self.kwh_waerme),
            spitzenleistung_kw: self.spitzenleistung_kw,
            months: a.opt_quantity(self.months),
        }
    }
}

impl WasserMeterInput {
    /// This leg's share of a water period total.
    ///
    /// Frischwasser, every Absetzung and the month count are apportioned; the
    /// same ratio on both keeps an Absetzung from overtaking the Frischwasser
    /// it is deducted from. The versiegelte Fläche is a property of the
    /// premises rather than a quantity delivered over the period.
    #[must_use]
    pub fn apportioned(&self, a: &DayApportionment) -> Self {
        Self {
            frischwasser_m3: a.quantity(self.frischwasser_m3),
            absetzungen: self
                .absetzungen
                .iter()
                .map(|x| Absetzung {
                    m3: a.quantity(x.m3),
                    grund: x.grund,
                })
                .collect(),
            versiegelte_flaeche_m2: self.versiegelte_flaeche_m2,
            months: a.opt_quantity(self.months),
        }
    }
}

impl SolarMeterInput {
    /// This leg's share of a self-consumption period total.
    #[must_use]
    pub fn apportioned(&self, a: &DayApportionment) -> Self {
        Self {
            eigenverbrauch_kwh: a.quantity(self.eigenverbrauch_kwh),
        }
    }
}

impl EegMeterInput {
    /// This leg's share of a feed-in period total.
    ///
    /// The § 51 EEG negative-price hours are apportioned with the feed-in they
    /// are subtracted from, so the billable kWh of the legs still sum to the
    /// billable kWh of the period.
    #[must_use]
    pub fn apportioned(&self, a: &DayApportionment) -> Self {
        Self {
            einspeisung_kwh: a.quantity(self.einspeisung_kwh),
            kwh_during_negative_epex: a.opt_quantity(self.kwh_during_negative_epex),
        }
    }
}

impl HemsMeterInput {
    /// This leg's share of a HEMS period total.
    #[must_use]
    pub fn apportioned(&self, a: &DayApportionment) -> Self {
        Self {
            months: a.opt_quantity(self.months),
            optimization_events: a.opt_count(self.optimization_events),
            readout_events: a.opt_count(self.readout_events),
        }
    }
}

impl EmobilityMeterInput {
    /// This leg's share of an e-mobility period total.
    #[must_use]
    pub fn apportioned(&self, a: &DayApportionment) -> Self {
        Self {
            months: a.opt_quantity(self.months),
            kwh_charged: a.opt_quantity(self.kwh_charged),
            sessions: a.opt_count(self.sessions),
            roaming_sessions: a.opt_count(self.roaming_sessions),
        }
    }
}

impl ServiceMeterInput {
    /// This leg's share of an Energiedienstleistung period total.
    ///
    /// `event_price_eur` is the agreed price of one event, not a total, so it
    /// is carried whole.
    #[must_use]
    pub fn apportioned(&self, a: &DayApportionment) -> Self {
        Self {
            months: a.opt_quantity(self.months),
            event_count: a.opt_count(self.event_count),
            event_price_eur: self.event_price_eur,
        }
    }
}

impl EnergyShareMeterInput {
    /// This leg's share of a § 42c EnWG community allocation.
    ///
    /// The allocated energy and the plant generation it was taken from are
    /// apportioned together, so the informational check the invoice offers the
    /// participant — fraction × generation ≈ allocation — still holds on each
    /// leg. The fraction itself is a ratio and the community identifier a name.
    #[must_use]
    pub fn apportioned(&self, a: &DayApportionment) -> Self {
        Self {
            allocated_kwh: a.quantity(self.allocated_kwh),
            total_plant_generation_kwh: a.opt_quantity(self.total_plant_generation_kwh),
            allocation_fraction: self.allocation_fraction,
            gemeinschaft_id: self.gemeinschaft_id.clone(),
        }
    }
}

// ── Quantities ────────────────────────────────────────────────────────────────

/// All metered quantities for one billing period.
///
/// Replaces the scattered positional parameters of the old `calculate_*` functions.
/// Set only the fields relevant for the current billing run — defaults are `None`/
/// empty for unused products.
///
/// ## Multi-product billing
///
/// To bill a customer with electricity + solar + HEMS on one invoice:
///
/// ```rust,ignore
/// let quantities = Quantities {
///     electricity: Some(MeterInput { arbeitsmenge_kwh: dec!(500), ..Default::default() }),
///     solar: Some(SolarMeterInput { eigenverbrauch_kwh: dec!(120) }),
///     hems: Some(HemsMeterInput { months: Some(dec!(1)), ..Default::default() }),
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct Quantities {
    /// Electricity consumption (STROM, WAERMEPUMPE, WALLBOX).
    pub electricity: Option<MeterInput>,

    /// §14a Modul 3 — the controllable device's energy per Tarifstufe.
    ///
    /// The Netzbetreiber's time windows, not the supplier's HT/NT: the two
    /// gratings are set by different parties and rarely coincide, which is why
    /// this is not derived from `MeterInput`'s Zweitarif split.
    pub sect14a_modul3: Option<Sect14aModul3Verbrauch>,
    /// Natural gas consumption (GAS).
    pub gas: Option<GasMeterInput>,
    /// District heat / Fernwärme (WAERME).
    pub heat: Option<WaermeMeterInput>,
    /// Drinking water / wastewater (WASSER).
    pub wasser: Option<WasserMeterInput>,
    /// Solar self-consumption / Mieterstrom / GGV (SOLAR) — simple single-rate path.
    pub solar: Option<SolarMeterInput>,
    /// §42b EnWG (Solarpaket I) — GGV community solar hybrid billing.
    ///
    /// Use instead of (or in addition to) `solar` when the plant’s generation must be
    /// proportionally allocated among tenants. The `SolarProvider` will then generate
    /// **two** positions per tenant:
    /// - **PV portion**: `min(consumption, allocated_pv)` at the community solar rate
    /// - **Grid portion**: `max(0, consumption − allocated_pv)` at the regular electricity rate
    ///
    /// Computed via `GgvNutzungsplan::allocate(plant_generation_kwh)` in `billingd`.
    pub ggv_solar: Option<GgvSolarInput>,
    /// EEG feed-in meter data (simplified path — rates from TariffInput).
    pub eeg: Option<EegMeterInput>,
    /// Full EEG settlement via `eeg-billing` — set this for NB-side precision.
    ///
    /// When set, `EegProvider` calls `eeg_billing::calculate_settlement(eeg_full)`
    /// for version-aware §51/§52 rules. Supersedes `eeg` when both are present.
    ///
    /// Requires the `eeg` feature of this crate.
    #[cfg(feature = "eeg")]
    pub eeg_full: Option<eeg_billing::SettleInput>,
    /// Non-EEG Direktvermarktung feed-in (EINSPEISUNG).
    pub einspeisung: Option<EegMeterInput>,
    /// HEMS subscription and event data.
    pub hems: Option<HemsMeterInput>,
    /// E-mobility CPO/EMSP data.
    pub emobility: Option<EmobilityMeterInput>,
    /// Energiedienstleistung service data.
    pub service: Option<ServiceMeterInput>,
    /// §41a dynamic tariff intervals (15-min Lastgang from edmd).
    pub dynamic_intervals: Vec<DynamicInterval>,
    /// EPEX Spot price map for §41a billing: quarter-hour MTU start (UTC) → ct/kWh.
    ///
    /// Keyed on the 15-minute market time unit start instant
    /// ([`crate::provider::mtu_start`]) — DST-safe and aligned with the EPEX
    /// SPOT 15-min day-ahead products (live since 2025-10-01).
    ///
    /// Set by the service layer (billingd) after fetching from `productd`.
    /// `DynamicElectricityProvider` reads this map as a fallback when its internal
    /// `SpotPriceSource` has no data for an interval. This is the standard production path:
    /// `build_engine()` creates the provider with an empty source, and prices flow in here
    /// at `bill()` time.
    pub dynamic_epex_prices: HashMap<OffsetDateTime, Decimal>,
    /// EEG Gutschrift credit passed through to electricity billing (e.g. from einsd).
    pub eeg_gutschrift_eur: Option<Decimal>,
    /// Prosumer meter data (PV self-consumption + grid draw).
    ///
    /// When set, `ElectricityProvider` uses the prosumer billing path:
    /// - Grid consumption is billed at full tariff (commodity + NNE + Stromsteuer)
    /// - Self-consumption is Stromsteuer-exempt (§ 9 Abs. 1 Nr. 3 StromStG)
    /// - NNE does NOT apply to self-consumed energy
    pub prosumer: Option<ProsumerMeterInput>,

    /// §41a Abs. 6 EnWG — annual savings comparison for dynamic tariff customers.
    ///
    /// When set, `DynamicElectricityProvider` renders a mandatory informational
    /// position on the annual invoice comparing actual dynamic costs against a
    /// reference fixed tariff (§41a Abs. 6 EnWG).
    pub sect41a_annual_comparison: Option<Sect41aAnnualComparison>,

    /// §42c EnWG Energy Sharing — allocated community energy for this customer.
    ///
    /// When set, `EnergyShareProvider` generates a credit position for the
    /// customer's share of locally produced community electricity.
    ///
    /// ## Data source
    ///
    /// Populated by `billingd` after querying the sharing community's allocation
    /// data from `edmd` (virtual meter with `GgvConstantAllocation` or
    /// `GgvProportionalAllocation` rule — same infrastructure as §42b EnWG GGV).
    pub energy_share: Option<EnergyShareMeterInput>,
}

impl Quantities {
    /// The metered sources that were supplied and carry no quantity at all.
    ///
    /// A supply invoice for a period longer than a day whose every energy
    /// source reads zero charges the standing charges and nothing for the
    /// commodity, and reads exactly like an ordinary invoice — the quantity
    /// twin of the `KEIN_ARBEITSPREIS` family, which refuses a product that
    /// prices nothing.
    ///
    /// Only sources with an energy or volume dimension are considered. HEMS and
    /// Energiedienstleistung are billed per month and per event, so "zero kWh"
    /// says nothing about them.
    ///
    /// Names the sources rather than answering yes/no, so the finding can say
    /// which reading is missing. Empty when at least one source carries a
    /// quantity, or when none of these sources was supplied at all.
    #[must_use]
    pub fn empty_energy_sources(&self) -> Vec<&'static str> {
        let mut supplied: Vec<(&'static str, bool)> = Vec::new();
        if let Some(m) = &self.electricity {
            supplied.push(("electricity", m.billable_kwh() > Decimal::ZERO));
        }
        if let Some(m) = &self.gas {
            supplied.push((
                "gas",
                m.messung_qm3 > Decimal::ZERO || m.kwh_hs.unwrap_or_default() > Decimal::ZERO,
            ));
        }
        if let Some(m) = &self.heat {
            supplied.push(("heat", m.kwh_waerme > Decimal::ZERO));
        }
        if let Some(m) = &self.wasser {
            supplied.push(("wasser", m.frischwasser_m3 > Decimal::ZERO));
        }
        if let Some(m) = &self.solar {
            supplied.push(("solar", m.eigenverbrauch_kwh > Decimal::ZERO));
        }
        if let Some(m) = &self.eeg {
            supplied.push(("eeg", m.einspeisung_kwh > Decimal::ZERO));
        }
        if let Some(m) = &self.einspeisung {
            supplied.push(("einspeisung", m.einspeisung_kwh > Decimal::ZERO));
        }
        if let Some(m) = &self.emobility {
            supplied.push((
                "emobility",
                m.kwh_charged.unwrap_or_default() > Decimal::ZERO
                    || m.sessions.unwrap_or_default() > 0,
            ));
        }
        if let Some(g) = &self.ggv_solar {
            supplied.push((
                "ggv_solar",
                g.pv_allocated_kwh > Decimal::ZERO || g.actual_consumption_kwh > Decimal::ZERO,
            ));
        }
        if supplied.is_empty() || supplied.iter().any(|(_, has)| *has) {
            return Vec::new();
        }
        supplied.into_iter().map(|(name, _)| name).collect()
    }
}

// ── ProsumerMeterInput ────────────────────────────────────────────────────────

/// Prosumer meter data — combines grid consumption with PV self-consumption.
///
/// A prosumer simultaneously consumes electricity (partly from the grid,
/// partly from their own PV plant) and may export surplus generation to the grid.
///
/// ## LF billing scope (energy-billing)
///
/// The Lieferant bills **grid consumption** only. Self-consumption billing and
/// EEG feed-in remuneration (Einspeisevergütung) are handled by `eeg-billing`.
///
/// ## Stromsteuer exemption
///
/// § 9 Abs. 1 Nr. 3 StromStG exempts self-consumed electricity from plants up to 2 MW
/// from Stromsteuer. This is applied automatically when `self_consumption_kwh > 0`.
///
/// ## Network charge exemption
///
/// Netzentgelte are charged for *Netznutzung* — the § 17 StromNEV Arbeits- and
/// Leistungspreis are levied on what is taken from the grid at the
/// Entnahmestelle. Self-consumed electricity never enters it, so it is outside
/// that base and no NNE applies to `self_consumption_kwh`. This is not the
/// § 14a EnWG reduction, which is a *reduced* Netzentgelt for a controllable
/// load that does draw from the grid.
///
/// ## Example
///
/// ```rust
/// use energy_billing::ProsumerMeterInput;
/// use rust_decimal::dec;
///
/// let m = ProsumerMeterInput {
///     grid_consumption_kwh: dec!(250),   // drawn from grid → full tariff
///     self_consumption_kwh: dec!(150),   // from own PV → Stromsteuer-exempt, no Netznutzung
///     export_kwh: Some(dec!(100)),       // fed back to grid (via eeg-billing)
/// };
/// assert_eq!(m.total_consumption_kwh(), dec!(400));
/// ```
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct ProsumerMeterInput {
    /// Electricity drawn from the public grid (kWh).
    ///
    /// Full tariff applies: Arbeitspreis + NNE + Stromsteuer.
    pub grid_consumption_kwh: Decimal,

    /// Electricity generated by the customer's PV plant and consumed on-site (kWh).
    ///
    /// - No NNE (does not transit the grid)
    /// - No Stromsteuer on the self-consumed part (§ 9 Abs. 1 Nr. 3 StromStG)
    /// - Appears as an informational invoice line showing the self-supply ratio
    pub self_consumption_kwh: Decimal,

    /// Electricity exported to the grid (kWh). Informational only.
    ///
    /// This quantity is handled by `eeg-billing` (EEG Einspeisevergütung),
    /// not by `energy-billing`. Included here so the retail invoice can show
    /// the complete energy balance to the customer (§41 EnWG transparency).
    #[serde(default)]
    pub export_kwh: Option<Decimal>,
}

impl ProsumerMeterInput {
    /// Total electricity consumption (grid + self, kWh).
    #[must_use]
    pub fn total_consumption_kwh(&self) -> Decimal {
        self.grid_consumption_kwh + self.self_consumption_kwh
    }

    /// Self-supply ratio (0.0–1.0): share of total consumption from own PV.
    #[must_use]
    pub fn self_supply_ratio(&self) -> Decimal {
        let total = self.total_consumption_kwh();
        if total.is_zero() {
            Decimal::ZERO
        } else {
            (self.self_consumption_kwh / total).min(Decimal::ONE)
        }
    }
}

/// §42b EnWG (Solarpaket I, BGBl I 2024 Nr. 107) — GGV allocation for one tenant.
///
/// Use this for **Gemeinschaftliche Gebäudeversorgung** billing where the plant’s
/// generation is proportionally distributed among building participants.
/// The `SolarProvider` splits the tenant’s invoice into:
///
/// - **PV portion** (community solar at discounted GGV rate)
/// - **Grid portion** (residual demand from the public grid at standard electricity rate)
///
/// ## Computing allocations
///
/// ```rust
/// use energy_billing::{GgvNutzungsplan, GgvNutzungsplanEntry, GgvSolarInput};
/// use rust_decimal::dec;
///
/// let plan = GgvNutzungsplan(vec![
///     GgvNutzungsplanEntry { malo_id: "A".into(), fraction: dec!(0.60) },
///     GgvNutzungsplanEntry { malo_id: "B".into(), fraction: dec!(0.40) },
/// ]);
/// let plant_kwh = dec!(100);
/// let allocs = plan.allocate(plant_kwh).unwrap(); // [("A", 60), ("B", 40)]
///
/// let tenant_a = GgvSolarInput {
///     pv_allocated_kwh: dec!(60),
///     actual_consumption_kwh: dec!(80),   // needs 80, gets 60 PV + 20 grid
/// };
/// assert_eq!(tenant_a.pv_delivered_kwh(), dec!(60));
/// assert_eq!(tenant_a.grid_kwh(), dec!(20));
/// ```
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GgvSolarInput {
    /// PV energy allocated to this tenant via the GGV Nutzungsplan.
    ///
    /// = `plant_generation_kwh × tenant_fraction` (from `GgvNutzungsplan::allocate`).
    pub pv_allocated_kwh: Decimal,
    /// Actual metered energy consumption at this tenant’s delivery point.
    ///
    /// Sourced from `edmd` for the billing period.
    pub actual_consumption_kwh: Decimal,
}

impl GgvSolarInput {
    /// PV energy actually delivered to this tenant.
    ///
    /// Capped at the tenant’s consumption: a tenant cannot receive more PV than they use.
    #[must_use]
    pub fn pv_delivered_kwh(&self) -> Decimal {
        self.actual_consumption_kwh.min(self.pv_allocated_kwh)
    }

    /// Residual grid electricity needed beyond the PV allocation.
    ///
    /// This quantity is billed at the standard electricity (STROM) rate.
    #[must_use]
    pub fn grid_kwh(&self) -> Decimal {
        (self.actual_consumption_kwh - self.pv_allocated_kwh).max(Decimal::ZERO)
    }

    /// Fraction of this tenant’s consumption covered by community PV (0.0–1.0).
    ///
    /// Useful for §40 kilowattstundenpreis reporting and sustainability KPIs.
    #[must_use]
    pub fn pv_coverage_ratio(&self) -> Decimal {
        if self.actual_consumption_kwh <= Decimal::ZERO {
            return Decimal::ZERO;
        }
        (self.pv_delivered_kwh() / self.actual_consumption_kwh)
            .min(Decimal::ONE)
            .round_kfm(4)
    }
}

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

    fn plan(fractions: &[(&str, &str)]) -> GgvNutzungsplan {
        GgvNutzungsplan(
            fractions
                .iter()
                .map(|(id, f)| GgvNutzungsplanEntry {
                    malo_id: (*id).to_owned(),
                    fraction: f.parse().unwrap(),
                })
                .collect(),
        )
    }

    /// Fractions summing to 1.0 do not prove the plan covers the community: a
    /// 3-entry plan for 4 tenants is internally consistent, and the omitted
    /// tenant would silently be billed as pure Solar-Eigenverbrauch.
    #[test]
    fn validate_covers_rejects_a_tenant_missing_from_the_plan() {
        let p = plan(&[("A", "0.5"), ("B", "0.3"), ("C", "0.2")]);
        p.validate().expect("fractions sum to 1.0");
        p.validate_covers(["A", "B", "C"]).expect("exact coverage");

        let err = p
            .validate_covers(["A", "B", "C", "D"])
            .expect_err("D is not allocated");
        assert!(err.contains('D'), "{err}");

        let err = p
            .validate_covers(["A", "B"])
            .expect_err("C is not a tenant of this run");
        assert!(err.contains('C'), "{err}");
    }

    /// The allocation is keyed on the MaLo, so a duplicated entry loses a share.
    #[test]
    fn validate_covers_rejects_a_duplicated_malo() {
        let p = plan(&[("A", "0.5"), ("A", "0.3"), ("B", "0.2")]);
        let err = p.validate_covers(["A", "B"]).expect_err("A appears twice");
        assert!(err.contains("more than once"), "{err}");
    }

    /// Σ(allocated) must always equal total_kwh exactly.
    #[test]
    fn allocate_sum_equals_total() {
        let p = plan(&[("A", "0.333"), ("B", "0.333"), ("C", "0.334")]);
        let total = dec!(100.000);
        let allocs = p
            .allocate(total)
            .expect("the shares partition the generation");
        let sum: Decimal = allocs.iter().map(|(_, k)| k).sum();
        assert_eq!(sum, total, "sum must equal total exactly");
    }

    /// With 3 equal tenants the old "dump remainder on last" method would give
    /// last tenant 0.001 kWh extra. LRM distributes evenly.
    #[test]
    fn allocate_lrm_distributes_evenly_not_just_last_entry() {
        // 3 equal tenants, 100.001 kWh → exact share = 33.333666…
        // floor 3dp = 33.333 each → 1 leftover unit (0.001 kWh)
        // LRM: give it to whichever has highest fractional part (they're equal, so first)
        // Old naive: last tenant gets all of it
        let p = plan(&[("A", "0.3333"), ("B", "0.3333"), ("C", "0.3334")]);
        let total = dec!(100.000);
        let allocs = p
            .allocate(total)
            .expect("the shares partition the generation");

        // All within ±0.001 of their exact share
        for (id, kwh) in &allocs {
            let fraction: Decimal = p.0.iter().find(|e| &e.malo_id == id).unwrap().fraction;
            let exact = total * fraction;
            let diff = (kwh - exact).abs();
            assert!(
                diff <= dec!(0.001),
                "{id}: allocated {kwh}, exact {exact}, diff {diff} > 0.001"
            );
        }

        let sum: Decimal = allocs.iter().map(|(_, k)| k).sum();
        assert_eq!(sum, total);
    }

    /// Many tenants: no single tenant should absorb disproportionate error.
    #[test]
    fn allocate_lrm_no_disproportionate_last_entry() {
        // 10 equal tenants, 1000.001 kWh → each gets 100.0001 → floor = 100.000
        // 1 leftover 0.001 unit
        let tenants: Vec<(String, String)> = (0..10)
            .map(|i| (format!("T{i}"), "0.1".to_owned()))
            .collect();
        let p = GgvNutzungsplan(
            tenants
                .iter()
                .map(|(id, f)| GgvNutzungsplanEntry {
                    malo_id: id.clone(),
                    fraction: f.parse().unwrap(),
                })
                .collect(),
        );
        let total = dec!(1000.001);
        let allocs = p
            .allocate(total)
            .expect("the shares partition the generation");

        // With old naive: T9 (last) gets 100.001, others get 100.000
        // With LRM: one tenant gets 100.001, the rest get 100.000 — but it's
        // the one with the highest fractional part, not necessarily the last.
        let over_base: Vec<_> = allocs.iter().filter(|(_, k)| *k > dec!(100.000)).collect();
        assert_eq!(
            over_base.len(),
            1,
            "exactly 1 tenant should get the extra 0.001"
        );

        let sum: Decimal = allocs.iter().map(|(_, k)| k).sum();
        assert_eq!(sum, total);
    }
}

// ── Sect14aModul3Verbrauch ────────────────────────────────────────────────────

/// Energy per §14a Modul 3 Tarifstufe (zeitvariable Netzentgelte, BK8-22/010-A).
///
/// All three bands are present by construction — a Modul 3 metering
/// configuration reports every window, and a zero band is a real zero, not an
/// absent one.
#[derive(Debug, Clone, Copy, Default, serde::Serialize, serde::Deserialize)]
pub struct Sect14aModul3Verbrauch {
    /// Hochtarif energy in kWh.
    pub ht_kwh: Decimal,
    /// Standardtarif energy in kWh.
    pub st_kwh: Decimal,
    /// Niedertarif energy in kWh.
    pub nt_kwh: Decimal,
}

// ── Abschlagsplan ─────────────────────────────────────────────────────────────

/// One scheduled advance payment entry (Abschlag) in an Abschlagsplan.
///
/// Advance payments must be based on the estimated annual consumption.
/// When the operator changes the Abschlag amount, customers must be notified
/// with adequate lead time per §41 Abs. 1 Nr. 6 EnWG.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AbschlagsplanEntry {
    /// Payment due date.
    pub faellig_am: time::Date,
    /// Amount to collect in EUR (brutto, i.e. inclusive of MwSt).
    pub betrag_eur: Decimal,
    /// Optional display label (e.g. `"Abschlag Januar 2026"`).
    #[serde(default)]
    pub beschreibung: Option<String>,
}

/// Complete advance payment schedule for a customer contract.
///
/// Provides the statutory context (estimated annual cost and consumption) to
/// satisfy §41 Abs. 1 Nr. 6 EnWG requirements.
///
/// ## Legal basis
///
/// §41 Abs. 1 Nr. 6 EnWG: the invoice must show the current and planned
/// advance payment amounts and collection dates.
///
/// ## Example — generate a 12-month uniform schedule
///
/// ```rust
/// use energy_billing::Abschlagsplan;
/// use rust_decimal::dec;
/// use time::macros::date;
///
/// let plan = Abschlagsplan::monthly_uniform(
///     "51238696012",
///     date!(2026-01-01),
///     12,
///     dec!(1440.00), // annual brutto estimate
///     dec!(3600),    // annual kWh estimate
/// );
/// assert_eq!(plan.entries.len(), 12);
/// assert_eq!(plan.entries[0].betrag_eur, dec!(120.00));
/// ```
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Abschlagsplan {
    /// Market location this plan belongs to.
    pub malo_id: String,
    /// Contract reference for ERP routing.
    #[serde(default)]
    pub contract_id: Option<String>,
    /// Scheduled advance payment entries in chronological order.
    pub entries: Vec<AbschlagsplanEntry>,
    /// Annual consumption estimate used to derive the plan (kWh).
    pub jahresverbrauch_schaetzung_kwh: Decimal,
    /// Annual cost estimate used to derive the plan (EUR brutto).
    pub jahreskosten_schaetzung_eur: Decimal,
}

impl Abschlagsplan {
    /// Build a uniform monthly advance payment plan for `months` months.
    ///
    /// The annual amount is **distributed exactly** over a 12-month cycle via
    /// [`billing::Amount::distribute`] (largest-remainder): any 12 consecutive
    /// instalments sum to precisely `annual_brutto_eur` at cent precision.
    /// Naïve `round(annual / 12)` per month drifts up to 6 ct per year — a
    /// reconciliation gap §13 Abs. 3 StromGVV's refund duty would surface on
    /// every Jahresrechnung.
    #[must_use]
    pub fn monthly_uniform(
        malo_id: impl Into<String>,
        start_date: time::Date,
        months: u32,
        annual_brutto_eur: Decimal,
        jahresverbrauch_kwh: Decimal,
    ) -> Self {
        use rust_decimal::dec;
        // Exact-sum 12-month cycle; conversion failure (absurd magnitude)
        // degrades to the plain division, never to a panic.
        let cycle: Vec<Decimal> = billing::Amount::<2>::checked_from_decimal(annual_brutto_eur)
            .and_then(|a| a.distribute(12))
            .map(|parts| {
                parts
                    .into_iter()
                    .map(billing::Amount::into_decimal)
                    .collect()
            })
            .unwrap_or_else(|_| vec![(annual_brutto_eur / dec!(12)).round_kfm(2); 12]);
        let entries = (0..months)
            .filter_map(|i| {
                let total_months = start_date.month() as u32 - 1 + i;
                let year = start_date.year() + (total_months / 12) as i32;
                let month_idx = (total_months % 12 + 1) as u8;
                let month = time::Month::try_from(month_idx).ok()?;
                let max_day = month.length(time::util::is_leap_year(year) as i32) as u8;
                let day = start_date.day().min(max_day);
                let date = time::Date::from_calendar_date(year, month, day).ok()?;
                Some(AbschlagsplanEntry {
                    faellig_am: date,
                    betrag_eur: cycle[(i % 12) as usize],
                    beschreibung: Some(format!("Abschlag {:02}/{}", month as u8, year)),
                })
            })
            .collect();
        Self {
            malo_id: malo_id.into(),
            contract_id: None,
            entries,
            jahresverbrauch_schaetzung_kwh: jahresverbrauch_kwh,
            jahreskosten_schaetzung_eur: annual_brutto_eur,
        }
    }

    /// Sum of all scheduled advance payment amounts.
    #[must_use]
    pub fn total_eur(&self) -> Decimal {
        self.entries.iter().map(|e| e.betrag_eur).sum()
    }
}

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

    #[test]
    fn monthly_uniform_12_months() {
        let plan = Abschlagsplan::monthly_uniform(
            "51238696781",
            date!(2026 - 01 - 01),
            12,
            dec!(1440.00),
            dec!(3600),
        );
        assert_eq!(plan.entries.len(), 12);
        assert_eq!(plan.entries[0].betrag_eur, dec!(120.00));
        assert_eq!(plan.entries[11].faellig_am.year(), 2026);
        assert_eq!(plan.total_eur(), dec!(1440.00));
    }

    #[test]
    fn monthly_uniform_distributes_indivisible_annual_exactly() {
        // 1000.00 / 12 = 83.333… — naïve per-month rounding gives
        // 12 × 83.33 = 999.96, a 4 ct gap the Jahresrechnung would have to
        // reconcile. Largest-remainder distribution closes it.
        let plan = Abschlagsplan::monthly_uniform(
            "51238696781",
            date!(2026 - 01 - 01),
            12,
            dec!(1000.00),
            dec!(2500),
        );
        assert_eq!(plan.total_eur(), dec!(1000.00), "instalments sum exactly");
        // Every instalment is within one cent of the uniform value.
        for e in &plan.entries {
            assert!(
                e.betrag_eur == dec!(83.33) || e.betrag_eur == dec!(83.34),
                "uniform ± 1 ct, got {}",
                e.betrag_eur
            );
        }
        // A 24-month plan sums to exactly two annual amounts.
        let two_years = Abschlagsplan::monthly_uniform(
            "51238696781",
            date!(2026 - 01 - 01),
            24,
            dec!(1000.00),
            dec!(2500),
        );
        assert_eq!(two_years.total_eur(), dec!(2000.00));
    }

    #[test]
    fn monthly_uniform_crosses_year_boundary() {
        let plan = Abschlagsplan::monthly_uniform(
            "51238696129",
            date!(2025 - 07 - 01),
            12,
            dec!(1200.00),
            dec!(3000),
        );
        assert_eq!(plan.entries.len(), 12);
        // July 2025 → June 2026
        assert_eq!(plan.entries[0].faellig_am.month(), time::Month::July);
        assert_eq!(plan.entries[0].faellig_am.year(), 2025);
        assert_eq!(plan.entries[5].faellig_am.month(), time::Month::December);
        assert_eq!(plan.entries[6].faellig_am.month(), time::Month::January);
        assert_eq!(plan.entries[6].faellig_am.year(), 2026);
    }
}