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
//! GPKE NB-initiated Lieferende — Kündigung by the Netzbetreiber.
//!
//! Covers GPKE Teil 2 §2.5: the Netzbetreiber proactively terminates a supply
//! relationship (e.g., for non-payment under §41 EnWG or after judicial order).
//! This is distinct from the Abmeldung (PID 55004) where the **Lieferant** initiates.
//!
//! This module implements the **receiving-party perspective** (Lieferant / LFN):
//! the system receives an inbound Ankündigung from the NB and responds with
//! Bestätigung or Ablehnung.
//!
//! # Prüfidentifikatoren (UTILMD AHB Strom 2.1/2.2, FV2025-10-01)
//!
//! ## Inbound (NB → LF)
//!
//! | PID   | Process name (AHB)                                   | Direction |
//! |-------|------------------------------------------------------|-----------|
//! | 55007 | Ankündigung NB-seitiges Lieferende (NB → LFN)        | NB → LF   |
//!
//! ## Outbound (LF → NB)
//!
//! | PID   | Process name (AHB)                                   | Derived from |
//! |-------|------------------------------------------------------|--------------|
//! | 55008 | Bestätigung NB-seitiges Lieferende (LFN → NB)        | 55007 accepted |
//! | 55009 | Ablehnung NB-seitiges Lieferende (LFN → NB)          | 55007 rejected |
//!
//! # Note on LFW24 context
//!
//! PIDs 55007–55009 are **present in UTILMD AHB Strom 2.1 (FV2025-10-01)** and
//! in the BDEW Anwendungsübersicht 3.3 / 4.0. LFW24 (BK6-24-174) redesigned
//! only the LF-initiated Lieferbeginn/Abmeldung (55001/55004); the NB-initiated
//! Lieferende is a separate process under GPKE Teil 2 § 2.5, answered by the LF
//! at **05:00 Uhr des 1. Werktags nach dem ÜT**.
//!
//! # Regulatory basis
//!
//! - **BDEW GPKE Teil 2 §2.5** — NB-seitiges Lieferende
//! - **UTILMD S2.1/S2.2** — EDI@Energy message format
//! - **APERAK AHB 1.0 § 2.4.1** — technical acknowledgement, **45 Minuten** on a
//!   weekday for a UTILMD. A separate clock from the business answer window,
//!   which GPKE Teil 2 states as a wall-clock instant on the 1. Werktag nach
//!   dem ÜT.

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

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

/// Workflow name used for PID routing and `WorkflowId` construction.
pub const WORKFLOW_NAME: &str = "gpke-lf-abmeldung";

/// Inbound PIDs for NB-initiated Lieferende handled by [`GpkeLfAbmeldungWorkflow`].
///
/// | PID   | Process (AHB name)                          | AHB profile  |
/// |-------|---------------------------------------------|--------------|
/// | 55007 | Ankündigung NB-seitiges Lieferende (NB→LFN) | S2.1–S2.2 ✅ |
pub const LF_ABMELDUNG_PIDS: &[u32] = &[55007];

/// Deadline label for the **business** answer window — 05:00 Uhr des 1. WT nach
/// dem ÜT (GPKE Teil 2 § 2.5.2.2), resolved by `mako_fristen::antwort`.
///
/// Not the APERAK clock: that is 45 Minuten for a UTILMD (APERAK AHB 1.0
/// § 2.4.1) and rides `mako_fristen::APERAK_STROM_WINDOW_LABEL`.
pub const LF_ABMELDUNG_ANTWORT_WINDOW_LABEL: &str = "gpke-lf-abmeldung-antwortfrist";

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

