rubo4e 0.10.0

Rust implementation of the BO4E energy-market data standard
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
//! Convenience methods and extension traits on generated BO4E types.
//!
//! These are hand-written extension `impl` blocks on generated structs.
//! The generated files are annotated `// @generated — do not edit by hand`,
//! so all ergonomic additions live here instead.
//!
//! All items are guarded by the feature flags that make their return types
//! available:
//!
//! - `versioned` — the generated BO/COM structs
//! - `time` — `time::Date` / `time::OffsetDateTime` return types
//! - `decimal` — `rust_decimal::Decimal` return types
//!
//! ## Extension traits
//!
//! [`BetragExt`][be], [`MengeExt`][me], and [`PreisExt`][pe] are the primary ergonomic
//! entry points for the common `Option<Com> → Option<Decimal>` pattern.  They
//! eliminate the repetitive `.as_ref().and_then(|x| x.wert)` chain:
//!
//! ```
//! # #[cfg(feature = "decimal")] {
//! use rubo4e::prelude::*;  // re-exports BetragExt, MengeExt, PreisExt
//! use rubo4e::current::{Betrag, Waehrungscode};
//!
//! let gesamtpreis = Some(Betrag {
//!     wert: Some(rust_decimal::Decimal::new(1250, 2)),
//!     waehrung: Some(Waehrungscode::Eur),
//!     ..Default::default()
//! });
//!
//! // Before: `gesamtpreis.as_ref().and_then(|b| b.wert)`
//! assert_eq!(gesamtpreis.wert_decimal(), Some(rust_decimal::Decimal::new(1250, 2)));
//! # }
//! ```
//!
//! Import via `use rubo4e::prelude::*` or individually via
//! `use rubo4e::convenience::{BetragExt, MengeExt, PreisExt}`.
//!
//! [be]: crate::convenience::BetragExt
//! [me]: crate::convenience::MengeExt
//! [pe]: crate::convenience::PreisExt

// ── Extension traits: Option<Com> → Option<Decimal> ─────────────────────────
//
// Flatten `Option<Betrag/Menge/Preis>` to `Option<Decimal>` in one method call.
// Gated on both `versioned` (the struct) and `decimal` (the type).

/// Ergonomic access to the `wert` field of an [`Option<Betrag>`][crate::v202607::Betrag].
///
/// Eliminates the `.as_ref().and_then(|b| b.wert)` chain that appears wherever
/// monetary amounts are read from `Betrag`-typed optional fields.
///
/// Automatically available with `use rubo4e::prelude::*`.
#[cfg(all(feature = "versioned", feature = "decimal"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "versioned", feature = "decimal"))))]
pub trait BetragExt {
    /// Returns `wert` from the inner `Betrag`, or `None` if the outer `Option`
    /// is empty or `wert` itself is `None`.
    fn wert_decimal(&self) -> Option<rust_decimal::Decimal>;
}

#[cfg(all(feature = "versioned", feature = "decimal"))]
impl BetragExt for Option<crate::generated::v202607::Betrag> {
    fn wert_decimal(&self) -> Option<rust_decimal::Decimal> {
        self.as_ref().and_then(|b| b.wert)
    }
}

/// Ergonomic access to the `wert` field of an [`Option<Menge>`][crate::v202607::Menge].
///
/// Eliminates the `.as_ref().and_then(|m| m.wert)` chain that appears wherever
/// quantities are read from `Menge`-typed optional fields.
///
/// Automatically available with `use rubo4e::prelude::*`.
#[cfg(all(feature = "versioned", feature = "decimal"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "versioned", feature = "decimal"))))]
pub trait MengeExt {
    /// Returns `wert` from the inner `Menge`, or `None` if the outer `Option`
    /// is empty or `wert` itself is `None`.
    fn wert_decimal(&self) -> Option<rust_decimal::Decimal>;
}

#[cfg(all(feature = "versioned", feature = "decimal"))]
impl MengeExt for Option<crate::generated::v202607::Menge> {
    fn wert_decimal(&self) -> Option<rust_decimal::Decimal> {
        self.as_ref().and_then(|m| m.wert)
    }
}

/// Ergonomic access to the `wert` field of an [`Option<Preis>`][crate::v202607::Preis].
///
/// Eliminates the `.as_ref().and_then(|p| p.wert)` chain that appears wherever
/// unit prices are read from `Preis`-typed optional fields.
///
/// Automatically available with `use rubo4e::prelude::*`.
#[cfg(all(feature = "versioned", feature = "decimal"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "versioned", feature = "decimal"))))]
pub trait PreisExt {
    /// Returns `wert` from the inner `Preis`, or `None` if the outer `Option`
    /// is empty or `wert` itself is `None`.
    fn wert_decimal(&self) -> Option<rust_decimal::Decimal>;
}

#[cfg(all(feature = "versioned", feature = "decimal"))]
impl PreisExt for Option<crate::generated::v202607::Preis> {
    fn wert_decimal(&self) -> Option<rust_decimal::Decimal> {
        self.as_ref().and_then(|p| p.wert)
    }
}

