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
//! # bo4e
//!
//! 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 |
//! | `decimal` | | `rust_decimal::Decimal` for amounts/prices (see note below) |
//! | `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 |
//!
//! ## Identifiers without schema overhead
//!
//! All identifier types (`MaloId`, `MeloId`, `NeloId`, `EicCode`, `ObisCode`,
//! `MarktpartnerId`, `SrId`, `TrId`) **always** provide `Display`, `FromStr`,
//! `TryFrom<&str>`, `TryFrom<String>`, and `AsRef<str>` without any feature
//! flags — the minimum needed for EDIFACT wire-format encoding/decoding.
//!
//! To use only identifier types without pulling in the versioned BO4E schema:
//! ```toml
//! rubo4e = { version = "...", default-features = false, features = ["identifiers"] }
//! ```
//! This gives `serde` support on all identifiers with zero versioned-schema overhead.
//!
//! ## `serde` is enabled by default
//!
//! The default feature set is `default = ["identifiers"]`, and `identifiers`
//! enables `serde`. Targets that only need the type definitions for in-memory
//! processing can opt out:
//! ```toml
//! rubo4e = { version = "...", default-features = false, features = ["versioned"] }
//! ```
//!
//! ## Feature-conditional field types (`decimal` and `time`)
//!
//! Enabling `decimal` or `time` **changes the Rust type** of certain struct fields:
//!
//! | Feature | Without feature | With feature | Affected fields |
//! |-----------|---------------------|-----------------------------------------------------|----------------------------------------|
//! | `decimal` | `Option<String>` | `Option<rust_decimal::Decimal>` | `wert`, `preis`, amounts, quantities |
//! | `time` | `Option<String>` | `Option<time::OffsetDateTime>` or `Option<time::Date>` | `beginn`/`ende` fields → `OffsetDateTime`; `*datum` fields → `Date` |
//!
//! This means code that compiles under one feature configuration may not compile
//! under the other. For code that must be feature-agnostic, either:
//! - Always enable `decimal`/`time` and use the strong types, **or**
//! - Access fields through JSON round-trip (`to_json_german` / `from_json_german`)
//! which is feature-independent.
//!
//! The string fallback keeps the value's lexical form, so nothing is lost when
//! these features are absent.
//!
//! Decimal fields read a JSON number as well as a JSON string, because BO4E
//! producers use both — but only the string spelling is exact. A number has
//! already passed through `f64` before this crate sees it, losing its scale
//! (`119.00` → `119`) and any precision past ~15 significant digits.
//! [`decimal_serde`] documents the whole picture and counts every such read.
//!
//! ## `Eq` and `Hash` on generated structs
//!
//! Generated BO and COM structs always derive `PartialEq`. They additionally
//! derive **`Eq` and `Hash` when the `json` feature is off**, which is what lets
//! them key a `HashMap` or a `HashSet`.
//!
//! One type blocks both: `serde_json::Value`, which appears in a generated
//! struct twice when `json` is on — inside `LimitedExtensionMap` (the
//! `_additional` field) and as `ZusatzAttribut::wert`. `Value` is neither `Eq`
//! nor `Hash`, because it wraps `f64` and `NaN != NaN`. With `json` off both
//! degrade to a ZST stub and a `String`, and the whole tree becomes `Eq + Hash`.
//!
//! Generated **enums** are always `Eq + Ord + Hash`, whatever the features.
//!
//! For content-addressed equality across every feature set, compare
//! `to_json_canonical()` (from `Bo4eJsonExt` in the `json` module), which
//! produces a deterministic byte string.
/// 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.
/// Current stable BO4E schema version — always resolves to the latest stable schema
/// (`v202607` in this release).
///
/// 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.
/// Marker trait implemented by every generated BO4E business object (Geschäftsobjekt).
///
/// Provides runtime access to the BO type discriminant and the schema version that
/// was used to generate this type. COM types and enums do NOT implement this trait.
///
/// # Sealed trait
///
/// `Bo4eObject` is sealed — it cannot be implemented by types outside this crate.
/// This allows the library to add new methods in future releases without breaking
/// downstream code that merely *uses* the trait.
///
/// # Design note — associated type over bare return type
///
/// `bo_type()` returns `Self::BoTyp` (an associated type) so that the single trait
/// definition in `src/lib.rs` can serve all schema versions while keeping each
/// version's `BoTyp` enum strongly typed. For `dyn` usage, bind the associated type:
///
/// ```
/// use rubo4e::current::{BoTyp, Marktlokation, Vertrag};
/// use rubo4e::Bo4eObject;
///
/// let objects: Vec<Box<dyn Bo4eObject<BoTyp = BoTyp>>> = vec![
/// Box::new(Vertrag::default()),
/// Box::new(Marktlokation::default()),
/// ];
/// let types: Vec<BoTyp> = objects.iter().map(|o| o.bo_type()).collect();
/// assert_eq!(types, [BoTyp::Vertrag, BoTyp::Marktlokation]);
/// ```
///
/// # Example
/// ```
/// use rubo4e::current::{BoTyp, Vertrag};
/// use rubo4e::Bo4eObject as _;
///
/// let v = Vertrag::default();
/// assert_eq!(v.bo_type(), BoTyp::Vertrag);
/// assert_eq!(v.schema_version(), "202607.1.0"); // exact release
/// assert_eq!(v.schema_series(), "202607"); // the series this module covers
/// ```
/// Uniform introspection & strict-parsing surface implemented by **every**
/// generated BO4E enum (`Zaehlertyp`, `Marktrolle`, `BdewArtikelnummer`, …).
///
/// Every BO4E enum carries an `Unknown` forward-compatibility catch-all, so the
/// `serde` / `FromStr` deserialization path never fails on an unrecognized wire
/// value — it silently maps to `Unknown`. That is the right default for
/// forward-compatibility, but the wrong default at an ingest boundary that must
/// reject typos, legacy codes, or values from a newer schema. This trait gives
/// every enum, **without requiring the `strum` feature**:
///
/// - [`VARIANTS`](Bo4eEnum::VARIANTS) / [`COUNT`](Bo4eEnum::COUNT) — the known
/// variants and their count, for drift-guarding SQL `CHECK` lists and mappings.
/// - [`as_wire`](Bo4eEnum::as_wire) — the canonical BO4E wire string.
/// - [`from_wire`](Bo4eEnum::from_wire) — **strict** parsing that returns
/// [`Err`](crate::error::UnknownVariant) for out-of-schema values instead of
/// yielding `Unknown`.
/// - [`is_known`](Bo4eEnum::is_known) / [`is_unknown`](Bo4eEnum::is_unknown) —
/// detect a value that fell through to the `Unknown` catch-all after a lenient
/// `serde` round-trip.
///
/// The same members are also available as inherent methods on each enum, so you
/// rarely need to import this trait unless you are writing code generic over the
/// enum type (e.g. a generic `fn assert_covered<T: Bo4eEnum>()` that proves a
/// database `CHECK` list covers `T::VARIANTS`).
///
/// # 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` —
/// so an enum can key a `HashMap` or a `BTreeMap`, be sorted, and let a caller's
/// own struct derive `Ord`.
///
/// **`Ord` is declaration order, not a business ranking.** The variants follow
/// the order the BO4E schema lists them in, with the `Unknown` catch-all last.
/// It is a *total* order — which is all `BTreeMap` and `sort()` need — but a
/// schema release may reorder the values, so never persist a sort key derived
/// from it or compare two variants expecting a domain meaning. Compare
/// [`as_wire`](Bo4eEnum::as_wire) when the order has to be stable across
/// releases.
///
/// # 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.
///
/// # Not sealed
///
/// Unlike [`Bo4eObject`] 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 types.
///
/// `use rubo4e::prelude::*;` gives you:
///
/// - **every** identifier type and its error type — always;
/// - [`Bo4eJsonExt`](crate::json::Bo4eJsonExt) and
/// [`Bo4eExtensionData`](crate::json::Bo4eExtensionData), with `json`;
/// - [`Bo4eObject`], [`Bo4eEnum`], and [`Bo4eStrict`], with `versioned`;
/// - [`Validate`](garde::Validate), [`Validated`](crate::validation::Validated),
/// and the report helpers, with `validate`;
/// - the COM extension traits [`BetragExt`](crate::convenience::BetragExt),
/// [`MengeExt`](crate::convenience::MengeExt),
/// [`PreisExt`](crate::convenience::PreisExt), and
/// [`PreisstaffelSliceExt`](crate::convenience::PreisstaffelSliceExt), with
/// `versioned` + `decimal`.
///
/// It deliberately does **not** re-export the generated BO/COM types: they are
/// version-scoped, and `use rubo4e::current::*` is the import that says which
/// schema series you meant.
///
/// `tests/prelude_surface.rs` holds the guard that keeps the first bullet true.