/// Events emitted by the GPKE LF Abmeldung workflow.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "data")]
pub enum LfAbmeldungEvent {
    /// PID 55007 Ankündigung NB-seitiges Lieferende received.
    AnkuendigungErhalten {
        /// Marktlokation EIC code.
        location_id: MaLo,
        /// GLN of the sending NB.
        sender: MarktpartnerCode,
        /// GLN of the receiving LF.
        receiver: MarktpartnerCode,
        /// EDIFACT document date (`YYYYMMDD`).
        document_date: String,
        /// Announced supply end date (`YYYYMMDD`).
        process_date: String,
        /// EDIFACT message reference.
        message_ref: MessageRef,
        /// BDEW Prüfidentifikator (55007).
        pruefidentifikator: Pruefidentifikator,
        /// `SG4 IDE+24` DE 7402 — carried into the answer's `SG4 RFF+TN`.
        vorgangsnummer: Option<String>,
    },
    /// EDIFACT message passed profile validation.
    ValidationPassed {
        /// Reference of the validated message.
        message_ref: MessageRef,
    },
    /// Outbound response (55008 or 55009) dispatched to the NB.
    AntwortGesendet {
        /// Response PID actually dispatched.
        response_pid: Pruefidentifikator,
        /// `true` = Bestätigung, `false` = Ablehnung — read from the
        /// Antwortcode's published Cluster, never supplied separately.
        accepted: bool,
        /// The answer as sent, kept for the audit trail.
        antwort: crate::lf_antwort::LfAntwort,
    },
    /// Supply relationship ended per NB notice.
    Beendet,
    /// APERAK 29001 dispatched for technical failure.
    AperakFehlerDispatched {
        /// APERAK PID.
        aperak_pid: Pruefidentifikator,
        /// Error reason.
        reason: String,
        /// Outbound APERAK message reference.
        outbound_ref: MessageRef,
    },
    /// Process rejected due to validation failure or deadline expiry.
    Rejected {
        /// Human-readable reason.
        reason: String,
    },
    /// A registered deadline expired.
    DeadlineExpired {
        /// Unique deadline ID.
        deadline_id: DeadlineId,
        /// Deadline label.
        label: Box<str>,
    },
}

impl EventPayload for LfAbmeldungEvent {
    fn event_type(&self) -> &'static str {
        match self {
            Self::AnkuendigungErhalten { .. } => "LfAbmeldungAnkuendigungErhalten",
            Self::ValidationPassed { .. } => "LfAbmeldungValidationPassed",
            Self::AntwortGesendet { .. } => "LfAbmeldungAntwortGesendet",
            Self::Beendet => "LfAbmeldungBeendet",
            Self::AperakFehlerDispatched { .. } => "LfAbmeldungAperakFehlerDispatched",
            Self::Rejected { .. } => "LfAbmeldungRejected",
            Self::DeadlineExpired { .. } => "LfAbmeldungDeadlineExpired",
        }
    }
}

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

/// Business data captured at `AnkuendigungErhalten` time.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LfAbmeldungData {
    /// EIC/MaLo code.
    pub location_id: MaLo,
    /// GLN of the NB who initiated the termination.
    pub sender: MarktpartnerCode,
    /// GLN of the affected LF.
    pub receiver: MarktpartnerCode,
    /// EDIFACT document date (`YYYYMMDD`).
    pub document_date: String,
    /// Announced supply end date (`YYYYMMDD`).
    pub process_date: String,
    /// BDEW Prüfidentifikator (55007).
    pub pruefidentifikator: Pruefidentifikator,
    /// `SG4 IDE+24` DE 7402 of the **request**.
    ///
    /// Retained because the answer must carry it back in `SG4 RFF+TN`
    /// („Referenz Vorgangsnummer (aus Anfragenachricht)", Muss on every
    /// Antwortnachricht). It is never reused as the answer's own `IDE+24`.
    pub vorgangsnummer: Option<String>,
}

/// State of a GPKE LF Abmeldung process.
///
/// # Lifecycle
///
/// ```text
/// New → Eingegangen → ValidationPassed → AntwortGesendet → Beendet
///                                       ↘ Rejected
///     ↘ Rejected (failed validation)
/// ```
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "status", content = "data")]
#[derive(Default)]
pub enum LfAbmeldungState {
    /// No events yet.
    #[default]
    New,
    /// Ankündigung received.
    Eingegangen(LfAbmeldungData),
    /// Validation passed; response not yet sent.
    ValidationPassed(LfAbmeldungData),
    /// Response dispatched; awaiting supply-end confirmation.
    AntwortGesendet {
        /// Data from the Ankündigung.
        data: LfAbmeldungData,
        /// Response PID sent (55008 or 55009).
        response_pid: Pruefidentifikator,
    },
    /// Supply relationship ended.
    Beendet(LfAbmeldungData),
    /// Process rejected.
    Rejected {
        /// Human-readable reason.
        reason: String,
    },
}