/// What the `format: "time"` accessors return: a time of day plus the UTC offset
/// it was written with, or the reason it did not parse.
///
/// The offset is `Option` because BO4E does not require one — see
/// [`offset_time`](crate::offset_time).
#[cfg(all(feature = "versioned", feature = "time"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "versioned", feature = "time"))))]
pub type OffsetTimeResult =
    Result<(time::Time, Option<time::UtcOffset>), crate::offset_time::OffsetTimeError>;

// ── Zeitraum ─────────────────────────────────────────────────────────────────

#[cfg(all(feature = "versioned", feature = "time"))]
mod zeitraum_impl {
    use super::OffsetTimeResult;
    use crate::generated::v202607::Zeitraum;
    use std::ops::RangeInclusive;
    use time::Date;

    /// # Boundary conventions
    ///
    /// BO4E states these on the fields themselves, and they are not the same for
    /// all three pairs:
    ///
    /// | Pair | Type | Interval | Read by |
    /// |---|---|---|---|
    /// | `startdatum` / `enddatum` | `time::Date` | `[start, end]` — **closed** | the methods below |
    /// | `startuhrzeit` / `enduhrzeit` | time of day + offset | `[start, end)` | [`startuhrzeit_parsed`](Zeitraum::startuhrzeit_parsed) |
    /// | `dauer` | ISO 8601 duration | — | [`duration`](Zeitraum::duration) |
    ///
    /// So `2026-01-01 … 2026-01-31` is the whole of January, 31 days, and
    /// `startdatum == enddatum` is a valid one-day period — the schema gives
    /// `'2025-01-01'` as the example for *both* date fields. Reading `enddatum`
    /// exclusively drops a day from every period.
    ///
    /// [`as_inclusive_range`](Zeitraum::as_inclusive_range) returns a
    /// [`RangeInclusive`] rather than a tuple so the convention travels with the
    /// value. The time pair keeps its wire `String`: it carries a UTC offset
    /// (`"18:00:00+01:00"`) and no `time` type holds both.
    ///
    impl Zeitraum {
        /// Returns the period as an inclusive range, when **both** dates are present.
        ///
        /// `start..=end`, matching BO4E's *"Enddatum … ist **inklusiv**"*. The
        /// return type is a [`RangeInclusive`] so the convention travels with the
        /// value: `range.contains(&d)` is correct by construction.
        ///
        /// Use this where an open-ended interval means "not yet determined" and
        /// should be filtered out; [`bounds`](Self::bounds) keeps it instead.
        ///
        /// ```
        /// # #[cfg(all(feature = "versioned", feature = "time"))] {
        /// use rubo4e::v202607::Zeitraum;
        /// use time::macros::date;
        ///
        /// let january = Zeitraum {
        ///     startdatum: Some(date!(2026-01-01)),
        ///     enddatum: Some(date!(2026-01-31)),
        ///     ..Default::default()
        /// };
        /// let range = january.as_inclusive_range().expect("both dates present");
        /// assert!(range.contains(&date!(2026-01-31)), "the end date is inside");
        /// # }
        /// ```
        #[must_use]
        pub fn as_inclusive_range(&self) -> Option<RangeInclusive<Date>> {
            Some(self.startdatum?..=self.enddatum?)
        }

        /// Returns both boundary dates as they stand, either of which may be absent.
        ///
        /// An absent boundary is an **open end**, not a missing value: no
        /// `startdatum` means "since forever", no `enddatum` means "until further
        /// notice". [`contains`](Self::contains) reads them the same way.
        ///
        /// ```
        /// # #[cfg(all(feature = "versioned", feature = "time"))] {
        /// use rubo4e::v202607::Zeitraum;
        /// use time::macros::date;
        ///
        /// let ongoing = Zeitraum {
        ///     startdatum: Some(date!(2026-01-01)),
        ///     ..Default::default()
        /// };
        /// match ongoing.bounds() {
        ///     (Some(start), Some(end)) => println!("{start} through {end} inclusive"),
        ///     (Some(start), None)      => println!("{start} onwards"),
        ///     (None, Some(end))        => println!("until {end} inclusive"),
        ///     (None, None)             => println!("unbounded"),
        /// }
        /// # }
        /// ```
        #[must_use]
        pub fn bounds(&self) -> (Option<Date>, Option<Date>) {
            (self.startdatum, self.enddatum)
        }

