mako-gpke 0.20.0

GPKE process engine for German electricity market communication (Lieferbeginn, Lieferende, Netznutzungsabrechnung)
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
//! GPKE LF-side Anmeldung workflow — Lieferbeginn, Lieferende, Kündigung.
//!
//! When `makod` operates as a **Lieferant (LF)**, the ERP instructs the engine
//! to initiate a GPKE process outbound to the Netzbetreiber (NB) or the old
//! Lieferant (LFA for Kündigung). This module implements that LF-side
//! outbound-first workflow.
//!
//! ## Process flow
//!
//! ```text
//! ERP → POST /api/v1/commands          (gpke.lieferbeginn.anmelden, role LF)
//!//!   [InitiateAnmeldung]
//!       ↓ emits Initiated + UTILMD outbox entry
//! AS4 sender → UTILMD 55001 to NB
//!//! AS4 inbound ← UTILMD 55002/55003 from NB
//!//!   [HandleAntwort]
//!       ↓ emits AntwortReceived
//!       ↓ (on acceptance) emits Activated
//! ERP webhook ← ErpEvent::AperakAccepted / AperakRejected (via outbox)
//! ```
//!
//! ## Prüfidentifikatoren
//!
//! | Outbound (LF → NB)               | PID   | Inbound response (NB → LF) | PID   |
//! |----------------------------------|-------|-------------------------------|-------|
//! | Anmeldung verb. MaLo             | 55001 | Bestätigung Anmeldung         | 55002 |
//! |                                  |       | Ablehnung Anmeldung           | 55003 |
//! | Abmeldung                        | 55004 | Bestätigung Abmeldung         | 55005 |
//! |                                  |       | Ablehnung Abmeldung           | 55006 |
//! | Kündigung Lieferbeginn           | 55016 | Bestätigung Kündigung        | 55017 |
//! |                                  |       | Ablehnung Kündigung          | 55018 |
//! | Anmeldung Lieferbeginn erz. MaLo | 55077 | Bestätigung erz. MaLo         | 55078 |
//! |                                  |       | Ablehnung erz. MaLo           | 55080 |
//!
//! ## Regulatory basis
//!
//! - **BDEW GPKE** — Geschäftsprozesse zur Kundenbelieferung mit Elektrizität
//! - **BK6-24-174** — the Festlegung that states the NB's answer window: a
//!   wall-clock instant on the 1. Werktag nach dem ÜT, per Prüfidentifikator
//!   (GPKE Teil 2). BK6-22-024 still carries GPKE **Teil 4**, but none of the
//!   Teil-2 Zuordnungsprozesse, and no 24-hour window anywhere.
//! - **UTILMD S2.1/S2.2** — EDI@Energy message format

use mako_engine::types::Pruefidentifikator;
use mako_engine::{
    error::WorkflowError,
    ids::DeadlineId,
    outbox::PendingOutbox,
    types::{MaLo, MarktpartnerCode, MessageRef},
    workflow::{CommandPayload, EventPayload, Workflow, WorkflowOutput},
};

// ── PID set ───────────────────────────────────────────────────────────────────

/// Workflow name for the GPKE LF-side Anmeldung workflow.
///
/// Used as the `workflow_name` in [`WorkflowId`] when spawning a new process
/// and as the registration key in the PID router (see [`GpkeModule`]).
///
/// [`WorkflowId`]: mako_engine::version::WorkflowId
/// [`GpkeModule`]: crate::GpkeModule
pub const WORKFLOW_NAME: &str = "gpke-lf-anmeldung";

/// Outbound request PIDs that trigger a new `GpkeLfAnmeldungWorkflow` process
/// when the ERP calls `POST /api/v1/commands`.
///
/// These are LF→NB/LFA direction only; the corresponding NB→LF response PIDs
/// ([`ANTWORT_PIDS_LF`]) complete the conversation.
pub const ANFRAGE_PIDS_LF: &[u32] = &[
    55001, // Anmeldung verb. MaLo (LF → NB)
    55004, // Abmeldung            (LF → NB)
    55016, // Kündigung Lieferbeginn (LFN → LFA)
    55077, // Anmeldung Lieferbeginn erz. MaLo (LFN → NB, BK6-24-174)
];

/// The Anfrage-PIDs whose `SG8 SEQ+Z79` Produktpaket is **Muss**.
///
/// UTILMD AHB Strom 2.2 Kap. 5.3 lists the six Anwendungsfälle that carry one;
/// the two this workflow sends are the Anmeldungen. An Abmeldung (55004) and a
/// Kündigung (55016) register nothing and carry none.
///
/// The Codeliste der Konfigurationen 1.4 Kap. 6.1.1 makes the Bilanzkreis
/// product (`9991000002082`) unconditional inside the package.
pub const ANMELDUNG_PIDS_MIT_BILANZKREIS: &[u32] = &[
    55001, // Anmeldung verb. MaLo
    55077, // Anmeldung erz. MaLo
];