impl LfAbmeldungState {
    /// Stable string label for the current variant.
    #[must_use]
    pub fn label(&self) -> &'static str {
        match self {
            Self::New => "New",
            Self::Eingegangen(_) => "Eingegangen",
            Self::ValidationPassed(_) => "ValidationPassed",
            Self::AntwortGesendet { .. } => "AntwortGesendet",
            Self::Beendet(_) => "Beendet",
            Self::Rejected { .. } => "Rejected",
        }
    }

    /// Return `Some(&LfAbmeldungData)` if the process has been initiated.
    #[must_use]
    pub fn data(&self) -> Option<&LfAbmeldungData> {
        match self {
            Self::Eingegangen(d) | Self::ValidationPassed(d) | Self::Beendet(d) => Some(d),
            Self::AntwortGesendet { data, .. } => Some(data),
            Self::New | Self::Rejected { .. } => None,
        }
    }
}

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

/// Commands for the GPKE LF Abmeldung workflow.
#[derive(Clone)]
pub enum LfAbmeldungCommand {
    /// Inbound UTILMD PID 55007 Ankündigung received from the AS4 layer.
    ReceiveAnkuendigung {
        /// BDEW Prüfidentifikator (55007).
        pid: Pruefidentifikator,
        /// GLN of the NB.
        sender: MarktpartnerCode,
        /// GLN of the LF.
        receiver: MarktpartnerCode,
        /// Marktlokation EIC code.
        location_id: MaLo,
        /// EDIFACT document date (`YYYYMMDD`).
        document_date: String,
        /// Announced supply end date (`YYYYMMDD`).
        process_date: String,
        /// EDIFACT message reference.
        message_ref: MessageRef,
        /// The `SG4` facts the trees branch on, forwarded to `processd` on
        /// the `de.mako.process.initiated` notification.
        vorgang: Box<crate::lf_antwort::LfVorgangsdaten>,
        /// `true` if validation returned no errors.
        validation_passed: bool,
        /// Validation error strings.
        validation_errors: Vec<String>,
    },
    /// Send the outbound UTILMD response (55008 = Bestätigung, 55009 = Ablehnung).
    ///
    /// The LF answers by **05:00 Uhr des 1. WT nach dem ÜT** — GPKE Teil 2
    /// § 2.5.2.2 SD Lieferende von NB an LF Prozessschritt 2, resolved by
    /// `mako_fristen::antwort` (trigger PID 55007).
    SendAntwort {
        /// The resolved answer: Antwortcode, its EBD, and the Cluster that
        /// selects the response PID.
        antwort: crate::lf_antwort::LfAntwort,
    },
    /// Record that the supply relationship has ended.
    BeendenBestaetigen,
    /// Dispatch APERAK 29001 for technical processing failure.
    DispatchAperakFehler {
        /// Error reason.
        reason: String,
        /// Outbound APERAK message reference.
        outbound_ref: MessageRef,
    },
    /// A registered deadline fired; close the process.
    TimeoutExpired {
        /// Unique deadline ID.
        deadline_id: DeadlineId,
        /// Deadline label.
        label: Box<str>,
    },
}

impl CommandPayload for LfAbmeldungCommand {}

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

/// GPKE NB-initiated Lieferende workflow (PID 55007 inbound, 55008/55009 outbound).
///
/// Spawn via [`mako_engine::process::Process`]:
/// ```rust,ignore
/// let process = ctx.spawn::<GpkeLfAbmeldungWorkflow>(
///     tenant_id,
///     WorkflowId::new("gpke-lf-abmeldung", "FV2025-10-01"),
/// );
/// ```
pub struct GpkeLfAbmeldungWorkflow;

impl Workflow for GpkeLfAbmeldungWorkflow {
    type State = LfAbmeldungState;
    type Event = LfAbmeldungEvent;
    type Command = LfAbmeldungCommand;

    fn on_deadline(deadline: &Deadline, state: &Self::State) -> Option<Self::Command> {
        match (deadline.label(), state) {
            (LF_ABMELDUNG_ANTWORT_WINDOW_LABEL, LfAbmeldungState::Eingegangen(_))
            | (LF_ABMELDUNG_ANTWORT_WINDOW_LABEL, LfAbmeldungState::ValidationPassed(_)) => {
                Some(LfAbmeldungCommand::TimeoutExpired {
                    deadline_id: deadline.deadline_id(),
                    label: deadline.label().into(),
                })
            }
            _ => None,
        }
    }