        /// Returns `true` if `date` falls in `[startdatum, enddatum]` — **both
        /// boundaries included**.
        ///
        /// An absent boundary is unbounded on that side, so a
        /// default-constructed `Zeitraum` answers `true` to everything. Filter on
        /// [`as_inclusive_range`](Self::as_inclusive_range) where a period must
        /// actually be stated.
        ///
        /// ```
        /// # #[cfg(all(feature = "versioned", feature = "time"))] {
        /// use rubo4e::v202607::Zeitraum;
        /// use time::macros::date;
        ///
        /// let january = Zeitraum {
        ///     startdatum: Some(date!(2026-01-01)),
        ///     enddatum: Some(date!(2026-01-31)),
        ///     ..Default::default()
        /// };
        /// assert!(january.contains(date!(2026-01-01)));   // start: inside
        /// assert!(january.contains(date!(2026-01-31)));   // end:   inside
        /// assert!(!january.contains(date!(2026-02-01)));
        ///
        /// // A single-day period is `start == end`, exactly as BO4E's own
        /// // examples show.
        /// let one_day = Zeitraum {
        ///     startdatum: Some(date!(2026-03-15)),
        ///     enddatum: Some(date!(2026-03-15)),
        ///     ..Default::default()
        /// };
        /// assert!(one_day.contains(date!(2026-03-15)));
        /// assert_eq!(one_day.whole_days(), Some(1));
        /// # }
        /// ```
        #[must_use]
        pub fn contains(&self, date: Date) -> bool {
            let start_ok = self.startdatum.is_none_or(|d| date >= d);
            let end_ok = self.enddatum.is_none_or(|d| date <= d);
            start_ok && end_ok
        }

        /// Returns the number of days the period covers, when both dates are present.
        ///
        /// Both boundaries count, so January 2026 (`2026-01-01` … `2026-01-31`)
        /// is 31 days and a one-day period is 1 — the count a day-proportional
        /// network charge or an abrechnungsrelevante Zeitmenge is computed from.
        ///
        /// Returns `None` if either bound is absent, and `0` for a reversed pair
        /// (which [`validate_zeitraum`] rejects).
        ///
        /// [`validate_zeitraum`]: crate::validation::v202607::validate_zeitraum
        ///
        /// ```
        /// # #[cfg(all(feature = "versioned", feature = "time"))] {
        /// use rubo4e::v202607::Zeitraum;
        /// use time::macros::date;
        ///
        /// let january = Zeitraum {
        ///     startdatum: Some(date!(2026-01-01)),
        ///     enddatum: Some(date!(2026-01-31)),
        ///     ..Default::default()
        /// };
        /// assert_eq!(january.whole_days(), Some(31));
        /// # }
        /// ```
        #[must_use]
        pub fn whole_days(&self) -> Option<i64> {
            let (start, end) = (self.startdatum?, self.enddatum?);
            Some(((end - start).whole_days() + 1).max(0))
        }

        /// Parses `dauer` as an exact [`time::Duration`].
        ///
        /// BO4E stores it as an ISO 8601 duration string (`"P1DT30H4S"`), which
        /// neither `serde` nor `time` parses.
        ///
        /// Returns `None` when `dauer` is absent, so a missing value and an
        /// unparsable one stay distinguishable.
        ///
        /// # Errors
        ///
        /// [`Iso8601DurationError`](crate::iso8601_duration::Iso8601DurationError)
        /// — including for a `P1Y` / `P1M` whose length depends on when it
        /// starts, which is refused rather than approximated. See the
        /// [module docs](crate::iso8601_duration).
        ///
        /// ```
        /// # #[cfg(all(feature = "versioned", feature = "time"))] {
        /// use rubo4e::v202607::Zeitraum;
        ///
        /// use time::Duration;
        ///
        /// let z = Zeitraum { dauer: Some("P1DT30H4S".into()), ..Default::default() };
        /// assert_eq!(
        ///     z.duration(),
        ///     Some(Ok(Duration::days(1) + Duration::hours(30) + Duration::seconds(4))),
        /// );
        ///
        /// assert_eq!(Zeitraum::default().duration(), None);
        /// # }
        /// ```
        #[must_use]
        pub fn duration(
            &self,
        ) -> Option<Result<time::Duration, crate::iso8601_duration::Iso8601DurationError>> {
            Some(crate::iso8601_duration::parse(self.dauer.as_deref()?))
        }

        /// Parses `startuhrzeit` into a time of day and its UTC offset.
        ///
        /// Returns `None` when the field is absent. The offset is itself
        /// optional — BO4E does not require one, and a missing offset means
        /// "local time, zone not stated", which is not the same claim as UTC.
        ///
        /// Unlike the date pair, `startuhrzeit` is inclusive and `enduhrzeit`
        /// **exclusive**: the window is `[start, end)`. See the
        /// [boundary convention](#boundary-convention-the-date-pair-is-closed).
        ///
        /// # Errors
        ///
        /// [`OffsetTimeError`](crate::offset_time::OffsetTimeError).
        ///
        /// ```
        /// # #[cfg(all(feature = "versioned", feature = "time"))] {
        /// use rubo4e::v202607::Zeitraum;
        /// use time::macros::{offset, time};
        ///
        /// let z = Zeitraum {
        ///     startuhrzeit: Some("18:00:00+01:00".into()),
        ///     enduhrzeit: Some("19:00:00+01:00".into()),
        ///     ..Default::default()
        /// };
        /// assert_eq!(z.startuhrzeit_parsed(), Some(Ok((time!(18:00:00), Some(offset!(+1))))));
        /// assert_eq!(z.enduhrzeit_parsed(),   Some(Ok((time!(19:00:00), Some(offset!(+1))))));
        /// # }
        /// ```
        #[must_use]
        pub fn startuhrzeit_parsed(&self) -> Option<OffsetTimeResult> {
            Some(crate::offset_time::parse(self.startuhrzeit.as_deref()?))
        }

