Skip to main content

mako_engine/
marktrolle.rs

1//! BDEW Rollenmodell — market-participant role configuration.
2//!
3//! The BDEW Rollenmodell für die Marktkommunikation (V2.2, January 2026) explicitly
4//! permits a single legal entity to hold multiple market roles simultaneously.
5//! Common combinations:
6//!
7//! | Combination | Regulatory basis |
8//! |---|---|
9//! | NB + gMSB | §41 MsbG — NB is grundzuständiger MSB for basic meters |
10//! | NB + BKV | Stadtwerke managing their own balance group |
11//! | NB + LF | Vertically integrated utility |
12//! | LF + BKV | Supplier managing its own balance group |
13//!
14//! ## Why role-awareness matters for PID routing
15//!
16//! Several EDIFACT PIDs are **shared across process families** and their correct
17//! inbound destination depends on which role this `makod` instance fills:
18//!
19//! | PID | ORDRSP semantics |
20//! |---|---|
21//! | 19001 (Bestellbestätigung) | → `gpke-konfiguration` when NB receiving from MSB |
22//! | 19001 (Bestellbestätigung) | → `wim-geraeteubernahme` when nMSB receiving from NB |
23//! | 19015 (Bestätigung Gerätewechselabsicht) | → `wim-geraeteubernahme` when NB receiving from nMSB |
24//! | 13003 (MSCONS Summenzeitreihe) | → `mabis-billing` when BKV receiving from BIKO |
25//! | 13003 (MSCONS Summenzeitreihe) | → MaBiS NZR handler when NB receiving from NB |
26//!
27//! By declaring which roles a `makod` instance serves, the engine can register
28//! only the PID routes that apply, preventing both silent dead-letters and
29//! accidental misrouting.
30//!
31//! ## Conflict guard
32//!
33//! [`PidRouter`] panics at build time if two modules register the same PID to
34//! **different** workflow names. Set explicit [`DeploymentRoles`] to exclude
35//! conflicting registrations from modules that don't apply to this instance.
36//!
37//! [`PidRouter`]: crate::pid_router::PidRouter
38
39use std::collections::HashSet;
40
41// ── Marktrolle ────────────────────────────────────────────────────────────────
42
43/// A BDEW market-participant role (Marktrolle).
44///
45/// Declares which roles this `makod` deployment fills within the German energy
46/// market communication (MaKo) ecosystem. A single deployment may hold several
47/// roles simultaneously (see module-level docs).
48///
49/// # Non-exhaustive
50///
51/// New roles may be added as BDEW regulations expand. Match with `_` in
52/// exhaustive arms or use [`DeploymentRoles::contains`] for membership checks.
53#[non_exhaustive]
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
55pub enum Marktrolle {
56    /// Netzbetreiber (NB) — distribution/transmission network operator.
57    ///
58    /// Receives the GPKE ANFRAGE — 55001 (Anmeldung / Lieferbeginn) and 55004
59    /// (Abmeldung / Lieferende) — and issues the matching ANTWORT pair:
60    /// 55002 Bestätigung / 55003 Ablehnung, 55005 Bestätigung / 55006 Ablehnung.
61    /// Also runs GPKE Konfiguration (17134/17135 outbound ORDERS, 19001/19002
62    /// inbound ORDRSP). The Kündigung (55016 → 55017/55018) is an LFN↔LFA
63    /// exchange, not an NB ANFRAGE.
64    Nb,
65
66    /// Lieferant (LF) — energy supplier.
67    ///
68    /// Initiates GPKE Lieferbeginn (55001) and Lieferende (55004), and receives
69    /// the ANTWORT from the NB. Registers as inbound-ANTWORT recipient for
70    /// 55002/55003, 55005/55006 and 55017/55018 in the LF-side anmeldung
71    /// workflow.
72    Lf,
73
74    /// grundzuständiger Messstellenbetreiber (gMSB) — incumbent meter operator.
75    ///
76    /// In the WiM MSB-Wechsel (BK6-24-174) receives the Verpflichtungsanfrage/
77    /// Aufforderung (55168, NB→gMSB); also handles WiM Zählerstand/Konfiguration
78    /// (11001–11003, MSCONS/UTILTS). Often the same legal entity as the NB (§41 MsbG).
79    Msb,
80
81    /// nicht-grundzuständiger Messstellenbetreiber (nMSB) — challenger meter operator.
82    ///
83    /// Sends the WiM MSB-Wechsel Anmeldung (55042, MSBN→NB) and Kündigung MSB
84    /// (55039, MSBN→MSBA), plus WiM Geräteübernahme ORDERS (17001, 17009).
85    /// Receives inbound ORDRSP responses 19001/19002 (Bestellbestätigung/Ablehnung)
86    /// and 19015/19016 (Gerätewechselabsicht).
87    Nmsb,
88
89    /// abgebender Messstellenbetreiber (aMSB) — outgoing meter operator.
90    ///
91    /// Receives the Kündigung MSB (55039, from the nMSB) and sends Ende MSB /
92    /// Abmeldung (55051, MSBA→NB). This role is often held by the gMSB after a
93    /// successful nMSB takeover.
94    Amsb,
95
96    /// Bilanzkreisverantwortlicher (BKV) — balance responsible party.
97    ///
98    /// Receives MABIS billing MSCONS (PID 13003 from BIKO: Abrechnungssummenzeitreihe).
99    Bkv,
100
101    /// Übertragungsnetzbetreiber (ÜNB) — transmission system operator.
102    ///
103    /// Issues BG-SZR Kategorie B/C and BK-SZR Kategorie B/C MSCONS (PID 13003).
104    Uenb,
105
106    /// Bilanzkoordinator (BIKO) — balancing coordinator.
107    ///
108    /// Issues Abrechnungssummenzeitreihe MSCONS (PID 13003) to BKV and NB-DZR.
109    Biko,
110
111    /// Energieserviceanbieter (ESA) — energy service provider acting for the
112    /// Anschlussnutzer (PARTIN 37006, "Kommunikationsdaten des ESA Strom").
113    ///
114    /// **Strom only.** An ESA has no Zuordnung to a Marktlokation: its access to
115    /// values rests on the Anschlussnutzer's consent (§49 Abs. 2 Nr. 9 MsbG) and
116    /// a bilateral contract with the MSB, which §34 Abs. 2 S. 2 Nr. 10 MsbG makes
117    /// a mandatory, non-discriminatory Zusatzleistung.
118    ///
119    /// Sends REQOTE 35003 (Werteanfrage), ORDERS 17007 (Bestellung), ORDERS
120    /// 17008 (Abbestellung) and ORDCHG 39002 (Stornierung); receives QUOTES
121    /// 15003, ORDRSP 19011–19014 and IFTSTA 21042, plus the values themselves
122    /// as MSCONS 13027.
123    ///
124    /// 17007 and 17008 are **different** Prüfidentifikatoren: one orders a
125    /// delivery, the other ends a running one, and their answers cite different
126    /// Entscheidungsbäume (`E_0256` vs `E_0254`).
127    ///
128    /// This role is for a deployment that **is** an ESA. An MSB *serving* an ESA
129    /// registers the inbound side under [`Marktrolle::Msb`].
130    Esa,
131
132    /// Gasnetzbetreiber (GNB) — gas network operator (GeLi Gas counterpart of NB).
133    ///
134    /// Receives GeLi Gas Lieferbeginn/Lieferende ANFRAGE messages (44001 ff.)
135    /// and issues the corresponding ANTWORT messages (44003–44006).
136    Gnb,
137
138    /// Lieferant Gas (LFG) — gas supplier (GeLi Gas counterpart of LF).
139    ///
140    /// Initiates GeLi Gas Lieferbeginn/Lieferende (44001/44002) and receives
141    /// the GNB's ANTWORT messages.
142    Lfg,
143
144    /// Lieferant neu (LFN) — the incoming supplier in a Lieferantenwechsel.
145    ///
146    /// Distinct from the generic [`Marktrolle::Lf`] where a process step is
147    /// specific to the *gaining* side of a switch.
148    Lfn,
149
150    /// Lieferant alt (LFA) — the outgoing supplier in a Lieferantenwechsel.
151    ///
152    /// Distinct from the generic [`Marktrolle::Lf`] where a process step is
153    /// specific to the *losing* side of a switch.
154    Lfa,
155
156    /// Marktgebietsverantwortlicher (MGV) — gas market-area manager.
157    ///
158    /// **Gas only.** Operates the Virtueller Handelspunkt and GaBi Gas
159    /// balancing (THE in Germany). Declares its communication data via
160    /// PARTIN 37011 ("Kommunikationsdaten des MGV Gas").
161    Mgv,
162}
163
164impl Marktrolle {
165    /// The canonical upper-case BDEW role code (e.g. `"NB"`, `"ÜNB"`, `"LFG"`).
166    #[must_use]
167    pub const fn as_code(self) -> &'static str {
168        match self {
169            Self::Nb => "NB",
170            Self::Lf => "LF",
171            Self::Msb => "MSB",
172            Self::Nmsb => "NMSB",
173            Self::Amsb => "AMSB",
174            Self::Bkv => "BKV",
175            Self::Uenb => "ÜNB",
176            Self::Biko => "BIKO",
177            Self::Esa => "ESA",
178            Self::Gnb => "GNB",
179            Self::Lfg => "LFG",
180            Self::Lfn => "LFN",
181            Self::Lfa => "LFA",
182            Self::Mgv => "MGV",
183        }
184    }
185
186    /// Parse a canonical upper-case BDEW role code back into a [`Marktrolle`].
187    ///
188    /// Round-trips [`as_code`] exactly (including the umlaut in `"ÜNB"`).
189    /// Returns `None` for anything else — callers decide whether an unknown
190    /// code is an error or simply "not one of ours".
191    ///
192    /// [`as_code`]: Marktrolle::as_code
193    #[must_use]
194    pub fn from_code(code: &str) -> Option<Self> {
195        Some(match code {
196            "NB" => Self::Nb,
197            "LF" => Self::Lf,
198            "MSB" => Self::Msb,
199            "NMSB" => Self::Nmsb,
200            "AMSB" => Self::Amsb,
201            "BKV" => Self::Bkv,
202            "ÜNB" => Self::Uenb,
203            "BIKO" => Self::Biko,
204            "ESA" => Self::Esa,
205            "GNB" => Self::Gnb,
206            "LFG" => Self::Lfg,
207            "LFN" => Self::Lfn,
208            "LFA" => Self::Lfa,
209            "MGV" => Self::Mgv,
210            _ => return None,
211        })
212    }
213
214    /// Map a PARTIN Prüfidentifikator to the sender's [`Marktrolle`].
215    ///
216    /// PARTIN (PIDs 37000–37014) distributes market-participant communication
217    /// data; the PID identifies the sender's role:
218    ///
219    /// | PID | Sender | `Marktrolle` |
220    /// |---|---|---|
221    /// | 37000 | LF Strom | [`Lf`](Self::Lf) |
222    /// | 37001 | NB Strom | [`Nb`](Self::Nb) |
223    /// | 37002 | MSB Strom | [`Msb`](Self::Msb) |
224    /// | 37003 | BKV Strom | [`Bkv`](Self::Bkv) |
225    /// | 37004 | BIKO Strom | [`Biko`](Self::Biko) |
226    /// | 37005 | ÜNB Strom | [`Uenb`](Self::Uenb) |
227    /// | 37006 | ESA Strom | [`Esa`](Self::Esa) |
228    /// | 37008 | LF Gas | [`Lfg`](Self::Lfg) |
229    /// | 37009 | NB Gas | [`Gnb`](Self::Gnb) |
230    /// | 37010 | MSB Gas | [`Msb`](Self::Msb) |
231    /// | 37011 | MGV Gas | [`Mgv`](Self::Mgv) |
232    /// | 37012 | NB Gas (spartenübergreifend) | [`Gnb`](Self::Gnb) |
233    /// | 37013 | MSB Gas (spartenübergreifend) | [`Msb`](Self::Msb) |
234    /// | 37014 | MSB Strom (spartenübergreifend) | [`Msb`](Self::Msb) |
235    ///
236    /// Returns `None` for unrecognised codes (37007 is a gap in the AHB).
237    #[must_use]
238    pub fn from_partin_pid(pid: u32) -> Option<Self> {
239        match pid {
240            37000 => Some(Self::Lf),
241            37001 => Some(Self::Nb),
242            37002 | 37010 | 37013 | 37014 => Some(Self::Msb),
243            37003 => Some(Self::Bkv),
244            37004 => Some(Self::Biko),
245            37005 => Some(Self::Uenb),
246            37006 => Some(Self::Esa),
247            37008 => Some(Self::Lfg),
248            37009 | 37012 => Some(Self::Gnb),
249            37011 => Some(Self::Mgv),
250            _ => None,
251        }
252    }
253}
254
255// Serde representation: the canonical BDEW role code (`"NB"`, `"ÜNB"`, `"LFG"`, …).
256// Used verbatim in persisted partner records and API payloads, so the wire
257// format matches EDIFACT/BO4E role codes exactly.
258impl serde::Serialize for Marktrolle {
259    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
260        serializer.serialize_str(self.as_code())
261    }
262}
263
264impl<'de> serde::Deserialize<'de> for Marktrolle {
265    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
266        let code = String::deserialize(deserializer)?;
267        Self::from_code(&code)
268            .ok_or_else(|| serde::de::Error::custom(format!("unknown Marktrolle code {code:?}")))
269    }
270}
271
272impl std::fmt::Display for Marktrolle {
273    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274        f.write_str(self.as_code())
275    }
276}
277
278// ── DeploymentRoles ───────────────────────────────────────────────────────────
279
280/// The set of [`Marktrolle`]s this `makod` deployment fills.
281///
282/// Used by [`EngineModule::register_pids_with_roles`] to conditionally register
283/// PID routes based on which roles are active. Modules check
284/// `roles.contains(Marktrolle::Nb)` before registering role-specific PIDs.
285///
286/// # Constructors
287///
288/// - [`DeploymentRoles::all()`] — registers everything regardless of role
289///   (useful for development and single-role deployments, default).
290/// - [`DeploymentRoles::from_roles`] — explicit set for multi-role conflict resolution.
291/// - Convenience methods: [`nb()`], [`lf()`], [`msb()`], [`nmsb()`] etc.
292///
293/// # Conflict guard
294///
295/// When two modules both register the same PID to **different** workflow names,
296/// `EngineBuilder::build` will detect the conflict and panic. Set exclusive roles
297/// to ensure only one workflow is registered per shared PID:
298///
299/// ```rust,ignore
300/// // NB deployment: GPKE registers 19001/19002 → gpke-konfiguration
301/// // nMSB deployment: WiM registers 19001/19002 → wim-geraeteubernahme
302/// // Combined (conflict!): set roles to prevent double-registration:
303/// use mako_engine::marktrolle::{DeploymentRoles, Marktrolle};
304///
305/// let roles = DeploymentRoles::from_roles([Marktrolle::Nb]);
306/// // Now only GPKE registers 19001/19002; WiM skips its nMSB-conditional block.
307/// ```
308///
309/// [`EngineModule::register_pids_with_roles`]: crate::builder::EngineModule::register_pids_with_roles
310/// [`nb()`]: DeploymentRoles::nb
311/// [`lf()`]: DeploymentRoles::lf
312/// [`msb()`]: DeploymentRoles::msb
313/// [`nmsb()`]: DeploymentRoles::nmsb
314#[derive(Debug, Clone)]
315pub struct DeploymentRoles {
316    /// When `true`, `contains()` returns `true` for every role (matches all).
317    all: bool,
318    roles: HashSet<Marktrolle>,
319}
320
321impl Default for DeploymentRoles {
322    /// Defaults to `all` — every role is considered active.
323    ///
324    /// This preserves backward-compatible behavior (all PIDs registered) for
325    /// deployments that have not yet configured explicit roles. Set explicit
326    /// roles via [`DeploymentRoles::from_roles`] for multi-role conflict safety.
327    fn default() -> Self {
328        Self::all()
329    }
330}
331
332impl DeploymentRoles {
333    /// All roles active — `contains` always returns `true`.
334    ///
335    /// The default for `EngineBuilder`. Modules register all their PIDs
336    /// unconditionally, identical to the pre-role-aware behavior.
337    ///
338    /// **Warning:** if two modules register the same PID to different workflows
339    /// and `all()` is active, the conflict guard in `PidRouter` will panic at
340    /// build time. Use [`from_roles`] to specify exactly which roles apply.
341    ///
342    /// [`from_roles`]: DeploymentRoles::from_roles
343    #[must_use]
344    pub fn all() -> Self {
345        Self {
346            all: true,
347            roles: HashSet::new(),
348        }
349    }
350
351    /// Construct from an explicit set of active roles.
352    ///
353    /// Only modules whose role-conditional PID blocks include at least one of
354    /// these roles will register those PIDs. All non-role-conditional PID blocks
355    /// (i.e., those that don't call `roles.contains(...)`) are always registered.
356    #[must_use]
357    pub fn from_roles(roles: impl IntoIterator<Item = Marktrolle>) -> Self {
358        Self {
359            all: false,
360            roles: roles.into_iter().collect(),
361        }
362    }
363
364    /// Return `true` when `role` is active.
365    ///
366    /// Always returns `true` for [`DeploymentRoles::all()`].
367    #[must_use]
368    pub fn contains(&self, role: Marktrolle) -> bool {
369        self.all || self.roles.contains(&role)
370    }
371
372    /// Return `true` when this is the [`all()`] sentinel (no explicit role list).
373    ///
374    /// [`all()`]: DeploymentRoles::all
375    #[must_use]
376    pub fn is_all(&self) -> bool {
377        self.all
378    }
379
380    // ── Convenience constructors ──────────────────────────────────────────────
381
382    /// NB-only deployment (most common for grid operators).
383    #[must_use]
384    pub fn nb() -> Self {
385        Self::from_roles([Marktrolle::Nb])
386    }
387
388    /// ESA-only deployment (energy service provider side).
389    #[must_use]
390    pub fn esa() -> Self {
391        Self::from_roles([Marktrolle::Esa])
392    }
393
394    /// LF-only deployment (supplier side).
395    #[must_use]
396    pub fn lf() -> Self {
397        Self::from_roles([Marktrolle::Lf])
398    }
399
400    /// gMSB-only deployment (incumbent meter operator).
401    #[must_use]
402    pub fn msb() -> Self {
403        Self::from_roles([Marktrolle::Msb])
404    }
405
406    /// nMSB-only deployment (challenger meter operator).
407    #[must_use]
408    pub fn nmsb() -> Self {
409        Self::from_roles([Marktrolle::Nmsb])
410    }
411
412    /// NB + gMSB (most common municipal utility / Stadtwerke combination).
413    #[must_use]
414    pub fn nb_msb() -> Self {
415        Self::from_roles([Marktrolle::Nb, Marktrolle::Msb])
416    }
417
418    /// NB + BKV (grid operator that also manages its own balance group).
419    #[must_use]
420    pub fn nb_bkv() -> Self {
421        Self::from_roles([Marktrolle::Nb, Marktrolle::Bkv])
422    }
423
424    /// Add a role to an existing set, returning a new `DeploymentRoles`.
425    #[must_use]
426    pub fn with(mut self, role: Marktrolle) -> Self {
427        if !self.all {
428            self.roles.insert(role);
429        }
430        self
431    }
432}
433
434impl FromIterator<Marktrolle> for DeploymentRoles {
435    fn from_iter<T: IntoIterator<Item = Marktrolle>>(iter: T) -> Self {
436        Self::from_roles(iter)
437    }
438}
439
440// ── Command licensing ─────────────────────────────────────────────────────────
441
442/// Why [`resolve_role`] rejected a command submission.
443#[derive(Debug, Clone, Copy, PartialEq, Eq)]
444pub enum LicensingError {
445    /// The command permits several roles and the caller asserted none —
446    /// the engine cannot infer which hat the caller is wearing.
447    MarktrolleRequired,
448    /// The asserted role is not in the command's permitted set.
449    RoleNotPermitted,
450    /// The effective role is not among the deployment's configured roles.
451    RoleNotConfigured,
452}
453
454impl std::fmt::Display for LicensingError {
455    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
456        match self {
457            Self::MarktrolleRequired => {
458                f.write_str("multi-role command requires an asserted Marktrolle")
459            }
460            Self::RoleNotPermitted => {
461                f.write_str("asserted Marktrolle is not permitted for this command")
462            }
463            Self::RoleNotConfigured => {
464                f.write_str("deployment is not configured for the required Marktrolle")
465            }
466        }
467    }
468}
469
470impl std::error::Error for LicensingError {}
471
472/// Resolve and validate the effective [`Marktrolle`] for a command submission.
473///
474/// Pure licensing policy — no registry lookup, no I/O:
475///
476/// - **Single-role commands** (`permitted.len() == 1`): the role is inferred
477///   from the permitted set; any `asserted` role is deliberately **ignored**
478///   so ERP connectors that always send a fixed role are not rejected.
479/// - **Multi-role commands** (`permitted.len() != 1`): `asserted` must be
480///   `Some` ([`LicensingError::MarktrolleRequired`]) and must be a member of
481///   `permitted` ([`LicensingError::RoleNotPermitted`]).
482///
483/// The effective role is then cross-checked against the deployment
484/// configuration: [`DeploymentRoles::all`] admits every role; an explicit
485/// (possibly empty) role set admits only its members
486/// ([`LicensingError::RoleNotConfigured`]).
487///
488/// # Errors
489///
490/// See [`LicensingError`] for the three rejection reasons.
491pub fn resolve_role(
492    permitted: &[Marktrolle],
493    asserted: Option<Marktrolle>,
494    configured: &DeploymentRoles,
495) -> Result<Marktrolle, LicensingError> {
496    let effective = if permitted.len() == 1 {
497        // Single-role command — fully implied; asserted role is ignored.
498        permitted[0]
499    } else {
500        let r = asserted.ok_or(LicensingError::MarktrolleRequired)?;
501        if !permitted.contains(&r) {
502            return Err(LicensingError::RoleNotPermitted);
503        }
504        r
505    };
506
507    if !configured.contains(effective) {
508        return Err(LicensingError::RoleNotConfigured);
509    }
510
511    Ok(effective)
512}
513
514#[cfg(test)]
515mod licensing_tests {
516    use super::*;
517
518    #[test]
519    fn code_round_trip_for_every_role() {
520        for role in [
521            Marktrolle::Nb,
522            Marktrolle::Lf,
523            Marktrolle::Msb,
524            Marktrolle::Nmsb,
525            Marktrolle::Amsb,
526            Marktrolle::Bkv,
527            Marktrolle::Uenb,
528            Marktrolle::Biko,
529            Marktrolle::Esa,
530            Marktrolle::Gnb,
531            Marktrolle::Lfg,
532            Marktrolle::Lfn,
533            Marktrolle::Lfa,
534            Marktrolle::Mgv,
535        ] {
536            assert_eq!(Marktrolle::from_code(role.as_code()), Some(role));
537        }
538        assert_eq!(Marktrolle::from_code("ÜNB"), Some(Marktrolle::Uenb));
539        assert_eq!(
540            Marktrolle::from_code("nb"),
541            None,
542            "codes are case-sensitive"
543        );
544        assert_eq!(Marktrolle::from_code(""), None);
545    }
546
547    #[test]
548    fn serde_round_trips_as_bdew_code() {
549        for role in [Marktrolle::Nb, Marktrolle::Uenb, Marktrolle::Lfg] {
550            let json = serde_json::to_string(&role).unwrap();
551            assert_eq!(json, format!("\"{}\"", role.as_code()));
552            let back: Marktrolle = serde_json::from_str(&json).unwrap();
553            assert_eq!(back, role);
554        }
555        assert!(serde_json::from_str::<Marktrolle>("\"LfStrom\"").is_err());
556    }
557
558    #[test]
559    fn from_partin_pid_covers_all_partin_pids() {
560        for pid in [
561            37000u32, 37001, 37002, 37003, 37004, 37005, 37006, 37008, 37009, 37010, 37011, 37012,
562            37013, 37014,
563        ] {
564            assert!(
565                Marktrolle::from_partin_pid(pid).is_some(),
566                "from_partin_pid({pid}) should return Some"
567            );
568        }
569        assert_eq!(Marktrolle::from_partin_pid(37000), Some(Marktrolle::Lf));
570        assert_eq!(Marktrolle::from_partin_pid(37008), Some(Marktrolle::Lfg));
571        assert_eq!(Marktrolle::from_partin_pid(37009), Some(Marktrolle::Gnb));
572        assert_eq!(Marktrolle::from_partin_pid(37011), Some(Marktrolle::Mgv));
573        assert_eq!(Marktrolle::from_partin_pid(37014), Some(Marktrolle::Msb));
574        // PID 37007 is not in the AHB (gap)
575        assert_eq!(Marktrolle::from_partin_pid(37007), None);
576        assert_eq!(Marktrolle::from_partin_pid(0), None);
577    }
578
579    #[test]
580    fn single_permitted_infers_and_ignores_assertion() {
581        let configured = DeploymentRoles::lf();
582        // No assertion → inferred.
583        assert_eq!(
584            resolve_role(&[Marktrolle::Lf], None, &configured),
585            Ok(Marktrolle::Lf)
586        );
587        // A wrong assertion is ignored, not rejected.
588        assert_eq!(
589            resolve_role(&[Marktrolle::Lf], Some(Marktrolle::Nb), &configured),
590            Ok(Marktrolle::Lf)
591        );
592    }
593
594    #[test]
595    fn multi_permitted_requires_assertion() {
596        let permitted = [Marktrolle::Nb, Marktrolle::Msb];
597        let configured = DeploymentRoles::nb_msb();
598        assert_eq!(
599            resolve_role(&permitted, None, &configured),
600            Err(LicensingError::MarktrolleRequired)
601        );
602        assert_eq!(
603            resolve_role(&permitted, Some(Marktrolle::Msb), &configured),
604            Ok(Marktrolle::Msb)
605        );
606    }
607
608    #[test]
609    fn multi_permitted_rejects_foreign_assertion() {
610        let permitted = [Marktrolle::Nb, Marktrolle::Msb];
611        let configured = DeploymentRoles::lf();
612        assert_eq!(
613            resolve_role(&permitted, Some(Marktrolle::Lf), &configured),
614            Err(LicensingError::RoleNotPermitted)
615        );
616    }
617
618    #[test]
619    fn configured_cross_check_rejects_unconfigured_role() {
620        // Resolves to LF; only NB is configured.
621        assert_eq!(
622            resolve_role(&[Marktrolle::Lf], None, &DeploymentRoles::nb()),
623            Err(LicensingError::RoleNotConfigured)
624        );
625        // Empty explicit set admits nothing.
626        assert_eq!(
627            resolve_role(&[Marktrolle::Lf], None, &DeploymentRoles::from_roles([])),
628            Err(LicensingError::RoleNotConfigured)
629        );
630    }
631
632    #[test]
633    fn deployment_roles_all_admits_every_role() {
634        assert_eq!(
635            resolve_role(&[Marktrolle::Biko], None, &DeploymentRoles::all()),
636            Ok(Marktrolle::Biko)
637        );
638        assert_eq!(
639            resolve_role(
640                &[Marktrolle::Bkv, Marktrolle::Uenb],
641                Some(Marktrolle::Uenb),
642                &DeploymentRoles::all()
643            ),
644            Ok(Marktrolle::Uenb)
645        );
646    }
647}
648
649#[cfg(test)]
650mod esa_role_tests {
651    use super::*;
652
653    /// An ESA-only deployment activates exactly that role.
654    #[test]
655    fn esa_is_a_selectable_deployment_role() {
656        let roles = DeploymentRoles::esa();
657        assert!(roles.contains(Marktrolle::Esa));
658        assert!(!roles.contains(Marktrolle::Msb));
659        assert!(!roles.is_all());
660    }
661
662    /// An integrated deployment can be both: the MSB serves ESAs and the ESA
663    /// arm consumes values. The two register disjoint PID sets.
664    #[test]
665    fn msb_and_esa_can_be_held_together() {
666        let roles = DeploymentRoles::from_roles([Marktrolle::Msb, Marktrolle::Esa]);
667        assert!(roles.contains(Marktrolle::Msb));
668        assert!(roles.contains(Marktrolle::Esa));
669    }
670}