    fn apply(state: Self::State, event: &Self::Event) -> Self::State {
        match event {
            LfAbmeldungEvent::AnkuendigungErhalten {
                location_id,
                sender,
                receiver,
                document_date,
                process_date,
                pruefidentifikator,
                vorgangsnummer,
                ..
            } => LfAbmeldungState::Eingegangen(LfAbmeldungData {
                location_id: location_id.clone(),
                sender: sender.clone(),
                receiver: receiver.clone(),
                document_date: document_date.clone(),
                process_date: process_date.clone(),
                pruefidentifikator: *pruefidentifikator,
                vorgangsnummer: vorgangsnummer.clone(),
            }),
            LfAbmeldungEvent::ValidationPassed { .. } => match state {
                LfAbmeldungState::Eingegangen(data) => LfAbmeldungState::ValidationPassed(data),
                other => other,
            },
            LfAbmeldungEvent::AntwortGesendet {
                accepted,
                response_pid,
                ..
            } => {
                if *accepted {
                    match state {
                        LfAbmeldungState::ValidationPassed(data) => {
                            LfAbmeldungState::AntwortGesendet {
                                response_pid: *response_pid,
                                data,
                            }
                        }
                        other => other,
                    }
                } else {
                    LfAbmeldungState::Rejected {
                        reason: "Ankündigung abgelehnt".to_owned(),
                    }
                }
            }
            LfAbmeldungEvent::Beendet => match state {
                LfAbmeldungState::AntwortGesendet { data, .. } => LfAbmeldungState::Beendet(data),
                other => other,
            },
            LfAbmeldungEvent::AperakFehlerDispatched { reason, .. } => LfAbmeldungState::Rejected {
                reason: format!("APERAK 29001: {reason}"),
            },
            LfAbmeldungEvent::Rejected { reason } => LfAbmeldungState::Rejected {
                reason: reason.clone(),
            },
            LfAbmeldungEvent::DeadlineExpired { label, .. } => match state {
                LfAbmeldungState::Beendet(_) | LfAbmeldungState::Rejected { .. } => state,
                _ => LfAbmeldungState::Rejected {
                    reason: format!("deadline expired: {label}"),
                },
            },
        }
    }