        /// Parses `enduhrzeit` into a time of day and its UTC offset.
        ///
        /// The end of a time window is **exclusive**, the opposite of
        /// `enddatum` on the same type. See
        /// [`startuhrzeit_parsed`](Self::startuhrzeit_parsed).
        ///
        /// # Errors
        ///
        /// [`OffsetTimeError`](crate::offset_time::OffsetTimeError).
        #[must_use]
        pub fn enduhrzeit_parsed(&self) -> Option<OffsetTimeResult> {
            Some(crate::offset_time::parse(self.enduhrzeit.as_deref()?))
        }
    }
}

// ── Umschaltzeit — the HT/NT switching time ──────────────────────────────────

#[cfg(all(feature = "versioned", feature = "time"))]
mod umschaltzeit_impl {
    use super::OffsetTimeResult;
    use crate::generated::v202607::Umschaltzeit;

    impl Umschaltzeit {
        /// Parses `umschaltzeit` into a time of day and its UTC offset.
        ///
        /// This is the instant a Doppeltarifzähler switches between
        /// Hoch- and Niedertarif, so the offset is load-bearing: `06:00:00+01:00`
        /// is a different wall-clock moment in summer than in winter, and
        /// dropping it moves the tariff boundary by an hour.
        ///
        /// Returns `None` when the field is absent.
        ///
        /// # Errors
        ///
        /// [`OffsetTimeError`](crate::offset_time::OffsetTimeError).
        #[must_use]
        pub fn umschaltzeit_parsed(&self) -> Option<OffsetTimeResult> {
            Some(crate::offset_time::parse(self.umschaltzeit.as_deref()?))
        }
    }
}

// ── Rechnung ─────────────────────────────────────────────────────────────────

#[cfg(all(feature = "versioned", feature = "time"))]
mod rechnung_impl {
    use crate::generated::v202607::Rechnung;
    use time::Date;

    impl Rechnung {
        /// Returns the billing period as `(start, end)` dates.
        ///
        /// Reads from `rechnungsperiode.startdatum` / `rechnungsperiode.enddatum`.
        /// Returns `None` when `rechnungsperiode` is absent or either boundary
        /// date is missing.
        ///
        /// Both boundaries are **inclusive** — see the [boundary convention] on
        /// `Zeitraum`. The last day of the month a monthly invoice covers is
        /// inside its own billing period.
        ///
        /// [boundary convention]: crate::v202607::Zeitraum#boundary-convention-the-date-pair-is-closed
        ///
        /// ```no_run
        /// # #[cfg(all(feature = "versioned", feature = "time"))] {
        /// # use rubo4e::v202607::Rechnung;
        /// # use time::macros::date;
        /// let r: Rechnung = todo!();
        /// if let Some(period) = r.billing_period() {
        ///     println!("invoice period: {} – {} inclusive", period.start(), period.end());
        ///     let billed = period.contains(&date!(2026-01-31));
        /// }
        /// # }
        /// ```
        #[must_use]
        pub fn billing_period(&self) -> Option<std::ops::RangeInclusive<Date>> {
            self.rechnungsperiode.as_ref()?.as_inclusive_range()
        }

        /// Billing period start date (shorthand for `billing_period().map(|(s,_)| s)`).
        ///
        /// Returns `None` when `rechnungsperiode` is absent or `startdatum` is missing.
        #[must_use]
        pub fn period_start(&self) -> Option<Date> {
            self.rechnungsperiode.as_ref()?.startdatum
        }

        /// Billing period end date (shorthand for `billing_period().map(|(_,e)| e)`).
        ///
        /// Returns `None` when `rechnungsperiode` is absent or `enddatum` is missing.
        #[must_use]
        pub fn period_end(&self) -> Option<Date> {
            self.rechnungsperiode.as_ref()?.enddatum
        }

        /// Invoice issue date — the calendar date of `rechnungsdatum`.
        ///
        /// BO4E types the field as a timestamp (`format: date-time`), but BDEW
        /// INVOIC transmits it as DTM+137 qualifier 102, a bare `YYYYMMDD`, so
        /// senders pin it to midnight in their own offset. Dropping the
        /// time-of-day keeps date comparisons from comparing offsets.
        ///
        /// The date is taken **in the offset the payload carries**; use
        /// [`Rechnung::rechnungsdatum`] to normalise first.
        #[must_use]
        pub fn rechnungsdatum_date(&self) -> Option<Date> {
            self.rechnungsdatum.map(|dt| dt.date())
        }

        /// Payment due date — the calendar date of `faelligkeitsdatum`.
        ///
        /// Same date-only reading as [`rechnungsdatum_date`](Self::rechnungsdatum_date);
        /// BDEW INVOIC carries this as DTM+92 with qualifier 102.
        #[must_use]
        pub fn faelligkeitsdatum_date(&self) -> Option<Date> {
            self.faelligkeitsdatum.map(|dt| dt.date())
        }
    }
}

