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
//! # rubo4e
//!
//! Rust implementation of the **BO4E** energy-market data standard.
//!
//! ## Feature gates
//!
//! | Feature | Default | Description |
//! |----------------|---------|----------------------------------------------------------------|
//! | `identifiers` | ✓ | Identifier types (`MaloId`, `EicCode`, `ObisCode`, …) + serde |
//! | `serde` | ✓ | Serde derives + extension-data map |
//! | `json` | | `serde_json` helpers (`to_json_*`, `from_json_*`) |
//! | `time` | | `time` crate for timestamps; also `utoipa/time` |
//! | `decimal` | | `rust_decimal::Decimal` for amounts/prices (see note below); also `schemars/rust_decimal1` and `utoipa/decimal` |
//! | `builder` | | `typed-builder` derives with `setter(into)` — accepts both `T` and `Option<T>` |
//! | `validate` | | `garde` validation |
//! | `schemars` | | JSON Schema generation |
//! | `sqlx` | | `sqlx` type integrations |
//! | `utoipa` | | `utoipa` OpenAPI integrations |
//! | `strum` | | Enum iteration and string conversion |
//! | `versioned` | | Expose the versioned schema module (`v202607`) |
//! | `tracing` | | Structured diagnostics via the `tracing` crate |
//! | `metrics` | | Optional export hooks via the `metrics` crate |
//!
//! ## Where to start
//!
//! | You want to | Look at |
//! |---|---|
//! | Read or write a BO4E payload | [`current`], [`json::Bo4eJsonExt`] |
//! | Reject a payload that carries an out-of-schema value | [`Bo4eStrict`], [`Bo4eEnum`] |
//! | Check that a document you produced uses only fields BO4E defines | [`json::Bo4eExtensions`] |
//! | Check a market identifier | [`identifiers`] |
//! | Check a document against BO4E's own rules | [`validation`] |
//! | Work with a `Lastgang`, `Zeitreihe` or `Zaehlwerk` | [`timeseries`] |
//! | Convert between units, or turn power into energy | [`units`] |
//!
//! ## Feature-conditional field types (`decimal` and `time`)
//!
//! Enabling `decimal` or `time` **changes the Rust type** of certain fields, so
//! code written against one configuration may not compile under the other:
//!
//! | Feature | Without | With |
//! |-----------|-------------------|--------------------------------------------------------|
//! | `decimal` | `Option<String>` | `Option<rust_decimal::Decimal>` |
//! | `time` | `Option<String>` | `Option<time::OffsetDateTime>` / `Option<time::Date>` |
//!
//! The string fallback keeps the value's lexical form, so nothing is lost.
//!
//! Decimal fields read a JSON number as well as a JSON string, because BO4E
//! producers use both — but only the string spelling is exact. See
//! [`decimal_serde`], which also counts every number read.
//!
//! ## `Eq` and `Hash` on generated structs
//!
//! Generated structs always derive `PartialEq`, and additionally `Eq + Hash`
//! **when `json` is off** — so a BO can key a `HashMap`. `serde_json::Value`
//! blocks both, and it appears twice with `json` on: in `LimitedExtensionMap` and
//! as `ZusatzAttribut::wert`. Generated **enums** are always `Eq + Ord + Hash`.
//!
//! For content-addressed equality under any feature set, compare
//! `to_json_canonical()` from [`json::Bo4eJsonExt`].
//!
//! ## Identifiers without the schema
//!
//! `default = ["identifiers"]` gives the identifier newtypes and `serde`, with no
//! versioned-schema overhead. Every identifier provides `Display`, `FromStr`,
//! `TryFrom`, `AsRef<str>`, `Borrow<str>` and `Deref<Target = str>` unfeatured —
//! the minimum an EDIFACT encoder needs.
//!
//! ```toml
//! rubo4e = { version = "...", default-features = false, features = ["identifiers"] }
//! ```
/// Error types returned by identifier construction.
/// JSON serialization helpers: `json::Bo4eJsonExt` with `to_json_german()`,
/// `to_json_snake_case()`, and `to_json_canonical()`.
/// Always-available re-export of `json::extension::LimitedExtensionMap`.
///
/// When the `json` feature is **active** this is the real DoS-hardened extension
/// map. When `json` is **inactive** it degrades to a zero-sized stub that is
/// `Debug + Clone + Default + PartialEq` but carries no data. All generated
/// BO/COM structs use `crate::LimitedExtensionMap` as their `_additional` field
/// type so that the field can be declared once without a `#[cfg]` branch.
pub use LimitedExtensionMap;
/// Zero-sized stub used when the `json` feature is disabled.
///
/// See the `json`-feature variant for the full description.
;
/// Cross-field business-rule validators for BO4E types (requires `validate` + `versioned`).
/// Also exports `Validated<T>` which only requires `validate`.
/// Schema helper functions used by generated schemars attributes.
///
/// Provides `"format": "date-time"` and `"format": "date"` JSON Schema
/// annotations for `time::OffsetDateTime` and `time::Date` fields, which
/// schemars 1.x does not emit automatically.
/// Serde modules for `time::Date` fields in generated structs.
///
/// - [`time_serde::date_serde`] — required `time::Date` ↔ `"YYYY-MM-DD"`
/// - [`time_serde::opt_date_serde`] — `Option<time::Date>` ↔ `"YYYY-MM-DD"` or `null`
///
/// These are referenced from generated code via
/// `#[serde(with = "crate::time_serde::opt_date_serde")]`.
///
/// The module is pure serde glue, so it needs `serde` as well as `time`; the
/// generated `serde(with = …)` attributes that reference it are themselves
/// gated on `serde`.
/// Time-of-day parsing for BO4E's `format: "time"` fields.
///
/// `Zeitraum.startuhrzeit`, `.enduhrzeit`, and `Umschaltzeit.umschaltzeit` carry
/// a UTC offset (`"18:00:00+01:00"`), which no `time` type holds alongside a
/// time of day — so the fields stay `String` and this reads them.
/// ISO 8601 duration parsing for BO4E's `dauer` fields.
///
/// `Zeitraum.dauer` is a string like `"P1DT30H4S"` that neither `serde` nor
/// `time` parses. Years and months are refused rather than approximated — see
/// the module docs.
/// Decimal deserialization, and what BO4E's two spellings of a number cost.
///
/// BO4E-python writes `"wert": "119.00"`, go-bo4e writes `"wert": 119.00`.
/// Both are read; only the string spelling is exact. See the module docs, and
/// [`decimal_serde::decimal_from_json_number_count`] for the counter that tells
/// you which one your producers use.
/// Strict-decoding support: reject out-of-schema (`Unknown`) enum values anywhere
/// in a deserialized payload. See [`Bo4eStrict`] and [`strict::StrictError`].
// Generator output. Run `just generate` to populate or refresh it.
//
// This holds two independently gated things: the versioned schema modules
// (`versioned`) and the wire-key ↔ snake_case map the JSON key transforms need
// (`json`). Neither feature implies the other, so the module is compiled when
// either is on and its contents are gated individually in the generated
// `mod.rs`.
/// Hand-written convenience methods on generated BO4E types.
///
/// Provides ergonomic accessors such as [`Zeitraum::as_inclusive_range`][az],
/// [`Rechnung::billing_period`][bp], and [`PreisblattNetznutzung::validity`][va].
///
/// All methods are gated on the feature flags that make their return types
/// available (`versioned`, `time`, `decimal`).
///
/// [az]: crate::current::Zeitraum::as_inclusive_range
/// [bp]: crate::current::Rechnung::billing_period
/// [va]: crate::current::PreisblattNetznutzung::validity
/// BO4E schema v202607 types.
/// The latest stable BO4E schema series this crate ships — currently `v202607`.
///
/// Prefer `use rubo4e::current::Foo` over `use rubo4e::v202607::Foo` so that
/// imports remain valid across schema version bumps without any code changes.
///
/// # rust-analyzer / IDE note
///
/// Because this is a true `pub mod` (not a `pub use … as` alias), IDE tooling
/// and rust-analyzer resolve hover types and auto-import suggestions as
/// `rubo4e::current::Foo` rather than the underlying versioned path.
/// The `_typ` discriminant, as constants — implemented by every generated BO
/// **and** COM.
///
/// BO4E pins each schema's `_typ` with a `const`, and this exposes it without a
/// value, so a gate at a wire boundary can read the discriminant of a type it
/// only knows generically:
///
/// ```
/// use rubo4e::{current::{Adresse, Marktlokation}, Bo4eTyped};
///
/// fn wire_typ<T: Bo4eTyped>() -> &'static str { T::TYP_WIRE }
///
/// assert_eq!(wire_typ::<Marktlokation>(), "MARKTLOKATION"); // a BO
/// assert_eq!(wire_typ::<Adresse>(), "ADRESSE"); // a COM
/// ```
///
/// [`Bo4eObject`] and [`Bo4eComponent`] narrow this to the Geschäftsobjekte and
/// the components; bind [`Typ`](Bo4eTyped::Typ) through either when you need the
/// discriminant as its own enum rather than as a string.
///
/// Every generated struct implements it except `ZusatzAttribut`, the one BO4E
/// schema that declares no `_typ`. Sealed: not implementable outside this crate.
///
/// # Not `dyn`-compatible
///
/// Associated constants make a trait dyn-incompatible. For a heterogeneous
/// collection of BOs use [`AnyBo`](crate::current::AnyBo), the sum type over
/// exactly [`Bo4eObject`]'s implementors — it carries the same facts and is
/// `Clone + PartialEq + Serialize + Deserialize` besides.
/// Marks a generated **Geschäftsobjekt** — the BO4E types that stand on their
/// own as a message payload.
///
/// Everything it carries comes from [`Bo4eTyped`]; this narrows the set, and
/// pins [`Typ`](Bo4eTyped::Typ) to `BoTyp`:
///
/// ```
/// use rubo4e::{current::{BoTyp, Lastgang, Vertrag}, Bo4eObject};
///
/// // No value needed, so no `Default` bound — which is what admits `Lastgang`
/// // and `Tarif`, the two types the schema marks `required`.
/// fn discriminant_of<T: Bo4eObject<Typ = BoTyp>>() -> BoTyp { T::TYP }
///
/// assert_eq!(discriminant_of::<Vertrag>(), BoTyp::Vertrag);
/// assert_eq!(discriminant_of::<Lastgang>(), BoTyp::Lastgang);
/// ```
///
/// Sealed: not implementable outside this crate.
/// Marks a generated **component** (COM) — the BO4E types that appear nested
/// inside a Geschäftsobjekt rather than on their own.
///
/// The counterpart of [`Bo4eObject`], with [`Typ`](Bo4eTyped::Typ) pinned to
/// `ComTyp`: `fn f<T: Bo4eComponent<Typ = ComTyp>>()` takes `Adresse` and
/// `Betrag` the way the example there takes `Vertrag` and `Lastgang`.
///
/// Sealed: not implementable outside this crate.
/// Uniform introspection & strict-parsing surface implemented by **every**
/// generated BO4E enum (`Zaehlertyp`, `Marktrolle`, `BdewArtikelnummer`, …).
///
/// Every BO4E enum carries an `Unknown` catch-all, so the `serde` / `FromStr`
/// path never fails on an unrecognized wire value — right for forward
/// compatibility, wrong at an ingest boundary. These members close that gap
/// **without the `strum` feature**.
///
/// They are inherent methods too, so importing the trait matters only for code
/// generic over the enum type.
///
/// # Example
/// ```
/// use rubo4e::{current::Zaehlertyp, Bo4eEnum};
///
/// // Introspection without `strum`:
/// assert_eq!(Zaehlertyp::COUNT, Zaehlertyp::VARIANTS.len());
///
/// // Strict parsing at the ingest boundary:
/// assert_eq!(Zaehlertyp::from_wire("WASSERZAEHLER"), Ok(Zaehlertyp::Wasserzaehler));
/// assert!(Zaehlertyp::from_wire("NOT_A_REAL_VALUE").is_err());
///
/// // Detect lenient-decode fall-through:
/// # #[cfg(feature = "json")] {
/// let z: Zaehlertyp = serde_json::from_str("\"BOGUS\"").unwrap();
/// assert!(z.is_unknown());
/// # }
/// ```
///
/// # Derived traits on every BO4E enum
///
/// `Debug`, `Clone`, `Copy`, `PartialEq`, `Eq`, `PartialOrd`, `Ord`, `Hash`.
///
/// **`Ord` is declaration order, not a business ranking** — schema order, with
/// `Unknown` last. Total, so `BTreeMap` and `sort()` work, but a schema release
/// may reorder the values: never persist a sort key derived from it. Compare
/// [`as_wire`](Bo4eEnum::as_wire) where the order must be stable.
///
/// # Sealed trait
///
/// `Bo4eEnum` is sealed — it cannot be implemented outside this crate.
/// Recursive strict-decode check: find every out-of-schema (`Unknown`) enum value
/// anywhere inside a deserialized BO4E value.
///
/// Implemented by **every** generated BO, COM, and enum, and by `AnyBo`. Because
/// the `serde` path is intentionally lenient (unknown wire values decode to
/// `Unknown` for forward-compatibility), this trait is how you make the popular
/// "round-trip as validation" pattern *actually* strict at an ingest boundary,
/// with a single call instead of hand-checking every enum field:
///
/// ```
/// # #[cfg(feature = "json")] {
/// use rubo4e::{current::Messlokation, Bo4eStrict};
///
/// let body = r#"{"messlokationsId":"DE0123456789012345678901234567890","sparte":"PLASMA"}"#;
/// let melo: Messlokation = serde_json::from_str(body).unwrap(); // lenient decode
///
/// // 422 if any Unknown, anywhere:
/// assert_eq!(melo.unknown_enum_paths(), ["sparte"]);
/// assert!(melo.ensure_known_enums().is_err());
/// # }
/// ```
///
/// Paths are reported relative to the checked value, using dotted field names and
/// bracketed array indices (e.g. `zaehler[0].zaehlertyp`). The field names are the
/// BO4E wire (camelCase) names, matching the JSON you deserialized from.
///
/// # It checks values, not fields
///
/// A payload can fall outside the schema in two ways, and this covers one of
/// them. An unrecognised **value** in a declared field decodes to `Unknown` and
/// is found here. An unrecognised **field** never reaches an enum at all — it
/// lands in extension data, the decode succeeds, and this reports nothing.
/// [`Bo4eExtensions::ensure_no_extension_data`](crate::json::Bo4eExtensions::ensure_no_extension_data)
/// is the sibling that finds those.
///
/// # Not sealed
///
/// Unlike [`Bo4eTyped`] and [`Bo4eEnum`], `Bo4eStrict` is intentionally **not**
/// sealed: downstream crates that wrap BO4E types in their own domain types can
/// implement it to make their wrappers participate in the same recursive check.
/// Re-exports the most commonly used traits and every identifier type.
///
/// | Feature | Brings in |
/// |---|---|
/// | always | every identifier type and [`IdentifierError`](crate::error::IdentifierError) |
/// | `versioned` | [`Bo4eTyped`], [`Bo4eObject`], [`Bo4eComponent`], [`Bo4eEnum`], [`Bo4eStrict`], [`Dimension`](crate::units::Dimension) |
/// | `json` | [`Bo4eJsonExt`](crate::json::Bo4eJsonExt), [`Bo4eExtensionData`](crate::json::Bo4eExtensionData), [`Bo4eExtensions`](crate::json::Bo4eExtensions) |
/// | `validate` | [`Validate`](garde::Validate), [`Validated`](crate::validation::Validated), the report helpers |
/// | `+ decimal` | [`BetragExt`](crate::convenience::BetragExt), [`MengeExt`](crate::convenience::MengeExt), [`PreisExt`](crate::convenience::PreisExt), [`PreisstaffelSliceExt`](crate::convenience::PreisstaffelSliceExt) |
/// | `+ time` | [`Bo4eTimeSeries`](crate::timeseries::Bo4eTimeSeries) |
///
/// Not the generated BO/COM types: those are version-scoped, and
/// `use rubo4e::current::*` is the import that says which series you meant.
///
/// `tests/prelude_surface.rs` guards the identifier row.