    fn handle(
        state: &Self::State,
        command: Self::Command,
    ) -> Result<WorkflowOutput<Self::Event>, WorkflowError> {
        match command {
            LfAbmeldungCommand::ReceiveAnkuendigung {
                pid,
                sender,
                receiver,
                location_id,
                document_date,
                process_date,
                message_ref,
                vorgang,
                validation_passed,
                validation_errors,
            } => {
                if !matches!(state, LfAbmeldungState::New) {
                    return Err(WorkflowError::invalid_state("New", state.label()));
                }
                if !LF_ABMELDUNG_PIDS.contains(&pid.as_u32()) {
                    return Err(WorkflowError::rejected(format!(
                        "expected NB-initiated Lieferende PID (55007), got {pid}",
                    )));
                }
                // Clone before move for APERAK emission in the validation-failed path.
                let sender_mp_id = sender.clone();
                let receiver_gln = receiver.clone();
                let notify_malo = location_id.clone();
                let notify_termin = process_date.clone();

                let mut events = vec![LfAbmeldungEvent::AnkuendigungErhalten {
                    location_id,
                    sender,
                    receiver,
                    document_date,
                    process_date,
                    message_ref: message_ref.clone(),
                    pruefidentifikator: pid,
                    vorgangsnummer: vorgang.vorgangsnummer.clone(),
                }];
                if validation_passed {
                    events.push(LfAbmeldungEvent::ValidationPassed {
                        message_ref: message_ref.clone(),
                    });
                    // F-038: APERAK BGM+312 (Anerkennungsmeldung) — mandatory per APERAK AHB 1.0 §2.4.
                    // Strom UTILMD (weekday): 45 Min; Saturday: Sonntag 12 Uhr (APERAK AHB 1.0 §2.4.1).
                    let outbox = vec![
                        // The business notification. `processd`'s LF module
                        // decides this process, and it only ever sees a message
                        // that reaches the ERP fan-out — an APERAK is a
                        // technical acknowledgement, not one.
                        vorgang
                            .process_initiated(
                                pid,
                                &notify_malo,
                                &sender_mp_id,
                                &receiver_gln,
                                &notify_termin,
                                &serde_json::Value::Null,
                            )
                            .caused_by(1),
                        PendingOutbox::aperak_anerkennung(
                            receiver_gln.as_str(),
                            sender_mp_id.as_str(),
                            message_ref.as_str(),
                        )
                        .caused_by(1),
                    ];
                    Ok(WorkflowOutput::with_outbox(events, outbox))
                } else {
                    let reason = validation_errors.join("; ");
                    events.push(LfAbmeldungEvent::Rejected {
                        reason: reason.clone(),
                    });
                    // F-035: APERAK BGM+313 — mandatory per APERAK AHB 1.0 §2.1.1.
                    // Strom UTILMD (weekday): 45 Min; Saturday: Sonntag 12 Uhr (APERAK AHB 1.0 §2.4.1).
                    let outbox = vec![
                        PendingOutbox::aperak_fehler(
                            receiver_gln.as_str(),
                            sender_mp_id.as_str(),
                            message_ref.as_str(),
                            mako_engine::erc::codes::Z29,
                            reason,
                        )
                        .caused_by(0),
                    ];
                    Ok(WorkflowOutput::with_outbox(events, outbox))
                }
            }

            LfAbmeldungCommand::SendAntwort { antwort } => {
                let data = match state {
                    LfAbmeldungState::ValidationPassed(d) => d,
                    _ => {
                        return Err(WorkflowError::invalid_state(
                            "ValidationPassed",
                            state.label(),
                        ));
                    }
                };
                // The Cluster the Antwortcode sits in decides the PID. A caller
                // cannot pick one independently of the other — that is how an
                // Ablehnungscode could otherwise ride a Bestätigung.
                let accepted = antwort.zustimmung;
                let response_code: u32 = if accepted { 55008 } else { 55009 };
                let response_pid = Pruefidentifikator::new(response_code)
                    .map_err(|e| WorkflowError::rejected(e.clone()))?;

                // The outbox entry *is* the answer. Without it the event log
                // recorded the process as answered while the counterparty saw
                // nothing but its Frist expire.
                let outbox = vec![
                    crate::lf_antwort::antwort_outbox(
                        response_code,
                        &antwort,
                        &data.location_id,
                        &data.sender,
                        &data.receiver,
                        &data.process_date,
                        data.vorgangsnummer.as_deref(),
                    )
                    .caused_by(0),
                ];
                Ok(WorkflowOutput::with_outbox(
                    vec![LfAbmeldungEvent::AntwortGesendet {
                        response_pid,
                        accepted,
                        antwort,
                    }],
                    outbox,
                ))
            }

            LfAbmeldungCommand::BeendenBestaetigen => {
                if !matches!(state, LfAbmeldungState::AntwortGesendet { .. }) {
                    return Err(WorkflowError::invalid_state(
                        "AntwortGesendet",
                        state.label(),
                    ));
                }
                Ok(vec![LfAbmeldungEvent::Beendet].into())
            }

            LfAbmeldungCommand::DispatchAperakFehler {
                reason,
                outbound_ref,
            } => {
                match state {
                    LfAbmeldungState::Eingegangen(_) | LfAbmeldungState::ValidationPassed(_) => {}
                    _ => {
                        return Err(WorkflowError::invalid_state(
                            "Eingegangen or ValidationPassed",
                            state.label(),
                        ));
                    }
                }
                let aperak_pid = Pruefidentifikator::new(29_001)
                    .map_err(|e| WorkflowError::rejected(e.clone()))?;
                Ok(vec![LfAbmeldungEvent::AperakFehlerDispatched {
                    aperak_pid,
                    reason,
                    outbound_ref,
                }]
                .into())
            }

            LfAbmeldungCommand::TimeoutExpired { deadline_id, label } => match state {
                LfAbmeldungState::Beendet(_) | LfAbmeldungState::Rejected { .. } => {
                    Ok(vec![].into())
                }
                _ => Ok(vec![LfAbmeldungEvent::DeadlineExpired { deadline_id, label }].into()),
            },
        }
    }
}

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

#[cfg(test)]
mod tests {
    use mako_engine::{ids::DeadlineId, workflow::Workflow};

    use super::*;

    fn pid(code: u32) -> Pruefidentifikator {
        Pruefidentifikator::new(code).unwrap()
    }
    fn mcod(s: &str) -> MarktpartnerCode {
        MarktpartnerCode::new(s)
    }
    fn malo(s: &str) -> MaLo {
        MaLo::new(s)
    }
    fn mref(s: &str) -> MessageRef {
        MessageRef::new(s)
    }

    fn ankuendigung_cmd(ok: bool) -> LfAbmeldungCommand {
        LfAbmeldungCommand::ReceiveAnkuendigung {
            pid: pid(55007),
            sender: mcod("9900357000004"),
            receiver: mcod("4012345000023"),
            location_id: malo("51238696781"),
            document_date: "20251001".to_owned(),
            process_date: "20260101".to_owned(),
            message_ref: mref("ABMELD-001"),
            vorgang: Box::new(crate::LfVorgangsdaten::default()),
            validation_passed: ok,
            validation_errors: if ok {
                vec![]
            } else {
                vec!["missing mandatory segment".to_owned()]
            },
        }
    }