// ── Rechnung — decimal accessors ─────────────────────────────────────────────

#[cfg(all(feature = "versioned", feature = "decimal"))]
mod rechnung_decimal_impl {
    use crate::generated::v202607::Rechnung;

    impl Rechnung {
        /// Net total (`gesamtnetto.wert`) as `Decimal`.
        ///
        /// Returns `None` when `gesamtnetto` is absent or its `wert` is `None`.
        ///
        /// ```no_run
        /// # #[cfg(all(feature = "versioned", feature = "decimal"))] {
        /// # use rubo4e::v202607::Rechnung;
        /// let r: Rechnung = todo!();
        /// if let Some(net) = r.gesamtnetto_decimal() {
        ///     println!("net total: {net}");
        /// }
        /// # }
        /// ```
        #[must_use]
        pub fn gesamtnetto_decimal(&self) -> Option<rust_decimal::Decimal> {
            self.gesamtnetto.as_ref()?.wert
        }

        /// Gross total (`gesamtbrutto.wert`) as `Decimal`.
        ///
        /// Returns `None` when `gesamtbrutto` is absent or its `wert` is `None`.
        #[must_use]
        pub fn gesamtbrutto_decimal(&self) -> Option<rust_decimal::Decimal> {
            self.gesamtbrutto.as_ref()?.wert
        }

        /// Total tax amount (`gesamtsteuer.wert`) as `Decimal`.
        ///
        /// Returns `None` when `gesamtsteuer` is absent or its `wert` is `None`.
        #[must_use]
        pub fn gesamtsteuer_decimal(&self) -> Option<rust_decimal::Decimal> {
            self.gesamtsteuer.as_ref()?.wert
        }

        /// Amount to pay (`zu_zahlen.wert`) as `Decimal`.
        ///
        /// This reads the value the sender computed; the crate does not re-derive
        /// it. BO4E describes it as `gesamtbrutto - vorausbezahlt - rabattBrutto`,
        /// but v202607 ships no `rabattBrutto` field, so the equation cannot be
        /// reconstructed from the payload. Use
        /// [`vorauszahlungen_summe`](Self::vorauszahlungen_summe) if you need the
        /// advance-payment total on its own.
        #[must_use]
        pub fn zu_zahlen_decimal(&self) -> Option<rust_decimal::Decimal> {
            self.zu_zahlen.as_ref()?.wert
        }

        /// Net discount (`rabatt_netto.wert`) as `Decimal`.
        #[must_use]
        pub fn rabatt_netto_decimal(&self) -> Option<rust_decimal::Decimal> {
            self.rabatt_netto.as_ref()?.wert
        }

        /// Estimated next instalment (`zukuenftiger_abschlag.wert`) as `Decimal`.
        ///
        /// Set by the sender as a forward-looking payment estimate for the next
        /// billing period.
        #[must_use]
        pub fn zukuenftiger_abschlag_decimal(&self) -> Option<rust_decimal::Decimal> {
            self.zukuenftiger_abschlag.as_ref()?.wert
        }

        /// Sum of all advance-payment amounts (`vorauszahlungen[*].betrag.wert`).
        ///
        /// Returns `None` when `vorauszahlungen` is absent, empty, or when the
        /// amounts overflow `Decimal`'s range. Returns `Some(Decimal::ZERO)`
        /// when payments are present but every `betrag` is `None`.
        ///
        /// Summed with [`checked_add`] rather than `+`, which would panic: the
        /// values come straight off a deserialization boundary.
        ///
        /// [`checked_add`]: rust_decimal::Decimal::checked_add
        #[must_use]
        pub fn vorauszahlungen_summe(&self) -> Option<rust_decimal::Decimal> {
            let payments = self.vorauszahlungen.as_deref()?;
            if payments.is_empty() {
                return None;
            }
            payments
                .iter()
                .filter_map(|p| p.betrag.as_ref().and_then(|b| b.wert))
                .try_fold(rust_decimal::Decimal::ZERO, |acc, v| acc.checked_add(v))
        }
    }
}

// ── Rechnung — versioned-only accessors ──────────────────────────────────────

#[cfg(feature = "versioned")]
mod rechnung_versioned_impl {
    use crate::generated::v202607::{Rechnung, Rechnungsposition};

    impl Rechnung {
        /// Iterates over all invoice line items (`rechnungspositionen`).
        ///
        /// Yields nothing when `rechnungspositionen` is `None` or empty.
        /// Eliminates the repetitive `.as_deref().into_iter().flatten()` pattern.
        ///
        /// ```no_run
        /// # #[cfg(feature = "versioned")] {
        /// # use rubo4e::v202607::Rechnung;
        /// let r: Rechnung = todo!();
        /// for pos in r.positions() {
        ///     println!("pos {}: {:?}", pos.positionsnummer.unwrap_or(0), pos.positionstext);
        /// }
        /// # }
        /// ```
        pub fn positions(&self) -> impl Iterator<Item = &Rechnungsposition> {
            self.rechnungspositionen.as_deref().into_iter().flatten()
        }