/// The Anfrage-PIDs whose `SG4 STS+7` Ergänzung is a **Geschäftsvorfall**.
///
/// The erzeugende Anmeldung admits `ZW0`/`ZW1`/`ZW2` and nothing else, where
/// the verbrauchende one admits `ZW4`/`ZAP`. There is no default among the
/// three: a 100 %-Zuordnung, a handover of an existing Tranche and the building
/// of a new one are different acts, and only the third carries a Tranchengröße.
pub const ANMELDUNG_PIDS_MIT_GESCHAEFTSVORFALL: &[u32] = &[
    55077, // Anmeldung erz. MaLo
];

/// `ZW0` — Geschäftsvorfall 1, „vollständige (100%ige) Zuordnung".
pub const GESCHAEFTSVORFALL_1: &str = "ZW0";
/// `ZW1` — Geschäftsvorfall 2, Zuordnung zu einer **bestehenden** Tranche.
pub const GESCHAEFTSVORFALL_2: &str = "ZW1";
/// `ZW2` — Geschäftsvorfall 3, Zuordnung zu einer **neu zu bildenden** Tranche.
///
/// The one that makes the Tranchengröße (`9991000002090`) mandatory, per
/// Codeliste der Konfigurationen 1.4 Kap. 6.1.1.
pub const GESCHAEFTSVORFALL_3: &str = "ZW2";

/// The three Geschäftsvorfälle an erzeugende Anmeldung may state.
pub const GESCHAEFTSVORFAELLE: &[&str] = &[
    GESCHAEFTSVORFALL_1,
    GESCHAEFTSVORFALL_2,
    GESCHAEFTSVORFALL_3,
];

/// Inbound response PIDs (NB → LF or LFA → LF) routed back to this workflow.
///
/// These must be registered in the PID router so the AS4 inbound layer can
/// route them by conversation ID to the correct `GpkeLfAnmeldungWorkflow`
/// instance.
pub const ANTWORT_PIDS_LF: &[u32] = &[
    55002, // Bestätigung Anmeldung verb. MaLo (NB → LF)
    55003, // Ablehnung Anmeldung verb. MaLo   (NB → LF)
    55005, // Bestätigung Abmeldung            (NB → LF)
    55006, // Ablehnung Abmeldung              (NB → LF)
    55017, // Bestätigung Kündigung                (LFA → LFN)
    55018, // Ablehnung Kündigung                  (LFA → LFN)
    55078, // Bestätigung Anmeldung erz. MaLo       (NB → LFN)
    55080, // Ablehnung Anmeldung erz. MaLo         (NB → LFN); 55079 unassigned
];

/// Deadline label for the NB/LFA response window.
///
/// Sized by `mako_fristen::antwort` — a clock time on the 1. Werktag
/// after the ÜT, per PID. Never a flat 24 hours: that approximation expires a
/// Friday arrival on Saturday and calls a Tuesday-evening one healthy nine
/// hours after its Frist lapsed.
///
/// After sending the outbound ANFRAGE, the LF registers a deadline with this
/// label. If no ANTWORT arrives before the window this Prüfidentifikator
/// publishes, the scheduler fires `on_deadline` → `TimeoutExpired` to
/// transition the process to `Rejected`.
///
/// ```rust,ignore
/// let due = mako_fristen::antwort::antwort_deadline(pid, sent_at)
///     .expect("a PID with a published Antwortfrist");
/// let deadline = Deadline::new(process.stream_id().clone(), ..., NB_RESPONSE_WINDOW_LABEL, due);
/// deadline_store.register(&deadline).await?;
/// ```
pub const NB_RESPONSE_WINDOW_LABEL: &str = "nb-response-window";

// ── Domain events ─────────────────────────────────────────────────────────────

/// Events emitted by the GPKE LF-side Anmeldung workflow.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "data")]
pub enum LfAnmeldungEvent {
    /// LF-side Anmeldung initiated — outbound UTILMD queued for AS4 delivery.
    Initiated {
        /// PID of the outbound Anfrage (55001, 55004, 55016, or 55077).
        pruefidentifikator: Pruefidentifikator,
        /// MaLo / supply point identifier.
        location_id: MaLo,
        /// Our own market-partner ID (the Lieferant).
        sender: MarktpartnerCode,
        /// Counterparty market-partner ID (NB or LFA).
        receiver: MarktpartnerCode,
        /// Requested supply start / end / cancellation date.
        process_date: String,
    },
    /// Counterparty (NB or LFA) responded — accepted or rejected.
    AntwortReceived {
        /// PID of the inbound response (55002/55003, 55005/55006, 55017, 55018, 55078, 55080).
        response_pid: Pruefidentifikator,
        /// `true` if the request was accepted.
        accepted: bool,
        /// Rejection reason (only set when `accepted = false`).
        reason: Option<String>,
        /// Message reference from the inbound response UTILMD.
        response_ref: MessageRef,
    },
    /// Accepted Lieferbeginn Anmeldung activated (supply now live).
    Activated,
    /// A registered deadline expired before the NB responded.
    DeadlineExpired {
        /// Unique ID of the expired deadline.
        deadline_id: DeadlineId,
        /// Label identifying the deadline type.
        label: Box<str>,
    },
}