    fn apply_all(init: LfAbmeldungState, events: &[LfAbmeldungEvent]) -> LfAbmeldungState {
        events.iter().fold(init, GpkeLfAbmeldungWorkflow::apply)
    }

    #[test]
    fn lf_abmeldung_happy_path_bestaetigung() {
        let out = GpkeLfAbmeldungWorkflow::handle(&LfAbmeldungState::New, ankuendigung_cmd(true))
            .unwrap();
        assert_eq!(out.events.len(), 2); // AnkuendigungErhalten + ValidationPassed
        let state = apply_all(LfAbmeldungState::New, &out.events);
        assert!(matches!(state, LfAbmeldungState::ValidationPassed(_)));

        let out = GpkeLfAbmeldungWorkflow::handle(
            &state,
            LfAbmeldungCommand::SendAntwort {
                antwort: crate::lf_antwort::LfAntwort::zustimmung("A10", "E_0609"),
            },
        )
        .unwrap();
        if let LfAbmeldungEvent::AntwortGesendet {
            response_pid,
            accepted,
            ..
        } = &out.events[0]
        {
            assert!(accepted);
            assert_eq!(response_pid.as_u32(), 55008);
        } else {
            panic!("expected AntwortGesendet");
        }
        let state = apply_all(state, &out.events);
        assert!(matches!(state, LfAbmeldungState::AntwortGesendet { .. }));

        let out = GpkeLfAbmeldungWorkflow::handle(&state, LfAbmeldungCommand::BeendenBestaetigen)
            .unwrap();
        let state = apply_all(state, &out.events);
        assert!(matches!(state, LfAbmeldungState::Beendet(_)));
    }

    #[test]
    fn lf_abmeldung_ablehnung() {
        let out = GpkeLfAbmeldungWorkflow::handle(&LfAbmeldungState::New, ankuendigung_cmd(true))
            .unwrap();
        let state = apply_all(LfAbmeldungState::New, &out.events);
        let out = GpkeLfAbmeldungWorkflow::handle(
            &state,
            LfAbmeldungCommand::SendAntwort {
                antwort: crate::lf_antwort::LfAntwort::ablehnung("A99", "E_0609")
                    .with_bemerkung("Widerspruch"),
            },
        )
        .unwrap();
        if let LfAbmeldungEvent::AntwortGesendet {
            response_pid,
            accepted,
            ..
        } = &out.events[0]
        {
            assert!(!accepted);
            assert_eq!(response_pid.as_u32(), 55009);
        } else {
            panic!("expected AntwortGesendet");
        }
        let state = apply_all(state, &out.events);
        assert!(matches!(state, LfAbmeldungState::Rejected { .. }));
    }

    #[test]
    fn lf_abmeldung_wrong_pid_rejected() {
        let result = GpkeLfAbmeldungWorkflow::handle(
            &LfAbmeldungState::New,
            LfAbmeldungCommand::ReceiveAnkuendigung {
                pid: pid(55001),
                sender: mcod("9900357000004"),
                receiver: mcod("4012345000023"),
                location_id: malo("51238696781"),
                document_date: "20251001".to_owned(),
                process_date: "20260101".to_owned(),
                message_ref: mref("X"),
                vorgang: Box::new(crate::LfVorgangsdaten::default()),
                validation_passed: true,
                validation_errors: vec![],
            },
        );
        assert!(result.is_err());
    }

    #[test]
    fn timeout_in_beendet_is_noop() {
        let data = LfAbmeldungData {
            location_id: malo("51238696781"),
            sender: mcod("9900357000004"),
            receiver: mcod("4012345000023"),
            document_date: "20251001".to_owned(),
            process_date: "20260101".to_owned(),
            pruefidentifikator: pid(55007),
            vorgangsnummer: Some("NNV1234".to_owned()),
        };
        let state = LfAbmeldungState::Beendet(data);
        let dl_id = DeadlineId::new();
        let out = GpkeLfAbmeldungWorkflow::handle(
            &state,
            LfAbmeldungCommand::TimeoutExpired {
                deadline_id: dl_id,
                label: LF_ABMELDUNG_ANTWORT_WINDOW_LABEL.into(),
            },
        )
        .unwrap();
        assert!(out.events.is_empty());
    }
}