        /// Returns `true` if this is a cancellation invoice (`ist_storno == Some(true)`).
        #[must_use]
        pub fn is_storno(&self) -> bool {
            self.ist_storno.unwrap_or(false)
        }

        /// Returns `true` if this is an original invoice (`ist_original == Some(true)`).
        #[must_use]
        pub fn is_original(&self) -> bool {
            self.ist_original.unwrap_or(false)
        }
    }
}

// ── Rechnungsposition — time accessors ───────────────────────────────────────

#[cfg(all(feature = "versioned", feature = "time"))]
mod rechnungsposition_time_impl {
    use crate::generated::v202607::Rechnungsposition;
    use time::Date;

    impl Rechnungsposition {
        /// Delivery period start date from `lieferungszeitraum.startdatum`.
        ///
        /// Returns `None` when `lieferungszeitraum` is absent or `startdatum` is
        /// not set on the embedded [`Zeitraum`][crate::v202607::Zeitraum].
        #[must_use]
        pub fn lieferung_von_date(&self) -> Option<Date> {
            self.lieferungszeitraum.as_ref()?.startdatum
        }

        /// Delivery period end date from `lieferungszeitraum.enddatum`.
        ///
        /// Returns `None` when `lieferungszeitraum` is absent or `enddatum` is
        /// not set on the embedded [`Zeitraum`][crate::v202607::Zeitraum].
        #[must_use]
        pub fn lieferung_bis_date(&self) -> Option<Date> {
            self.lieferungszeitraum.as_ref()?.enddatum
        }

        /// Returns `true` if `date` falls within this line item's delivery period.
        ///
        /// Delegates to [`Zeitraum::contains`][crate::v202607::Zeitraum::contains].
        /// Returns `false` when `lieferungszeitraum` is absent.
        #[must_use]
        pub fn lieferungszeitraum_contains(&self, date: Date) -> bool {
            self.lieferungszeitraum
                .as_ref()
                .is_some_and(|z| z.contains(date))
        }
    }
}

// ── Zahlungsinformation — checked bank identifiers on demand ─────────────────

#[cfg(feature = "versioned")]
mod zahlungsinformation_impl {
    use crate::error::IdentifierError;
    use crate::generated::v202607::Zahlungsinformation;
    use crate::identifiers::{Bic, Iban};

    /// # Why `iban` is a `String` and not an [`Iban`]
    ///
    /// `Zahlungsinformation` hangs off `Rechnung` and nothing else, so a
    /// newtype that refuses a masked IBAN (`DE89 **** **** 3000`, routine on an
    /// invoice) would take the whole invoice down with it. The check is one call
    /// away instead, and returns an error rather than the invoice.
    impl Zahlungsinformation {
        /// Parses `iban` as a checksum-verified [`Iban`].
        ///
        /// Returns `None` when the field is absent, so "not stated" and "stated
        /// but invalid" stay distinguishable. Grouping spaces and lowercase are
        /// normalised, so a value copied from a bank statement parses.
        ///
        /// # Errors
        ///
        /// [`IdentifierError`], typically
        /// [`InvalidChecksum`](IdentifierError::InvalidChecksum) for a mistyped
        /// or masked value.
        ///
        /// ```
        /// # #[cfg(feature = "versioned")] {
        /// use rubo4e::current::Zahlungsinformation;
        ///
        /// let stated = |iban: &str| Zahlungsinformation {
        ///     iban: Some(iban.into()),
        ///     ..Default::default()
        /// };
        ///
        /// let z = stated("DE89 3704 0044 0532 0130 00");
        /// assert_eq!(z.iban_checked().unwrap().unwrap().bankleitzahl(), Some("37040044"));
        ///
        /// assert!(stated("DE89 **** **** **** 3000").iban_checked().unwrap().is_err());
        /// assert!(Zahlungsinformation::default().iban_checked().is_none());
        /// # }
        /// ```
        #[must_use]
        pub fn iban_checked(&self) -> Option<Result<Iban, IdentifierError>> {
            Some(Iban::new(self.iban.as_deref()?))
        }

        /// Parses `bic` as a [`Bic`], verifying the ISO 9362 grammar.
        ///
        /// Returns `None` when the field is absent. ISO 9362 defines no
        /// checksum, so this verifies the shape and nothing more.
        ///
        /// # Errors
        ///
        /// [`IdentifierError`] if the value is neither 8 nor 11 characters, or
        /// carries a digit where the standard requires a letter.
        #[must_use]
        pub fn bic_checked(&self) -> Option<Result<Bic, IdentifierError>> {
            Some(Bic::new(self.bic.as_deref()?))
        }
    }
}

// ── Preisstaffel — tier bounds and tier selection ────────────────────────────

#[cfg(all(feature = "versioned", feature = "decimal"))]
pub use preisstaffel_impl::PreisstaffelSliceExt;

#[cfg(all(feature = "versioned", feature = "decimal"))]
mod preisstaffel_impl {
    use crate::generated::v202607::Preisstaffel;
    use rust_decimal::Decimal;