impl EventPayload for LfAnmeldungEvent {
    fn event_type(&self) -> &'static str {
        match self {
            Self::Initiated { .. } => "LfAnmeldungInitiated",
            Self::AntwortReceived { .. } => "LfAnmeldungAntwortReceived",
            Self::Activated => "LfAnmeldungActivated",
            Self::DeadlineExpired { .. } => "LfAnmeldungDeadlineExpired",
        }
    }
}

// ── Domain state ──────────────────────────────────────────────────────────────

/// Business data captured at `Initiated` time.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LfAnmeldungData {
    /// PID of the outbound Anfrage (55001, 55004, 55016, or 55077).
    pub pruefidentifikator: Pruefidentifikator,
    /// MaLo / supply point identifier.
    pub location_id: MaLo,
    /// Our own market-partner ID (the Lieferant).
    pub sender: MarktpartnerCode,
    /// Counterparty market-partner ID (NB or LFA).
    pub receiver: MarktpartnerCode,
    /// Requested supply start / end / cancellation date.
    pub process_date: String,
}

/// Process state for the GPKE LF-side Anmeldung workflow.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
pub enum LfAnmeldungState {
    /// Initial state before `InitiateAnmeldung` is received.
    #[default]
    New,
    /// UTILMD Anfrage sent; awaiting NB/LFA response.
    Pending(LfAnmeldungData),
    /// NB or LFA accepted the Anmeldung; supply active (Lieferbeginn only).
    Active(LfAnmeldungData),
    /// NB rejected or deadline expired.
    Rejected {
        /// Human-readable rejection reason.
        reason: String,
    },
}

impl mako_engine::workflow::OccupiesBusinessKey for LfAnmeldungState {
    fn occupies_business_key(&self) -> bool {
        match self {
            // Awaiting the NB's answer, or supply is running — a second
            // Anmeldung for the same MaLo would put two live processes on one
            // supply point.
            Self::Pending(_) | Self::Active(_) => true,
            // `New` never started. `Rejected` is terminal: the NB refused, and
            // the LF's corrected Anmeldung is a normal GPKE flow that must be
            // allowed rather than answered with `duplicate_process`.
            Self::New | Self::Rejected { .. } => false,
        }
    }
}

impl LfAnmeldungState {
    fn label(&self) -> &'static str {
        match self {
            Self::New => "New",
            Self::Pending(_) => "Pending",
            Self::Active(_) => "Active",
            Self::Rejected { .. } => "Rejected",
        }
    }
}

// ── Domain commands ───────────────────────────────────────────────────────────

/// Commands for the GPKE LF-side Anmeldung workflow.
#[derive(Clone)]
pub enum LfAnmeldungCommand {
    /// ERP instructs the engine to initiate a Lieferbeginn, Lieferende, or
    /// Kündigung Anmeldung as the Lieferant.
    ///
    /// The engine:
    /// 1. Records the `Initiated` event.
    /// 2. Enqueues a `PendingOutbox` entry with `message_type = "UTILMD"` and
    ///    the structured domain payload. The AS4 sender serialises this to
    ///    wire-format EDIFACT and delivers it to the NB via AS4.
    InitiateAnmeldung {
        /// Outbound request PID (55001, 55004, 55016, or 55077).
        pid: Pruefidentifikator,
        /// Our own market-partner ID (the Lieferant, from `--tenant-id`).
        sender: MarktpartnerCode,
        /// Counterparty market-partner ID (NB or LFA), resolved from the MaLo cache.
        receiver: MarktpartnerCode,
        /// Supply point identifier.
        location_id: MaLo,
        /// Requested process date (Lieferbeginn-/Lieferende-/Kündigungs-Datum).
        process_date: String,
        /// SG4 STS Transaktionsgrund (DE9013) — `E01` Ein-/Auszug,
        /// `E03` Wechsel. Rendered as the outbound STS segment.
        transaktionsgrund: Option<String>,
        /// `SG8 SEQ+Z79` Produktpaket — the Bilanzkreis the LF registers the
        /// Marktlokation into.
        ///
        /// **Muss on 55001 and 55077** (UTILMD AHB Strom 2.2 Kap. 5.3): „ohne
        /// die Angabe eines für den LF gültigen Bilanzkreises `[kann]` der NB den
        /// LF der Marktlokation bzw. Tranche nicht zuordnen". `None` on 55004
        /// and 55016, which register nothing.
        bilanzkreis: Option<String>,
        /// `SG4 STS+7` DE 9013 element 3 — the Transaktionsgrundergänzung.
        ///
        /// **Muss on 55077**, where the column admits only the three
        /// Geschäftsvorfälle and no default among them is safe. On 55001 the
        /// renderer supplies `ZW4` „verbrauchende Marktlokation", which is the
        /// code that column lists.
        transaktionsgrund_ergaenzung: Option<String>,
        /// `SG8 SEQ+Z79` Produkt `9991000002090` — the **Tranchengröße**.
        ///
        /// Muss in Geschäftsvorfall 3 („`STS+7++xxx+ZW2`") per Codeliste der
        /// Konfigurationen 1.4 Kap. 6.1.1, and meaningless outside it. Carried
        /// verbatim to the renderer, which knows the three Produkteigenschaften
        /// and the Bedingungen on each.
        tranchengroesse: Option<serde_json::Value>,
    },
    /// Inbound NB/LFA response (55002/55003, 55005/55006, 55017, 55018, 55078, 55080) received via AS4.
    ///
    /// Dispatched by the AS4 inbound layer after extracting the domain fields
    /// from the UTILMD response message.
    HandleAntwort {
        /// PID of the inbound response.
        response_pid: Pruefidentifikator,
        /// `true` if the NB accepted; `false` if rejected.
        accepted: bool,
        /// Optional rejection reason from the UTILMD text segment.
        reason: Option<String>,
        /// Message reference from the inbound response.
        response_ref: MessageRef,
    },
    /// Mark the accepted Lieferbeginn supply relationship as active.
    ///
    /// Typically dispatched after the ERP confirms supply activation downstream.
    Activate,
    /// A registered deadline fired — the NB let the published answer window
    /// lapse without a Bestätigung or Ablehnung.
    TimeoutExpired {
        /// Unique ID of the expired deadline.
        deadline_id: DeadlineId,
        /// Label identifying the deadline type.
        label: Box<str>,
    },
}

impl CommandPayload for LfAnmeldungCommand {}

// ── Workflow ──────────────────────────────────────────────────────────────────

/// GPKE LF-side outbound Anmeldung workflow.
///
/// Handles the Lieferant's perspective of initiating a supplier-change process:
/// sends the UTILMD Anfrage to the NB and tracks the NB's response.
///
/// Spawn via [`mako_engine::process::Process`]:
/// ```rust,ignore
/// let process = ctx.spawn::<GpkeLfAnmeldungWorkflow>(
///     tenant_id,
///     WorkflowId::new("gpke-lf-anmeldung", "FV2025-10-01"),
/// );
/// ```
pub struct GpkeLfAnmeldungWorkflow;

impl Workflow for GpkeLfAnmeldungWorkflow {
    type State = LfAnmeldungState;
    type Event = LfAnmeldungEvent;
    type Command = LfAnmeldungCommand;

    /// Deadline compensation for the NB/LFA answer window.
    ///
    /// | Label | State guard | Command emitted | Fundstelle |
    /// |---|---|---|---|
    /// | [`NB_RESPONSE_WINDOW_LABEL`] | `Pending` | `TimeoutExpired` | BK6-24-174 GPKE Teil 2 — the per-PID Antwortfrist |
    ///
    /// The label must be exactly this constant. `makod` registered
    /// `nb-response-window-24h` here, which fell through to `_ => None`: the
    /// deadline fired, nothing happened, and the process sat in `Pending`
    /// forever. `services/makod/tests/deadline_labels.rs` pins the two ends
    /// together.
    fn on_deadline(
        deadline: &mako_engine::deadline::Deadline,
        state: &Self::State,
    ) -> Option<Self::Command> {
        match (deadline.label(), state) {
            (NB_RESPONSE_WINDOW_LABEL, LfAnmeldungState::Pending(_)) => {
                Some(LfAnmeldungCommand::TimeoutExpired {
                    deadline_id: deadline.deadline_id(),
                    label: deadline.label().into(),
                })
            }
            _ => None,
        }
    }

    fn apply(state: Self::State, event: &Self::Event) -> Self::State {
        match event {
            LfAnmeldungEvent::Initiated {
                pruefidentifikator,
                location_id,
                sender,
                receiver,
                process_date,
            } => LfAnmeldungState::Pending(LfAnmeldungData {
                pruefidentifikator: *pruefidentifikator,
                location_id: location_id.clone(),
                sender: sender.clone(),
                receiver: receiver.clone(),
                process_date: process_date.clone(),
            }),
            LfAnmeldungEvent::AntwortReceived {
                accepted, reason, ..
            } => {
                if *accepted {
                    match state {
                        LfAnmeldungState::Pending(data) => LfAnmeldungState::Active(data),
                        other => other,
                    }
                } else {
                    LfAnmeldungState::Rejected {
                        reason: reason.clone().unwrap_or_else(|| "Ablehnung".to_owned()),
                    }
                }
            }
            LfAnmeldungEvent::Activated => match state {
                LfAnmeldungState::Active(data) => LfAnmeldungState::Active(data),
                other => other,
            },
            LfAnmeldungEvent::DeadlineExpired { label, .. } => match state {
                LfAnmeldungState::Active(_) | LfAnmeldungState::Rejected { .. } => state,
                _ => LfAnmeldungState::Rejected {
                    reason: format!("deadline expired: {label}"),
                },
            },
        }
    }