    impl Preisstaffel {
        /// Returns `true` if `value` lies within this tier's own stated bounds,
        /// `staffelgrenzeVon ..= staffelgrenzeBis`. An absent bound is unbounded
        /// on that side.
        ///
        /// # This is *not* how a tier is selected
        ///
        /// BO4E's tiers can leave gaps — the schema's own example is
        /// `0 – 1000, 1001 – 2000` — and it rules that a value in a gap
        /// (`1000.6`) *"rutscht in die obere Zone"*. No single tier can honour
        /// that; the decision needs the whole list. Use
        /// [`select_for`](PreisstaffelSliceExt::select_for) to pick a tier, and
        /// this only to ask about one tier in isolation.
        ///
        /// ```
        /// # #[cfg(all(feature = "versioned", feature = "decimal"))] {
        /// use rubo4e::current::Preisstaffel;
        /// use rust_decimal::Decimal;
        ///
        /// let tier = Preisstaffel {
        ///     staffelgrenze_von: Some(Decimal::ZERO),
        ///     staffelgrenze_bis: Some(Decimal::from(1000)),
        ///     ..Default::default()
        /// };
        /// assert!(tier.contains(Decimal::from(1000)), "both bounds are inclusive");
        /// assert!(!tier.contains(Decimal::from(1001)));
        /// # }
        /// ```
        #[must_use]
        pub fn contains(&self, value: Decimal) -> bool {
            self.staffelgrenze_von.is_none_or(|von| value >= von)
                && self.staffelgrenze_bis.is_none_or(|bis| value <= bis)
        }
    }

    /// Picking the price tier that applies to a quantity.
    ///
    /// Implemented for `[Preisstaffel]`, so it works on the `preisstaffeln` /
    /// `staffeln` field of every type that carries one — `Preisposition`,
    /// `LastvariablePreisposition`, `TarifPreisposition`, and `AufAbschlag`.
    #[cfg_attr(docsrs, doc(cfg(all(feature = "versioned", feature = "decimal"))))]
    pub trait PreisstaffelSliceExt {
        /// Returns the tier that applies to `value`, or `None` if it falls below
        /// every tier or above all of them.
        ///
        /// # The gap rule
        ///
        /// BO4E states tier bounds like `0 – 1000, 1001 – 2000` and rules that a
        /// value *between* two tiers *"rutscht in die obere Zone / Staffel"*, so
        /// `1000.6` bills at the `1001 – 2000` rate. A `von <= x <= bis` scan
        /// finds no tier for it at all.
        ///
        /// What satisfies both cases: **the tier with the smallest
        /// `staffelgrenzeBis` still ≥ `value`**, provided `value` reaches the
        /// lowest `staffelgrenzeVon`. Slice order is irrelevant. An absent bound
        /// is unbounded on that side, so an open-topped final tier catches
        /// everything above the last stated one.
        ///
        /// ```
        /// # #[cfg(all(feature = "versioned", feature = "decimal"))] {
        /// use rubo4e::convenience::PreisstaffelSliceExt;
        /// use rubo4e::current::Preisstaffel;
        /// use rust_decimal::Decimal;
        ///
        /// fn tier(von: i64, bis: i64, preis: i64) -> Preisstaffel {
        ///     Preisstaffel {
        ///         staffelgrenze_von: Some(Decimal::from(von)),
        ///         staffelgrenze_bis: Some(Decimal::from(bis)),
        ///         preis: Some(Decimal::from(preis)),
        ///         ..Default::default()
        ///     }
        /// }
        /// let staffeln = [tier(0, 1000, 30), tier(1001, 2000, 25)];
        ///
        /// let price = |v| staffeln.select_for(v).and_then(|s| s.preis);
        ///
        /// assert_eq!(price(Decimal::from(1000)), Some(Decimal::from(30)));  // upper bound: inside
        /// assert_eq!(price(Decimal::new(10006, 1)), Some(Decimal::from(25))); // in the gap: upward
        /// assert!(price(Decimal::from(5000)).is_none());                    // above every tier
        /// assert!(price(Decimal::from(-1)).is_none());                      // below every tier
        /// # }
        /// ```
        fn select_for(&self, value: Decimal) -> Option<&Preisstaffel>;
    }

    impl PreisstaffelSliceExt for [Preisstaffel] {
        fn select_for(&self, value: Decimal) -> Option<&Preisstaffel> {
            // Below the lowest stated floor there is no tier at all. A tier with
            // no `von` is unbounded below, so its presence removes the floor.
            let below_floor = self
                .iter()
                .all(|s| s.staffelgrenze_von.is_some_and(|von| value < von));
            if self.is_empty() || below_floor {
                return None;
            }

            // The tier whose ceiling is the tightest one still at or above the
            // value. An absent ceiling is +∞ and therefore always a candidate,
            // but loses to any stated ceiling that also fits.
            self.iter()
                .filter(|s| s.staffelgrenze_bis.is_none_or(|bis| value <= bis))
                .min_by(|a, b| match (a.staffelgrenze_bis, b.staffelgrenze_bis) {
                    (Some(x), Some(y)) => x.cmp(&y),
                    (Some(_), None) => std::cmp::Ordering::Less,
                    (None, Some(_)) => std::cmp::Ordering::Greater,
                    (None, None) => std::cmp::Ordering::Equal,
                })
        }
    }
}

// ── Rechnungsposition — decimal accessors ────────────────────────────────────

#[cfg(all(feature = "versioned", feature = "decimal"))]
mod rechnungsposition_decimal_impl {
    use crate::generated::v202607::Rechnungsposition;

    impl Rechnungsposition {
        /// Line item total (`gesamtpreis.wert`) as `Decimal`.
        ///
        /// Returns `None` when `gesamtpreis` is absent or its `wert` is `None`.
        ///
        /// ```no_run
        /// # #[cfg(all(feature = "versioned", feature = "decimal"))] {
        /// # use rubo4e::v202607::Rechnungsposition;
        /// let pos: Rechnungsposition = todo!();
        /// if let Some(net) = pos.gesamtpreis_decimal() {
        ///     println!("line total: {net}");
        /// }
        /// # }
        /// ```
        #[must_use]
        pub fn gesamtpreis_decimal(&self) -> Option<rust_decimal::Decimal> {
            self.gesamtpreis.as_ref()?.wert
        }

        /// Unit price (`einzelpreis.wert`) as `Decimal`.
        ///
        /// Returns `None` when `einzelpreis` is absent or its `wert` is `None`.
        #[must_use]
        pub fn einzelpreis_decimal(&self) -> Option<rust_decimal::Decimal> {
            self.einzelpreis.as_ref()?.wert
        }

        /// Quantity (`positions_menge.wert`) as `Decimal`.
        ///
        /// Returns `None` when `positions_menge` is absent or its `wert` is `None`.
        #[must_use]
        pub fn positions_menge_decimal(&self) -> Option<rust_decimal::Decimal> {
            self.positions_menge.as_ref()?.wert
        }

        /// Time-proportional quantity (`zeitbezogene_menge.wert`) as `Decimal`.
        ///
        /// Used for period-proportional pricing (e.g. 3 months of a yearly rate).
        /// Returns `None` when `zeitbezogene_menge` is absent or its `wert` is `None`.
        #[must_use]
        pub fn zeitbezogene_menge_decimal(&self) -> Option<rust_decimal::Decimal> {
            self.zeitbezogene_menge.as_ref()?.wert
        }
    }
}

// ── PreisblattNetznutzung ─────────────────────────────────────────────────────

#[cfg(all(feature = "versioned", feature = "time"))]
mod preisblatt_netznutzung_impl {
    use crate::generated::v202607::{PreisblattNetznutzung, Zeitraum};
    use time::Date;

    impl PreisblattNetznutzung {
        /// Returns the price sheet's validity bounds, either of which may be absent.
        ///
        /// Reads `gueltigkeit.startdatum` / `gueltigkeit.enddatum`. Both are
        /// **inclusive**: the sheet is still valid on its `enddatum`. An absent
        /// bound is an open end — an indefinitely-valid sheet has no `enddatum`.
        ///
        /// Returns `(None, None)` when `gueltigkeit` itself is absent, which is
        /// indistinguishable from an unbounded validity; use
        /// [`is_valid_at`](Self::is_valid_at) if you need the "no validity stated"
        /// case to read as *not valid*.
        ///
        /// ```no_run
        /// # #[cfg(all(feature = "versioned", feature = "time"))] {
        /// # use rubo4e::v202607::PreisblattNetznutzung;
        /// let p: PreisblattNetznutzung = todo!();
        /// match p.validity() {
        ///     (Some(start), Some(end)) => println!("valid {start} – {end} inclusive"),
        ///     (Some(start), None)      => println!("valid from {start} (open-ended)"),
        ///     (None, Some(end))        => println!("valid until {end} inclusive"),
        ///     (None, None)             => println!("no validity stated"),
        /// }
        /// # }
        /// ```
        #[must_use]
        pub fn validity(&self) -> (Option<Date>, Option<Date>) {
            self.gueltigkeit
                .as_ref()
                .map_or((None, None), Zeitraum::bounds)
        }

        /// Returns `true` if this price sheet's validity period contains `date`.
        ///
        /// Uses [`Zeitraum::contains`][crate::v202607::Zeitraum::contains] — a
        /// missing `gueltigkeit` is treated as
        /// "always invalid" (returns `false`).
        ///
        /// ```no_run
        /// # #[cfg(all(feature = "versioned", feature = "time"))] {
        /// # use rubo4e::v202607::PreisblattNetznutzung;
        /// # use time::macros::date;
        /// let sheets: Vec<PreisblattNetznutzung> = todo!();
        /// let billing_date = date!(2026-03-15);
        /// let valid = sheets.iter().find(|s| s.is_valid_at(billing_date));
        /// # }
        /// ```
        #[must_use]
        pub fn is_valid_at(&self, date: Date) -> bool {
            self.gueltigkeit.as_ref().is_some_and(|z| z.contains(date))
        }
    }
}