    fn handle(
        state: &Self::State,
        command: Self::Command,
    ) -> Result<WorkflowOutput<Self::Event>, WorkflowError> {
        match command {
            LfAnmeldungCommand::InitiateAnmeldung {
                pid,
                sender,
                receiver,
                location_id,
                process_date,
                transaktionsgrund,
                bilanzkreis,
                transaktionsgrund_ergaenzung,
                tranchengroesse,
            } => {
                if !matches!(state, LfAnmeldungState::New) {
                    return Err(WorkflowError::invalid_state("New", state.label()));
                }
                if !ANFRAGE_PIDS_LF.contains(&pid.as_u32()) {
                    return Err(WorkflowError::rejected(format!(
                        "expected an LF Anfrage PID (55001, 55004, 55016, 55077), got {pid}",
                    )));
                }
                // An Anmeldung without a Bilanzkreis is not a message the NB
                // can act on. UTILMD AHB Strom 2.2 Kap. 5.3 makes `SG8 SEQ+Z79`
                // Muss on 55001 and 55077 and names the reason: „ohne die
                // Angabe eines für den LF gültigen Bilanzkreises [kann] der NB
                // den LF der Marktlokation bzw. Tranche nicht zuordnen."
                // Refusing here beats sending an AHB-invalid Anmeldung and
                // waiting a Werktag for the APERAK.
                if ANMELDUNG_PIDS_MIT_BILANZKREIS.contains(&pid.as_u32())
                    && bilanzkreis.as_deref().is_none_or(str::is_empty)
                {
                    return Err(WorkflowError::rejected(format!(
                        "Anmeldung {pid} ohne Bilanzkreis: die UTILMD AHB Strom 2.2 \
                         Kap. 5.3 macht das Produktpaket SG8 SEQ+Z79 mit dem Produkt-Code \
                         9991000002082 (Bilanzkreis) zur Muss-Angabe — ohne einen für den \
                         LF gültigen Bilanzkreis kann der NB die Zuordnung nicht vornehmen.",
                    )));
                }

                // The erzeugende Anmeldung states which Geschäftsvorfall it
                // is. Its column admits `ZW0`/`ZW1`/`ZW2` and nothing else, so
                // an unstated one cannot be defaulted: the renderer would fall
                // back to the verbrauchende `ZW4`, which 55077 forbids, and the
                // NB would refuse the message.
                if ANMELDUNG_PIDS_MIT_GESCHAEFTSVORFALL.contains(&pid.as_u32()) {
                    let erg = transaktionsgrund_ergaenzung.as_deref().unwrap_or("");
                    if !GESCHAEFTSVORFAELLE.contains(&erg) {
                        return Err(WorkflowError::rejected(format!(
                            "Anmeldung {pid} ohne Geschäftsvorfall: SG4 STS+7 DE 9013 \
                             lässt für die erzeugende Marktlokation nur {} zu — \
                             ZW0 (100%ige Zuordnung), ZW1 (bestehende Tranche) und \
                             ZW2 (neu zu bildende Tranche) sind verschiedene Vorgänge.",
                            GESCHAEFTSVORFAELLE.join("/"),
                        )));
                    }
                    // Codeliste der Konfigurationen 1.4 Kap. 6.1.1: „Im
                    // Geschäftsvorfall 3 … ist zwingend dieses Produkt
                    // anzugeben." No AHB Bedingung says so, so nothing
                    // downstream would catch its absence.
                    if erg == GESCHAEFTSVORFALL_3 && tranchengroesse.is_none() {
                        return Err(WorkflowError::rejected(format!(
                            "Anmeldung {pid} im Geschäftsvorfall 3 ohne Tranchengröße: \
                             die Codeliste der Konfigurationen 1.4 Kap. 6.1.1 macht den \
                             Produkt-Code 9991000002090 bei STS+7++xxx+ZW2 zur \
                             Muss-Angabe, weil die neu zu bildende Tranche sonst keine \
                             Größe hat.",
                        )));
                    }
                }

                let event = LfAnmeldungEvent::Initiated {
                    pruefidentifikator: pid,
                    location_id: location_id.clone(),
                    sender: sender.clone(),
                    receiver: receiver.clone(),
                    process_date: process_date.clone(),
                };

                // Enqueue the outbound UTILMD as a PendingOutbox entry.
                //
                // The AS4 sender in `makod` picks up entries with
                // `message_type = "UTILMD"` and serialises the payload
                // to wire-format EDIFACT before handing it to the AS4
                // transport layer.
                // `document_date` and `message_ref` are intentionally omitted:
                // the renderer derives them at dispatch time (today / causation_event_id).
                let outbox = PendingOutbox::new(
                    "UTILMD",
                    receiver.as_str(),
                    serde_json::json!({
                        "direction":         "outbound",
                        "pid":               pid.as_u32(),
                        "sender":            sender.as_str(),
                        "receiver":          receiver.as_str(),
                        "malo":              location_id.as_str(),
                        "process_date":      process_date,
                        // SG4 STS Transaktionsgrund (E01 Ein-/Auszug, E03
                        // Wechsel) — rendered as the outbound STS segment.
                        "transaktionsgrund": transaktionsgrund,
                        // `SG8 SEQ+Z79` / `SG10 CAV+ZV4` — the Bilanzkreis.
                        "bilanzkreis":       bilanzkreis,
                        // `SG4 STS+7` DE 9013 element 3 — the Geschäftsvorfall
                        // on the erzeugende Anmeldung, `ZW4` elsewhere.
                        "transaktionsgrund_ergaenzung": transaktionsgrund_ergaenzung,
                        // `SG8 SEQ+Z79` Produkt 9991000002090 — Muss on ZW2.
                        "tranchengroesse":   tranchengroesse,
                    }),
                );

                Ok(WorkflowOutput::with_outbox(vec![event], vec![outbox]))
            }

            LfAnmeldungCommand::HandleAntwort {
                response_pid,
                accepted,
                reason,
                response_ref,
            } => {
                if !matches!(state, LfAnmeldungState::Pending(_)) {
                    return Err(WorkflowError::invalid_state("Pending", state.label()));
                }
                if !ANTWORT_PIDS_LF.contains(&response_pid.as_u32()) {
                    return Err(WorkflowError::rejected(format!(
                        "expected an LF Antwort PID (55002/55003, 55005/55006, 55017, 55018, 55078, 55080), got {response_pid}",
                    )));
                }

                // Carry malo_id so marktd's event_ingest can derive
                // VersorgungsStatus without relying on the CE subject (a process
                // UUID). Mirrors the GeLi Gas LFN workflow — without this outbox
                // entry no `de.mako.process.completed` is ever emitted for a
                // Strom supplier change, so `lf_mp_id_next` stays announced and
                // never gets promoted to the active Lieferant.
                let malo_id_str = match state {
                    LfAnmeldungState::Pending(data) => data.location_id.as_str().to_owned(),
                    _ => String::new(),
                };
                let outbox = vec![PendingOutbox::new(
                    "ProcessCompleted",
                    "",
                    serde_json::json!({
                        "pid":      response_pid.as_u32(),
                        "malo_id":  malo_id_str,
                        "accepted": accepted,
                        "outcome":  if accepted { "accepted" } else { "rejected" },
                    }),
                )];

                Ok(WorkflowOutput::with_outbox(
                    vec![LfAnmeldungEvent::AntwortReceived {
                        response_pid,
                        accepted,
                        reason,
                        response_ref,
                    }],
                    outbox,
                ))
            }

            LfAnmeldungCommand::Activate => {
                if !matches!(state, LfAnmeldungState::Active(_)) {
                    return Err(WorkflowError::invalid_state("Active", state.label()));
                }
                // Already active — emit a no-op or idempotent event.
                // In practice Activate is sent after ERP confirms supply.
                Ok(vec![LfAnmeldungEvent::Activated].into())
            }

            LfAnmeldungCommand::TimeoutExpired { deadline_id, label } => {
                if matches!(
                    state,
                    LfAnmeldungState::Active(_) | LfAnmeldungState::Rejected { .. }
                ) {
                    return Ok(WorkflowOutput::events(vec![]));
                }
                Ok(vec![LfAnmeldungEvent::DeadlineExpired { deadline_id, label }].into())
            }
        }
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use mako_engine::{
        types::{MaLo, MarktpartnerCode, MessageRef, Pruefidentifikator},
        workflow::Workflow,
    };

    use super::*;

    fn make_initiate(pid: u32) -> LfAnmeldungCommand {
        LfAnmeldungCommand::InitiateAnmeldung {
            transaktionsgrund_ergaenzung: None,
            tranchengroesse: None,
            pid: Pruefidentifikator::new(pid).unwrap(),
            sender: MarktpartnerCode::new("4012345000009"),
            receiver: MarktpartnerCode::new("9900123456789"),
            location_id: MaLo::new("10001234558"),
            process_date: "2026-10-01".to_owned(),
            transaktionsgrund: None,
            bilanzkreis: Some("11XBK-LF-------9".to_owned()),
        }
    }

    /// An erzeugende Anmeldung with its Geschäftsvorfall, and — on
    /// Geschäftsvorfall 3 — the Tranchengröße the Codeliste demands.
    fn make_erzeugende(erg: &str, groesse: Option<serde_json::Value>) -> LfAnmeldungCommand {
        let LfAnmeldungCommand::InitiateAnmeldung {
            pid,
            sender,
            receiver,
            location_id,
            process_date,
            transaktionsgrund,
            bilanzkreis,
            ..
        } = make_initiate(55077)
        else {
            unreachable!("make_initiate builds an InitiateAnmeldung")
        };
        LfAnmeldungCommand::InitiateAnmeldung {
            pid,
            sender,
            receiver,
            location_id,
            process_date,
            transaktionsgrund,
            bilanzkreis,
            transaktionsgrund_ergaenzung: Some(erg.to_owned()),
            tranchengroesse: groesse,
        }
    }

    /// 55077's `SG4 STS+7` DE 9013 column admits `ZW0`/`ZW1`/`ZW2` and nothing
    /// else. Without one the renderer would fall back to the verbrauchende
    /// `ZW4`, which that column forbids — the NB refuses the message and the LF
    /// loses the Anmeldefrist.
    #[test]
    fn an_erzeugende_anmeldung_states_its_geschaeftsvorfall() {
        let err = GpkeLfAnmeldungWorkflow::handle(&LfAnmeldungState::New, make_initiate(55077))
            .expect_err("55077 without a Geschäftsvorfall must be refused");
        assert!(format!("{err}").contains("Geschäftsvorfall"), "{err}");

        for erg in GESCHAEFTSVORFAELLE {
            let groesse = (*erg == GESCHAEFTSVORFALL_3).then(|| serde_json::json!("33.33"));
            let out = GpkeLfAnmeldungWorkflow::handle(
                &LfAnmeldungState::New,
                make_erzeugende(erg, groesse),
            )
            .unwrap_or_else(|e| panic!("{erg} is a lawful Geschäftsvorfall: {e}"));
            assert_eq!(out.outbox[0].payload["transaktionsgrund_ergaenzung"], *erg);
        }
    }

    /// Codeliste der Konfigurationen 1.4 Kap. 6.1.1: „Im Geschäftsvorfall 3 …
    /// ist zwingend dieses Produkt anzugeben." No AHB Bedingung says so, so the
    /// message would validate clean and still be refused by the NB.
    #[test]
    fn geschaeftsvorfall_3_carries_a_tranchengroesse() {
        let err = GpkeLfAnmeldungWorkflow::handle(
            &LfAnmeldungState::New,
            make_erzeugende(GESCHAEFTSVORFALL_3, None),
        )
        .expect_err("ZW2 without a Tranchengröße must be refused");
        assert!(format!("{err}").contains("9991000002090"), "{err}");

        let out = GpkeLfAnmeldungWorkflow::handle(
            &LfAnmeldungState::New,
            make_erzeugende(GESCHAEFTSVORFALL_3, Some(serde_json::json!("33.33"))),
        )
        .expect("a stated Tranchengröße is accepted");
        assert_eq!(out.outbox[0].payload["tranchengroesse"], "33.33");

        // The other two Geschäftsvorfälle build no Tranche and carry none.
        for erg in [GESCHAEFTSVORFALL_1, GESCHAEFTSVORFALL_2] {
            let out =
                GpkeLfAnmeldungWorkflow::handle(&LfAnmeldungState::New, make_erzeugende(erg, None))
                    .expect("no Tranchengröße is owed");
            assert!(out.outbox[0].payload["tranchengroesse"].is_null());
        }
    }

    #[test]
    fn initiate_lieferbeginn_transitions_to_pending() {
        let state = LfAnmeldungState::New;
        let out = GpkeLfAnmeldungWorkflow::handle(&state, make_initiate(55001)).unwrap();
        assert_eq!(out.events.len(), 1);
        assert_eq!(out.outbox.len(), 1, "must enqueue UTILMD outbox entry");

        let new_state = GpkeLfAnmeldungWorkflow::apply(state, &out.events[0]);
        assert!(matches!(new_state, LfAnmeldungState::Pending(_)));
    }

    #[test]
    fn initiate_abmeldung_transitions_to_pending() {
        let state = LfAnmeldungState::New;
        let out = GpkeLfAnmeldungWorkflow::handle(&state, make_initiate(55004)).unwrap();
        let new_state = GpkeLfAnmeldungWorkflow::apply(state, &out.events[0]);
        assert!(matches!(new_state, LfAnmeldungState::Pending(_)));
    }

    #[test]
    fn initiate_kuendigung_transitions_to_pending() {
        let state = LfAnmeldungState::New;
        let out = GpkeLfAnmeldungWorkflow::handle(&state, make_initiate(55016)).unwrap();
        let new_state = GpkeLfAnmeldungWorkflow::apply(state, &out.events[0]);
        assert!(matches!(new_state, LfAnmeldungState::Pending(_)));
    }

    #[test]
    fn nb_acceptance_transitions_to_active() {
        let initiated_event = LfAnmeldungEvent::Initiated {
            pruefidentifikator: Pruefidentifikator::new(55001).unwrap(),
            location_id: MaLo::new("10001234558"),
            sender: MarktpartnerCode::new("4012345000009"),
            receiver: MarktpartnerCode::new("9900123456789"),
            process_date: "2026-10-01".to_owned(),
        };
        let state = GpkeLfAnmeldungWorkflow::apply(LfAnmeldungState::New, &initiated_event);

        let cmd = LfAnmeldungCommand::HandleAntwort {
            response_pid: Pruefidentifikator::new(55002).unwrap(), // Bestätigung Anmeldung
            accepted: true,
            reason: None,
            response_ref: MessageRef::new("NB-RESP-001"),
        };
        let out = GpkeLfAnmeldungWorkflow::handle(&state, cmd).unwrap();
        assert_eq!(out.events.len(), 1);
        let final_state = GpkeLfAnmeldungWorkflow::apply(state, &out.events[0]);
        assert!(matches!(final_state, LfAnmeldungState::Active(_)));
    }

    /// `HandleAntwort` must enqueue the `ProcessCompleted` outbox entry that
    /// drives marktd's `VersorgungsStatus` transition.
    ///
    /// Without it no `de.mako.process.completed` is emitted for a Strom
    /// supplier change, so `lf_mp_id_next` is announced and never promoted —
    /// the MaLo stays `Unbeliefert` forever. The Gas twin
    /// (`geli-gas-lf-anmeldung`) always emitted this; GPKE did not.
    ///
    /// marktd keys on the PID: 55002 confirms, 55003 clears the announcement.
    #[test]
    fn handle_antwort_emits_process_completed_for_marktd() {
        let initiated_event = LfAnmeldungEvent::Initiated {
            pruefidentifikator: Pruefidentifikator::new(55001).unwrap(),
            location_id: MaLo::new("10001234558"),
            sender: MarktpartnerCode::new("4012345000009"),
            receiver: MarktpartnerCode::new("9900123456789"),
            process_date: "2026-10-01".to_owned(),
        };
        let state = GpkeLfAnmeldungWorkflow::apply(LfAnmeldungState::New, &initiated_event);

        for (response_pid, accepted, outcome) in
            [(55002u32, true, "accepted"), (55003, false, "rejected")]
        {
            let out = GpkeLfAnmeldungWorkflow::handle(
                &state,
                LfAnmeldungCommand::HandleAntwort {
                    response_pid: Pruefidentifikator::new(response_pid).unwrap(),
                    accepted,
                    reason: None,
                    response_ref: MessageRef::new("NB-RESP-001"),
                },
            )
            .unwrap();

            assert_eq!(out.outbox.len(), 1, "{response_pid}: one outbox entry");
            let entry = &out.outbox[0];
            assert_eq!(entry.message_type.as_ref(), "ProcessCompleted");
            assert_eq!(
                entry.payload["pid"].as_u64().unwrap(),
                u64::from(response_pid)
            );
            assert_eq!(
                entry.payload["malo_id"].as_str().unwrap(),
                "10001234558",
                "{response_pid}: marktd resolves the MaLo from the payload, not the CE subject",
            );
            assert_eq!(entry.payload["outcome"].as_str().unwrap(), outcome);
        }
    }

    #[test]
    fn nb_rejection_transitions_to_rejected() {
        let initiated_event = LfAnmeldungEvent::Initiated {
            pruefidentifikator: Pruefidentifikator::new(55001).unwrap(),
            location_id: MaLo::new("10001234558"),
            sender: MarktpartnerCode::new("4012345000009"),
            receiver: MarktpartnerCode::new("9900123456789"),
            process_date: "2026-10-01".to_owned(),
        };
        let state = GpkeLfAnmeldungWorkflow::apply(LfAnmeldungState::New, &initiated_event);

        let cmd = LfAnmeldungCommand::HandleAntwort {
            response_pid: Pruefidentifikator::new(55003).unwrap(), // Ablehnung Anmeldung
            accepted: false,
            reason: Some("MaLo nicht in Netzgebiet".to_owned()),
            response_ref: MessageRef::new("NB-RESP-002"),
        };
        let out = GpkeLfAnmeldungWorkflow::handle(&state, cmd).unwrap();
        let final_state = GpkeLfAnmeldungWorkflow::apply(state, &out.events[0]);
        assert!(matches!(final_state, LfAnmeldungState::Rejected { .. }));
    }

    #[test]
    fn invalid_pid_is_rejected() {
        let state = LfAnmeldungState::New;
        // 55003 is a response PID, not an Anfrage PID
        let err = GpkeLfAnmeldungWorkflow::handle(&state, make_initiate(55003));
        assert!(err.is_err());
    }

    #[test]
    fn timeout_on_pending_transitions_to_rejected() {
        use mako_engine::ids::DeadlineId;
        let initiated_event = LfAnmeldungEvent::Initiated {
            pruefidentifikator: Pruefidentifikator::new(55001).unwrap(),
            location_id: MaLo::new("10001234558"),
            sender: MarktpartnerCode::new("4012345000009"),
            receiver: MarktpartnerCode::new("9900123456789"),
            process_date: "2026-10-01".to_owned(),
        };
        let state = GpkeLfAnmeldungWorkflow::apply(LfAnmeldungState::New, &initiated_event);

        let cmd = LfAnmeldungCommand::TimeoutExpired {
            deadline_id: DeadlineId::new(),
            label: "nb-response-window".into(),
        };
        let out = GpkeLfAnmeldungWorkflow::handle(&state, cmd).unwrap();
        let final_state = GpkeLfAnmeldungWorkflow::apply(state, &out.events[0]);
        assert!(matches!(final_state, LfAnmeldungState::Rejected { .. }));
    }

    #[test]
    fn timeout_on_active_is_noop() {
        use mako_engine::ids::DeadlineId;
        let initiated_event = LfAnmeldungEvent::Initiated {
            pruefidentifikator: Pruefidentifikator::new(55001).unwrap(),
            location_id: MaLo::new("10001234558"),
            sender: MarktpartnerCode::new("4012345000009"),
            receiver: MarktpartnerCode::new("9900123456789"),
            process_date: "2026-10-01".to_owned(),
        };
        let state = GpkeLfAnmeldungWorkflow::apply(LfAnmeldungState::New, &initiated_event);
        let accepted_event = LfAnmeldungEvent::AntwortReceived {
            response_pid: Pruefidentifikator::new(55003).unwrap(),
            accepted: true,
            reason: None,
            response_ref: MessageRef::new("REF-002"),
        };
        let state = GpkeLfAnmeldungWorkflow::apply(state, &accepted_event);
        assert!(matches!(state, LfAnmeldungState::Active(_)));

        let cmd = LfAnmeldungCommand::TimeoutExpired {
            deadline_id: DeadlineId::new(),
            label: "nb-response-window".into(),
        };
        let out = GpkeLfAnmeldungWorkflow::handle(&state, cmd).unwrap();
        assert_eq!(out.events.len(), 0, "timeout is no-op on Active");
    }
}