1use core::fmt;
106
107use carrier_core::Calendar;
108use carrier_core::count::day_of;
109use jiff::Timestamp;
110use jiff::civil::Date;
111
112use crate::deadline::{self, Deadline};
113use crate::{
114 Aenderungskennzeichen, Antwortcode, Auftrag, ExterneAuftragsnummer, Geschaeftsfall, GeschaeftsfallCode, JaNein,
115 LineId, Meldung, Meldungscode, Meldungsinhalt, Meldungstyp, StoerungsNr, Teq, VorabstimmungsId,
116};
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
120pub enum Role {
121 Auftraggeber,
124 Leistungserbringer,
127 AbgebenderProvider,
129}
130
131impl fmt::Display for Role {
132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133 f.write_str(match self {
134 Self::Auftraggeber => "Auftraggeber",
135 Self::Leistungserbringer => "Leistungserbringer",
136 Self::AbgebenderProvider => "abgebender Provider",
137 })
138 }
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
143pub enum Direction {
144 Sent,
146 Received,
148}
149
150#[derive(Debug, Clone, PartialEq, Eq)]
152#[allow(clippy::large_enum_variant)]
153pub enum Message {
154 Auftrag(Auftrag),
157 Meldung(Meldung),
159 Teq(Teq),
161}
162
163impl From<Auftrag> for Message {
164 fn from(a: Auftrag) -> Self {
165 Self::Auftrag(a)
166 }
167}
168impl From<Meldung> for Message {
169 fn from(m: Meldung) -> Self {
170 Self::Meldung(m)
171 }
172}
173impl From<Teq> for Message {
174 fn from(t: Teq) -> Self {
175 Self::Teq(t)
176 }
177}
178
179#[derive(Debug, Clone, PartialEq, Eq)]
181pub struct Event {
182 pub at: Timestamp,
184 pub direction: Direction,
186 pub sender: Role,
188 pub message: Message,
190}
191
192#[derive(Debug, Clone, PartialEq, Eq)]
194pub enum State {
195 Sent,
197 Rejected {
200 code: Meldungscode,
202 },
203 Received,
205 Accepted,
207 Confirmed {
209 liefertermin: Date,
211 },
212 TamOpen {
214 since: Timestamp,
216 },
217 MtamOpen {
219 since: Timestamp,
221 },
222 ErlmKCheck,
224 Completed {
226 erledigungstermin: Date,
228 },
229 Cancelled,
231 Closed,
233 Aborted {
235 code: Meldungscode,
237 },
238}
239
240impl State {
241 #[must_use]
244 pub const fn is_terminal(&self) -> bool {
245 matches!(self, Self::Closed | Self::Aborted { .. })
246 }
247
248 const fn is_open(&self) -> bool {
250 matches!(
251 self,
252 Self::Received
253 | Self::Accepted
254 | Self::Confirmed { .. }
255 | Self::TamOpen { .. }
256 | Self::MtamOpen { .. }
257 | Self::ErlmKCheck
258 )
259 }
260
261 const fn is_after_qeb(&self) -> bool {
263 self.is_open() && !matches!(self, Self::Received)
264 }
265}
266
267impl fmt::Display for State {
268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 match self {
270 Self::Sent => f.write_str("sent"),
271 Self::Rejected { code } => write!(f, "not delivered ({})", code.as_str()),
272 Self::Received => f.write_str("received"),
273 Self::Accepted => f.write_str("accepted (QEB)"),
274 Self::Confirmed { liefertermin } => write!(f, "confirmed for {liefertermin}"),
275 Self::TamOpen { .. } => f.write_str("appointment requested (TAM)"),
276 Self::MtamOpen { .. } => f.write_str("appointment requested again (MTAM)"),
277 Self::ErlmKCheck => f.write_str("reported done (ERLM-K)"),
278 Self::Completed { erledigungstermin } => write!(f, "completed on {erledigungstermin}"),
279 Self::Cancelled => f.write_str("cancelled"),
280 Self::Closed => f.write_str("closed"),
281 Self::Aborted { code } => write!(f, "aborted ({})", code.as_str()),
282 }
283 }
284}
285
286#[derive(Debug, Clone, PartialEq, Eq)]
288pub enum Pending {
289 Storno {
291 since: Timestamp,
293 },
294 Terminverschiebung {
296 since: Timestamp,
298 termin: Option<Date>,
300 },
301}
302
303impl Pending {
304 const fn is_storno(&self) -> bool {
305 matches!(self, Self::Storno { .. })
306 }
307}
308
309#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
311pub enum PvAnswer {
312 Positive,
314 Negative,
316 Missing,
318}
319
320#[derive(Debug, Clone, PartialEq, Eq)]
323pub enum PvLeg {
324 AwaitRuem {
326 antwortfrist: Date,
328 },
329 Refused {
332 antwortcode: Option<Antwortcode>,
334 },
335 Missed,
337 Agreed,
339 Confirmed {
341 uebernahmedatum: Date,
343 },
344 Completed,
346 Closed,
348 Aborted {
350 answer: PvAnswer,
352 },
353}
354
355impl PvLeg {
356 const fn is_open(&self) -> bool {
357 !matches!(self, Self::Closed | Self::Aborted { .. })
358 }
359}
360
361#[derive(Debug, Clone, PartialEq, Eq)]
363#[non_exhaustive]
364pub enum Action {
365 Acknowledge,
367 Resend,
369 Correct,
372 Send(Meldungstyp),
374 Abort(Meldungscode),
376 Storno,
378 Terminverschiebung,
380 AnswerStorno,
382 AnswerTerminverschiebung,
384 Reklamation,
386}
387
388#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
390#[error("{reason}")]
391pub struct Refusal {
392 pub reason: String,
394 pub answer: Option<Meldungscode>,
398}
399
400fn refuse<T>(reason: impl Into<String>) -> Result<T, Refusal> {
401 Err(Refusal { reason: reason.into(), answer: None })
402}
403
404fn refuse_with<T>(answer: Meldungscode, reason: impl Into<String>) -> Result<T, Refusal> {
405 Err(Refusal { reason: reason.into(), answer: Some(answer) })
406}
407
408#[derive(Debug, Clone, Copy, PartialEq, Eq)]
410enum Item {
411 Order,
412 Storno,
413 Tv,
414 Meldung(Meldungstyp),
415}
416
417#[derive(Debug, Clone, PartialEq, Eq)]
419struct Undelivered {
420 from: Role,
421 code: Meldungscode,
422}
423
424#[derive(Debug, Clone, PartialEq, Eq)]
426#[allow(clippy::struct_excessive_bools)] struct Core {
428 state: State,
429 liefertermin: Option<Date>,
430 wunschtermin: Option<Date>,
431 konnektivitaet: bool,
432 activated: bool,
433 abm_seen: bool,
434 pending: Vec<Pending>,
435 pv: Option<PvLeg>,
436 pv_ext: Option<ExterneAuftragsnummer>,
437 abm_pv_owed: bool,
438 undelivered: Option<Undelivered>,
439 stoerungs_nr: Option<StoerungsNr>,
440}
441
442impl Core {
443 fn new(state: State) -> Self {
444 Self {
445 state,
446 liefertermin: None,
447 wunschtermin: None,
448 konnektivitaet: false,
449 activated: false,
450 abm_seen: false,
451 pending: Vec::new(),
452 pv: None,
453 pv_ext: None,
454 abm_pv_owed: false,
455 undelivered: None,
456 stoerungs_nr: None,
457 }
458 }
459}
460
461#[derive(Debug, Clone, PartialEq, Eq)]
463struct Awaiting {
464 from: Role,
465 to: Role,
466 at: Timestamp,
467 attachment: bool,
468 item: Item,
469 before: Box<Core>,
470}
471
472struct Accepted {
474 sender: Role,
475 hop: Option<(Role, Item, bool)>,
476}
477
478#[derive(Debug, Clone, PartialEq, Eq)]
480pub struct Process {
481 role: Role,
482 fall: GeschaeftsfallCode,
483 ext: ExterneAuftragsnummer,
484 calendar: Calendar,
485 core: Core,
486 awaiting: Vec<Awaiting>,
487 history: Vec<Event>,
488}
489
490const fn sender_of(typ: Meldungstyp) -> Role {
491 match typ {
492 Meldungstyp::ErlmK | Meldungstyp::ZwmAg | Meldungstyp::TbkAg => Role::Auftraggeber,
493 Meldungstyp::RuemPv => Role::AbgebenderProvider,
494 _ => Role::Leistungserbringer,
495 }
496}
497
498const fn is_leg(typ: Meldungstyp) -> bool {
499 matches!(
500 typ,
501 Meldungstyp::AkmPv
502 | Meldungstyp::RuemPv
503 | Meldungstyp::AbmPv
504 | Meldungstyp::ErlmPv
505 | Meldungstyp::EntmPv
506 | Meldungstyp::AbbmPv
507 )
508}
509
510const fn receiver_of(typ: Meldungstyp) -> Role {
511 match typ {
512 Meldungstyp::ErlmK | Meldungstyp::ZwmAg | Meldungstyp::TbkAg | Meldungstyp::RuemPv => Role::Leistungserbringer,
513 t if is_leg(t) => Role::AbgebenderProvider,
514 _ => Role::Auftraggeber,
515 }
516}
517
518const fn meldung_has_attachment(m: &Meldungsinhalt) -> bool {
519 match m {
520 Meldungsinhalt::Erlm(x) => x.anlage.is_some(),
521 Meldungsinhalt::Entm(x) => x.anlage.is_some(),
522 Meldungsinhalt::ZwmLe(x) => x.anlage.is_some(),
523 Meldungsinhalt::ZwmAg(x) => x.anlage.is_some(),
524 Meldungsinhalt::AkmPv(x) => x.anlage.is_some(),
525 _ => false,
526 }
527}
528
529const fn order_has_attachment(g: &Geschaeftsfall) -> bool {
530 match g {
531 Geschaeftsfall::Neu(x) => x.anlage.is_some(),
532 Geschaeftsfall::KueAg(x) => x.anlage.is_some(),
533 Geschaeftsfall::Lae(x) => x.anlage.is_some(),
534 Geschaeftsfall::AenLmae(x) => x.anlage.is_some(),
535 Geschaeftsfall::Est(x) => x.anlage.is_some(),
536 Geschaeftsfall::Pv(x) => x.anlage.is_some(),
537 Geschaeftsfall::Get(_) | Geschaeftsfall::Set(_) => false,
538 }
539}
540
541const fn wunschtermin_of(g: &Geschaeftsfall) -> Option<Date> {
542 match g {
543 Geschaeftsfall::Neu(x) => Some(x.wunschtermin.datum),
544 Geschaeftsfall::KueAg(x) => Some(x.wunschtermin.datum),
545 Geschaeftsfall::Lae(x) => Some(x.wunschtermin.datum),
546 Geschaeftsfall::AenLmae(x) => Some(x.wunschtermin.datum),
547 Geschaeftsfall::Est(x) => Some(x.wunschtermin.datum),
548 Geschaeftsfall::Pv(x) => Some(x.wunschtermin.datum),
549 Geschaeftsfall::Get(_) | Geschaeftsfall::Set(_) => None,
550 }
551}
552
553fn is_dummy(line: &LineId) -> bool {
556 line.as_str().rsplit('.').next().is_some_and(|c| !c.is_empty() && c.bytes().all(|b| b == b'0'))
557}
558
559fn has_code(m: &Meldungsinhalt, codes: &[&str]) -> bool {
560 m.codes().iter().any(|c| codes.contains(&c.as_str()))
561}
562
563pub(crate) const fn has_storno(fall: GeschaeftsfallCode) -> bool {
565 !matches!(fall, GeschaeftsfallCode::Get | GeschaeftsfallCode::Set | GeschaeftsfallCode::KueLe)
566}
567
568pub(crate) const fn has_tv(fall: GeschaeftsfallCode) -> bool {
571 matches!(
572 fall,
573 GeschaeftsfallCode::Neu | GeschaeftsfallCode::KueAg | GeschaeftsfallCode::Lae | GeschaeftsfallCode::Pv
574 )
575}
576
577const fn has_tam_loop(fall: GeschaeftsfallCode) -> bool {
579 matches!(fall, GeschaeftsfallCode::Neu | GeschaeftsfallCode::Lae | GeschaeftsfallCode::Pv)
580}
581
582pub(crate) const REFUSAL_CODES: [&str; 5] = ["LnB", "KVE", "TAV", "VnB", "Vnv"];
586
587pub(crate) fn is_refusal_code(code: &Antwortcode) -> bool {
589 REFUSAL_CODES.iter().any(|c| c.eq_ignore_ascii_case(code.as_str()))
590}
591
592fn ruem_negative(r: &crate::RuemPv) -> bool {
594 r.abgebender_provider.zustimmung == JaNein::Nein
595 || r.abgebender_provider.antwortcode.as_ref().is_some_and(is_refusal_code)
596}
597
598impl Process {
599 fn start(role: Role, fall: GeschaeftsfallCode, ext: ExterneAuftragsnummer, core: Core) -> Self {
600 Self { role, fall, ext, calendar: Calendar::werktage(), core, awaiting: Vec::new(), history: Vec::new() }
601 }
602
603 pub fn new(role: Role, auftrag: &Auftrag, direction: Direction, at: Timestamp) -> Result<Self, Refusal> {
614 let expected = match direction {
615 Direction::Sent => Role::Auftraggeber,
616 Direction::Received => Role::Leistungserbringer,
617 };
618 if role != expected {
619 return refuse("an order is sent by the Auftraggeber to the Leistungserbringer (S/PRI 4.4 §8.3)");
620 }
621 if auftrag.aenderungskennzeichen != Aenderungskennzeichen::Standard {
622 return refuse(
623 "a Storno or Terminverschiebung repeats the order number of an existing order (S/PRI 4.4 §5.1.3, §5.1.4)",
624 );
625 }
626 let mut core = Core::new(State::Sent);
627 core.wunschtermin = wunschtermin_of(&auftrag.geschaeftsfall);
628 let fall = auftrag.geschaeftsfall.code();
629 let mut p = Self::start(role, fall, auftrag.externe_auftragsnummer.clone(), core);
630 p.awaiting.push(Awaiting {
631 from: Role::Auftraggeber,
632 to: Role::Leistungserbringer,
633 at,
634 attachment: order_has_attachment(&auftrag.geschaeftsfall),
635 item: Item::Order,
636 before: Box::new(p.core.clone()),
637 });
638 p.history.push(Event { at, direction, sender: Role::Auftraggeber, message: Message::Auftrag(auftrag.clone()) });
639 Ok(p)
640 }
641
642 pub fn from_kdle(role: Role, kdle: &Meldung, direction: Direction, at: Timestamp) -> Result<Self, Refusal> {
654 let Meldungsinhalt::Kdle(k) = &kdle.inhalt else {
655 return refuse("a KUE-LE process starts with a KDLE (Anl. 7 EPK V.13 p.4)");
656 };
657 if kdle.auftragstyp.geschaeftsfall != GeschaeftsfallCode::KueLe {
658 return refuse("a KDLE belongs to business case KUE-LE (Anl. 7 EPK V.13 p.4)");
659 }
660 let expected = match direction {
661 Direction::Sent => Role::Leistungserbringer,
662 Direction::Received => Role::Auftraggeber,
663 };
664 if role != expected {
665 return refuse("a KDLE is sent by the Leistungserbringer to the Auftraggeber (S/PRI 4.4 §8.2.11)");
666 }
667 if k.abschaltungstermin <= day_of(at) {
668 return refuse("a KDLE names a shutdown date in the future (S/PRI 4.4 §8.2.11)");
669 }
670 let mut core = Core::new(State::Confirmed { liefertermin: k.abschaltungstermin });
671 core.liefertermin = Some(k.abschaltungstermin);
672 let mut p = Self::start(role, GeschaeftsfallCode::KueLe, k.externe_auftragsnummer.clone(), core);
673 p.awaiting.push(Awaiting {
674 from: Role::Leistungserbringer,
675 to: Role::Auftraggeber,
676 at,
677 attachment: false,
678 item: Item::Meldung(Meldungstyp::Kdle),
679 before: Box::new(p.core.clone()),
680 });
681 p.history.push(Event {
682 at,
683 direction,
684 sender: Role::Leistungserbringer,
685 message: Message::Meldung(kdle.clone()),
686 });
687 Ok(p)
688 }
689
690 pub fn from_akm_pv(akm_pv: &Meldung, at: Timestamp) -> Result<Self, Refusal> {
699 let Meldungsinhalt::AkmPv(a) = &akm_pv.inhalt else {
700 return refuse("the losing provider's process starts with an AKM-PV (Anl. 7 EPK V.13 p.7)");
701 };
702 if akm_pv.auftragstyp.geschaeftsfall != GeschaeftsfallCode::Pv {
703 return refuse("an AKM-PV belongs to business case PV (Anl. 7 EPK V.13 p.7)");
704 }
705 let mut core = Core::new(State::Accepted);
706 core.pv = Some(PvLeg::AwaitRuem { antwortfrist: a.aufnehmender_provider.antwortfrist });
707 core.pv_ext = Some(a.externe_auftragsnummer.clone());
708 core.wunschtermin = Some(a.aufnehmender_provider.uebernahmedatum_geplant);
709 let mut p =
710 Self::start(Role::AbgebenderProvider, GeschaeftsfallCode::Pv, a.externe_auftragsnummer.clone(), core);
711 p.awaiting.push(Awaiting {
712 from: Role::Leistungserbringer,
713 to: Role::AbgebenderProvider,
714 at,
715 attachment: a.anlage.is_some(),
716 item: Item::Meldung(Meldungstyp::AkmPv),
717 before: Box::new(p.core.clone()),
718 });
719 p.history.push(Event {
720 at,
721 direction: Direction::Received,
722 sender: Role::Leistungserbringer,
723 message: Message::Meldung(akm_pv.clone()),
724 });
725 Ok(p)
726 }
727
728 #[must_use]
732 pub fn with_konnektivitaet(mut self) -> Self {
733 if self.fall == GeschaeftsfallCode::Neu {
734 self.core.konnektivitaet = true;
735 for w in &mut self.awaiting {
736 w.before.konnektivitaet = true;
737 }
738 }
739 self
740 }
741
742 #[must_use]
745 pub fn with_calendar(mut self, calendar: Calendar) -> Self {
746 self.calendar = calendar;
747 self
748 }
749
750 #[must_use]
752 pub const fn role(&self) -> Role {
753 self.role
754 }
755
756 #[must_use]
758 pub const fn geschaeftsfall(&self) -> GeschaeftsfallCode {
759 self.fall
760 }
761
762 #[must_use]
764 pub const fn externe_auftragsnummer(&self) -> &ExterneAuftragsnummer {
765 &self.ext
766 }
767
768 #[must_use]
770 pub const fn state(&self) -> &State {
771 &self.core.state
772 }
773
774 #[must_use]
777 pub fn vorabstimmungs_id(&self) -> Option<&VorabstimmungsId> {
778 self.history.first().and_then(|e| match &e.message {
779 Message::Auftrag(a) => a.geschaeftsfall.vorabstimmungs_id(),
780 Message::Meldung(Meldung { inhalt: Meldungsinhalt::AkmPv(a), .. }) => a.vorabstimmungs_id.as_ref(),
781 Message::Meldung(_) | Message::Teq(_) => None,
782 })
783 }
784
785 #[must_use]
787 pub const fn liefertermin(&self) -> Option<Date> {
788 self.core.liefertermin
789 }
790
791 #[must_use]
793 pub const fn is_konnektivitaet(&self) -> bool {
794 self.core.konnektivitaet
795 }
796
797 #[must_use]
799 pub fn pending(&self) -> &[Pending] {
800 &self.core.pending
801 }
802
803 #[must_use]
806 pub const fn pv(&self) -> Option<&PvLeg> {
807 self.core.pv.as_ref()
808 }
809
810 #[must_use]
812 pub fn history(&self) -> &[Event] {
813 &self.history
814 }
815
816 #[must_use]
819 pub const fn is_aborted_by_kdle(&self) -> bool {
820 !matches!(
821 self.fall,
822 GeschaeftsfallCode::Est | GeschaeftsfallCode::Get | GeschaeftsfallCode::Set | GeschaeftsfallCode::KueLe
823 ) && (self.core.state.is_open() || matches!(self.core.state, State::Sent))
824 }
825
826 pub fn apply(&mut self, direction: Direction, at: Timestamp, message: impl Into<Message>) -> Result<(), Refusal> {
832 let message = message.into();
833 let before = self.core.clone();
834 let before_awaiting = self.awaiting.clone();
835 let result = match &message {
836 Message::Auftrag(a) => self.auftrag(a, direction, at),
837 Message::Meldung(m) => self.meldung(m, direction, at),
838 Message::Teq(t) => self.teq(t, direction),
839 };
840 match result {
841 Ok(Accepted { sender, hop }) => {
842 if let Some((to, item, attachment)) = hop {
843 self.awaiting.retain(|w| w.to != sender);
846 if self.core.undelivered.as_ref().is_some_and(|u| u.from == sender) {
847 self.core.undelivered = None;
848 }
849 self.awaiting.push(Awaiting { from: sender, to, at, attachment, item, before: Box::new(before) });
850 }
851 self.history.push(Event { at, direction, sender, message });
852 Ok(())
853 }
854 Err(e) => {
855 self.core = before;
856 self.awaiting = before_awaiting;
857 Err(e)
858 }
859 }
860 }
861
862 fn check_direction(&self, direction: Direction, from: Role, to: Role, what: &str) -> Result<(), Refusal> {
863 match direction {
864 Direction::Sent if self.role != from => refuse(format!("{what} is sent by the {from}")),
865 Direction::Received if self.role != to => refuse(format!("{what} is addressed to the {to}")),
866 _ => Ok(()),
867 }
868 }
869
870 fn auftrag(&mut self, a: &Auftrag, direction: Direction, at: Timestamp) -> Result<Accepted, Refusal> {
871 self.check_direction(direction, Role::Auftraggeber, Role::Leistungserbringer, "an order")?;
872 if a.externe_auftragsnummer != self.ext {
873 return refuse("an order with another order number starts its own process (S/PRI 4.4 §11.4)");
874 }
875 if a.geschaeftsfall.code() != self.fall {
876 return refuse("a Storno or Terminverschiebung keeps the business case of the order (S/PRI 4.4 §5.1.3)");
877 }
878 let attachment = order_has_attachment(&a.geschaeftsfall);
879 let item = match a.aenderungskennzeichen {
880 Aenderungskennzeichen::Standard => {
881 self.resend_or_reklamation(a)?;
882 Item::Order
883 }
884 Aenderungskennzeichen::Storno => {
885 self.check_storno(at)?;
886 self.core.pending.push(Pending::Storno { since: at });
887 Item::Storno
888 }
889 Aenderungskennzeichen::Terminverschiebung => {
890 let termin = a.termin_neu.or_else(|| wunschtermin_of(&a.geschaeftsfall));
891 self.check_tv(at, termin)?;
892 if self.core.state == State::Accepted {
893 self.core.wunschtermin = termin;
895 }
896 self.core.pending.push(Pending::Terminverschiebung { since: at, termin });
897 Item::Tv
898 }
899 };
900 Ok(Accepted { sender: Role::Auftraggeber, hop: Some((Role::Leistungserbringer, item, attachment)) })
901 }
902
903 fn resend_or_reklamation(&mut self, a: &Auftrag) -> Result<(), Refusal> {
904 match (&self.core.state, &a.geschaeftsfall) {
905 (State::Rejected { .. }, _) => {
906 self.core.state = State::Sent;
908 self.core.wunschtermin = wunschtermin_of(&a.geschaeftsfall);
909 Ok(())
910 }
911 (State::Completed { .. } | State::Closed, Geschaeftsfall::Est(e)) if e.reklamation.is_some() => {
912 if let (Some(known), Some(r)) = (&self.core.stoerungs_nr, &e.reklamation)
913 && *known != r.stoerungs_nr_leistungserbringer
914 {
915 return refuse(
916 "an EST Reklamation names the network owner's ticket of the repair (S/PRI 4.4 §6.1.5)",
917 );
918 }
919 let stoerungs_nr = self.core.stoerungs_nr.take();
920 self.core = Core::new(State::Sent);
921 self.core.stoerungs_nr = stoerungs_nr;
922 self.core.wunschtermin = Some(e.wunschtermin.datum);
923 Ok(())
924 }
925 (State::Completed { .. } | State::Closed, Geschaeftsfall::Est(_)) => refuse(
926 "after a repair the same order number returns only as a Reklamation (Anl. 7 EPK V.13 p.8; S/PRI 4.4 §6.1.5)",
927 ),
928 _ => refuse("the order was already sent; a repeated order is refused (S/PRI 4.4 §11.4)"),
929 }
930 }
931
932 fn has_pending(&self, storno: bool) -> bool {
933 self.core.pending.iter().any(|p| p.is_storno() == storno)
934 }
935
936 fn take_pending(&mut self, storno: bool) -> bool {
937 let before = self.core.pending.len();
938 self.core.pending.retain(|p| p.is_storno() != storno);
939 self.core.pending.len() != before
940 }
941
942 fn check_storno(&self, at: Timestamp) -> Result<(), Refusal> {
944 if !has_storno(self.fall) {
945 return refuse_with(Meldungscode::C1007, "no Storno in DIAG and KUE-LE (Anl. 7 EPK V.13 p.4, p.9)");
946 }
947 if !self.core.state.is_after_qeb() {
948 return refuse_with(
949 Meldungscode::C1087,
950 "a Storno is sent after the QEB and before the ERLM (AH 2.9.5 §3.5)",
951 );
952 }
953 if self.has_pending(true) {
954 return refuse_with(Meldungscode::C1086, "a Storno is already open (Anl. 7 EPK V.13 p.11)");
955 }
956 if let State::Confirmed { liefertermin } = self.core.state {
957 let latest = deadline::storno_latest(liefertermin);
958 if latest.is_overdue(at) {
959 return refuse_with(Meldungscode::C1087, format!("Storno too late: {}", latest.rule.text));
960 }
961 }
962 Ok(())
963 }
964
965 fn check_tv(&self, at: Timestamp, termin: Option<Date>) -> Result<(), Refusal> {
967 if !has_tv(self.fall) {
968 return refuse_with(
969 Meldungscode::C1007,
970 "no Terminverschiebung in AEN-LMAE, EST, DIAG and KUE-LE (S/PRI 4.4 §5.3.1.3, §6.1.3; Anl. 7 EPK V.13 p.9)",
971 );
972 }
973 if !self.core.state.is_after_qeb() {
974 return refuse_with(
975 Meldungscode::C1085,
976 "a Terminverschiebung is sent after the QEB and before the ERLM (AH 2.9.5 §3.4)",
977 );
978 }
979 if self.has_pending(false) {
980 return refuse_with(Meldungscode::C1085, "a Terminverschiebung is already open (Anl. 7 EPK V.13 p.12)");
981 }
982 if self.core.konnektivitaet && !self.core.abm_seen {
983 return refuse_with(
984 Meldungscode::C1085,
985 "no Terminverschiebung before the first ABM of a Konnektivität order (AH 2.9.5 §3.4.1; S/PRI 4.4 §5.1.4)",
986 );
987 }
988 let current = self.core.liefertermin.or(self.core.wunschtermin);
989 if let (Some(new), Some(old)) = (termin, current) {
990 if new == old {
991 return refuse_with(Meldungscode::C1085, "a Terminverschiebung names a new date (S/PRI 4.4 §5.1.4)");
992 }
993 if self.fall == GeschaeftsfallCode::Pv && new < old {
994 return refuse_with(
995 Meldungscode::C1085,
996 "in PV the date cannot move earlier after the positive pre-agreement (AH 2.9.5 §3.4)",
997 );
998 }
999 }
1000 if let State::Confirmed { liefertermin } = self.core.state {
1001 let latest = deadline::terminverschiebung_latest(liefertermin);
1002 if latest.is_overdue(at) {
1003 return refuse_with(Meldungscode::C1085, format!("Terminverschiebung too late: {}", latest.rule.text));
1004 }
1005 }
1006 Ok(())
1007 }
1008
1009 fn answers(&self, m: &Meldung) -> Option<bool> {
1012 match m.auftragstyp.aenderungskennzeichen {
1013 Aenderungskennzeichen::Storno => return Some(true),
1014 Aenderungskennzeichen::Terminverschiebung => return Some(false),
1015 Aenderungskennzeichen::Standard => {}
1016 }
1017 match &m.inhalt {
1018 Meldungsinhalt::Abbm(_) => {
1019 if has_code(&m.inhalt, &["1086", "1087"]) {
1020 Some(true)
1021 } else if has_code(&m.inhalt, &["1085", "7523"])
1022 || (self.has_pending(false) && has_code(&m.inhalt, &["7522", "7524"]))
1023 {
1024 Some(false)
1025 } else if has_code(&m.inhalt, &["1007"]) && self.core.pending.len() == 1 {
1026 self.core.pending.first().map(Pending::is_storno)
1027 } else {
1028 None
1029 }
1030 }
1031 Meldungsinhalt::Erlm(_) if has_code(&m.inhalt, &["0012"]) => Some(true),
1032 _ => None,
1033 }
1034 }
1035
1036 fn meldung(&mut self, m: &Meldung, direction: Direction, at: Timestamp) -> Result<Accepted, Refusal> {
1037 let typ = m.typ();
1038 let (from, to) = (sender_of(typ), receiver_of(typ));
1039 self.check_direction(direction, from, to, &format!("a {typ}"))?;
1040 if m.auftragstyp.geschaeftsfall != self.fall {
1041 return refuse(format!("a {typ} of another business case"));
1042 }
1043 let ext = m.externe_auftragsnummer();
1044 if is_leg(typ) {
1045 if self.core.pv_ext.as_ref().is_some_and(|e| e != ext) {
1046 return refuse(format!("a {typ} refers to another provider switch"));
1047 }
1048 self.leg(m, typ, at)?;
1049 } else {
1050 if *ext != self.ext {
1051 return refuse(format!("a {typ} refers to another order number"));
1052 }
1053 if self.core.state.is_terminal() {
1054 return refuse(format!("no {typ} after the order has ended (S/PRI 4.4 §8.2.4, §8.2.5)"));
1055 }
1056 match self.core.state {
1057 State::Rejected { .. } => {
1058 return refuse(format!("no {typ}: the order was not delivered (Anl. 7 EPK V.13 p.10)"));
1059 }
1060 State::Sent if from == Role::Leistungserbringer => self.core.state = State::Received,
1061 _ => {}
1062 }
1063 self.order_meldung(m, typ, at)?;
1064 }
1065 Ok(Accepted { sender: from, hop: Some((to, Item::Meldung(typ), meldung_has_attachment(&m.inhalt))) })
1066 }
1067
1068 #[allow(clippy::too_many_lines)] fn order_meldung(&mut self, m: &Meldung, typ: Meldungstyp, at: Timestamp) -> Result<(), Refusal> {
1070 use GeschaeftsfallCode as G;
1071 let fall = self.fall;
1072 let state = self.core.state.clone();
1073 let diag = matches!(fall, G::Get | G::Set);
1074 match &m.inhalt {
1075 Meldungsinhalt::Qeb(q) => {
1076 if diag || fall == G::KueLe {
1077 return refuse("no QEB in DIAG and KUE-LE (Anl. 7 EPK V.13 p.4, p.9)");
1078 }
1079 if state != State::Received {
1080 return refuse("a QEB is the first message, once, before the ABM (S/PRI 4.4 §8.2.1, §8.2.2)");
1081 }
1082 self.core.state = State::Accepted;
1083 self.core.stoerungs_nr.clone_from(&q.stoerungs_nr_leistungserbringer);
1084 }
1085 Meldungsinhalt::Vzm(_) => {
1086 if diag || fall == G::KueLe {
1087 return refuse("no VZM in DIAG and KUE-LE (Anl. 7 EPK V.13 p.4, p.9)");
1088 }
1089 match self.answers(m) {
1090 Some(true) if fall == G::Est => {
1091 return refuse("no VZM to a Storno in EST (Anl. 7 EPK V.13 p.11)");
1092 }
1093 Some(storno) if !self.has_pending(storno) => {
1094 return refuse(
1095 "a VZM to a Storno or Terminverschiebung needs one open (Anl. 7 EPK V.13 p.11, p.12)",
1096 );
1097 }
1098 None if !state.is_open() => {
1099 return refuse("a VZM comes between the receipt and the ERLM (S/PRI 4.4 §8.2.6)");
1100 }
1101 _ => {}
1102 }
1103 }
1104 Meldungsinhalt::Abm(a) => self.abm(m, a, &state)?,
1105 Meldungsinhalt::Abbm(_) => self.abbm(m, &state, at)?,
1106 Meldungsinhalt::Erlm(e) => {
1107 if self.answers(m) == Some(false) {
1108 return refuse("a Terminverschiebung is not answered with an ERLM (Anl. 7 EPK V.13 p.12)");
1109 }
1110 if self.answers(m) == Some(true) {
1111 if !self.take_pending(true) {
1112 return refuse("an ERLM to a Storno needs an open Storno (Anl. 7 EPK V.13 p.11)");
1113 }
1114 self.core.pending.clear();
1115 self.core.state = State::Cancelled;
1116 return Ok(());
1117 }
1118 let allowed = match fall {
1119 G::Get | G::Set => state == State::Received,
1120 G::KueLe => matches!(state, State::Confirmed { .. }),
1121 G::Est => state == State::Accepted,
1122 _ => matches!(state, State::Confirmed { .. } | State::ErlmKCheck),
1123 };
1124 if !allowed {
1125 return refuse(match fall {
1126 G::Get | G::Set => "a DIAG ends with ERLM or ABBM after the receipt (Anl. 7 EPK V.13 p.9)",
1127 G::Est => "an EST is completed after the QEB, outside a TAM (Anl. 7 EPK V.13 p.8)",
1128 _ => {
1129 "an ERLM follows the ABM, or the check of an ERLM-K (Anl. 7 EPK V.13 p.1, p.3, p.5–7; S/PRI 4.4 §8.2.3)"
1130 }
1131 });
1132 }
1133 if self.core.konnektivitaet && !self.core.activated {
1134 return refuse(
1135 "a Konnektivität order completes after the activation ABM with a real LineID (Anl. 7 EPK V.13 p.2; S/PRI 4.4 §5.1.6)",
1136 );
1137 }
1138 self.core.pending.clear();
1139 self.core.state =
1140 if diag { State::Closed } else { State::Completed { erledigungstermin: e.erledigungstermin } };
1141 }
1142 Meldungsinhalt::Entm(_) => {
1143 if diag {
1144 return refuse("no ENTM in DIAG (Anl. 7 EPK V.13 p.9)");
1145 }
1146 if !matches!(state, State::Completed { .. } | State::Cancelled) {
1147 return refuse("an ENTM follows the ERLM (S/PRI 4.4 §8.2.3, §8.2.4)");
1148 }
1149 self.core.state = State::Closed;
1150 }
1151 Meldungsinhalt::Tam(_) => {
1152 let ok = match fall {
1153 G::Est => state == State::Accepted,
1154 f if has_tam_loop(f) => matches!(state, State::Confirmed { .. } | State::ErlmKCheck),
1155 _ => false,
1156 };
1157 if !ok {
1158 return refuse(
1159 "a TAM comes after the ABM (EST: after the QEB) in NEU, LAE, PV and EST (S/PRI 4.4 §8.2.7; AH 2.9.5 §3.6)",
1160 );
1161 }
1162 self.core.state = State::TamOpen { since: at };
1163 }
1164 Meldungsinhalt::Mtam(_) => {
1165 if !has_tam_loop(fall) || !matches!(state, State::TamOpen { .. }) {
1166 return refuse("an MTAM follows an unanswered TAM in NEU, LAE and PV (AH 2.9.5 §3.6)");
1167 }
1168 self.core.state = State::MtamOpen { since: at };
1169 }
1170 Meldungsinhalt::ErlmK(_) => {
1171 let ok = has_tam_loop(fall)
1172 && (matches!(state, State::TamOpen { .. } | State::MtamOpen { .. })
1173 || (fall == G::Pv && matches!(state, State::Confirmed { .. })));
1174 if !ok {
1175 return refuse(
1176 "an ERLM-K answers a TAM or MTAM in NEU, LAE and PV, in PV also after the ABM (AH 2.9.5 §3.6; Anl. 7 EPK V.13 p.7)",
1177 );
1178 }
1179 self.core.state = State::ErlmKCheck;
1180 }
1181 Meldungsinhalt::TbkLe(_) => {
1182 if fall != G::Est || state != State::Accepted {
1183 return refuse("a TBK-LE comes in an EST after the QEB (Anl. 7 EPK V.13 p.8)");
1184 }
1185 }
1186 Meldungsinhalt::TbkAg(_) => {
1187 if fall != G::Est || !matches!(state, State::TamOpen { .. }) {
1188 return refuse("a TBK-AG answers the TAM of an EST (Anl. 7 EPK V.13 p.8)");
1189 }
1190 self.core.state = State::Accepted;
1191 }
1192 Meldungsinhalt::ZwmLe(_) | Meldungsinhalt::ZwmAg(_) => {
1193 if !matches!(fall, G::Neu | G::Est) || !state.is_after_qeb() {
1194 return refuse(format!(
1195 "a {typ} comes between the QEB and the ERLM in NEU and EST (S/PRI 4.4 §8.2.9, §8.3.1; Anl. 7 EPK V.13 p.1, p.8)"
1196 ));
1197 }
1198 }
1199 Meldungsinhalt::Kdle(_) => {
1200 return refuse("a KDLE starts its own process (Anl. 7 EPK V.13 p.4)");
1201 }
1202 Meldungsinhalt::AkmPv(_)
1203 | Meldungsinhalt::RuemPv(_)
1204 | Meldungsinhalt::AbmPv(_)
1205 | Meldungsinhalt::ErlmPv(_)
1206 | Meldungsinhalt::EntmPv(_)
1207 | Meldungsinhalt::AbbmPv(_) => {}
1208 }
1209 Ok(())
1210 }
1211
1212 fn abm(&mut self, m: &Meldung, a: &crate::Abm, state: &State) -> Result<(), Refusal> {
1213 use GeschaeftsfallCode as G;
1214 let fall = self.fall;
1215 if matches!(fall, G::Est | G::Get | G::Set | G::KueLe) {
1216 return refuse("no ABM in EST, DIAG and KUE-LE (Anl. 7 EPK V.13 p.4, p.8, p.9)");
1217 }
1218 if m.auftragstyp.aenderungskennzeichen != Aenderungskennzeichen::Standard {
1219 return refuse("an ABM carries the Änderungskennzeichen Standard, also after a TV (AH 2.9.5 §3.4)");
1220 }
1221 let tv_open = self.has_pending(false);
1222 match state {
1223 State::Accepted => {
1224 if self.role == Role::Leistungserbringer
1225 && fall == G::Pv
1226 && !matches!(self.core.pv, Some(PvLeg::Agreed | PvLeg::Confirmed { .. }))
1227 {
1228 return refuse("in PV the ABM follows a positive RUEM-PV (Anl. 7 EPK V.13 p.7)");
1229 }
1230 }
1231 State::Confirmed { .. } | State::TamOpen { .. } | State::MtamOpen { .. } | State::ErlmKCheck => {
1232 let repeat = m.codes().iter().any(|c| {
1233 ["6012", "8500", "8501", "8502"].contains(&c.as_str()) && c.applies(Meldungstyp::Abm, fall)
1234 });
1235 if !repeat && !tv_open {
1236 return refuse(
1237 "a repeated ABM carries 6012 or 8500–8502 or confirms a Terminverschiebung (Anl. 7 EPK V.13 p.1, p.3, p.6, p.7, p.12)",
1238 );
1239 }
1240 }
1241 State::Received => return refuse("the QEB comes before the ABM (S/PRI 4.4 §8.2.2)"),
1242 _ => return refuse("an ABM comes after the QEB and before the ERLM (S/PRI 4.4 §8.2.2, §8.2.3)"),
1243 }
1244 let dummy = is_dummy(&a.anschluss.line_id);
1245 if fall == G::Neu && !self.core.abm_seen && dummy {
1246 self.core.konnektivitaet = true;
1247 }
1248 if self.core.konnektivitaet && !dummy {
1249 self.core.activated = true;
1250 }
1251 self.take_pending(false);
1252 self.core.abm_seen = true;
1253 let date = a.verbindlicher_liefertermin.datum;
1254 self.core.liefertermin = Some(date);
1255 self.core.state = State::Confirmed { liefertermin: date };
1256 if self.role == Role::Leistungserbringer && self.core.pv.is_some() {
1257 self.core.abm_pv_owed = true;
1258 }
1259 Ok(())
1260 }
1261
1262 fn abbm(&mut self, m: &Meldung, state: &State, at: Timestamp) -> Result<(), Refusal> {
1263 use GeschaeftsfallCode as G;
1264 let fall = self.fall;
1265 if fall == G::KueLe {
1266 return refuse("no ABBM in KUE-LE (Anl. 7 EPK V.13 p.4)");
1267 }
1268 if let Some(storno) = self.answers(m) {
1269 if !self.take_pending(storno) {
1270 return refuse("an ABBM to a Storno or Terminverschiebung needs one open (Anl. 7 EPK V.13 p.11, p.12)");
1271 }
1272 return Ok(());
1273 }
1274 if !state.is_open() {
1275 return refuse("an ABBM comes between the receipt and the ERLM (S/PRI 4.4 §8.2.5)");
1276 }
1277 let le = self.role == Role::Leistungserbringer;
1278 if has_code(&m.inhalt, &["1198"]) && !matches!(state, State::MtamOpen { .. }) {
1279 return refuse("ABBM 1198 follows an unanswered MTAM (AH 2.9.5 §3.6)");
1280 }
1281 if has_code(&m.inhalt, &["7015"]) && !(fall == G::Est && matches!(state, State::TamOpen { .. })) {
1282 return refuse("ABBM 7015 follows an unanswered TAM of an EST (Anl. 7 EPK V.13 p.8)");
1283 }
1284 if has_code(&m.inhalt, &["0041"]) {
1285 let ok = if le {
1286 matches!(self.core.pv, Some(PvLeg::Refused { .. } | PvLeg::Aborted { answer: PvAnswer::Negative }))
1287 } else {
1288 fall == G::Pv && *state == State::Accepted
1289 };
1290 if !ok {
1291 return refuse("ABBM 0041 follows a negative RUEM-PV (Anl. 7 EPK V.13 p.7)");
1292 }
1293 }
1294 if has_code(&m.inhalt, &["0042"]) {
1295 let ok = if le {
1296 match &self.core.pv {
1297 Some(PvLeg::AwaitRuem { antwortfrist }) => {
1298 let missed = deadline::ruem_pv(*antwortfrist).is_overdue(at);
1299 if missed {
1300 self.core.pv = Some(PvLeg::Missed);
1301 }
1302 missed
1303 }
1304 Some(PvLeg::Missed | PvLeg::Aborted { answer: PvAnswer::Missing }) => true,
1305 _ => false,
1306 }
1307 } else {
1308 fall == G::Pv && *state == State::Accepted
1309 };
1310 if !ok {
1311 return refuse("ABBM 0042 follows the antwortfrist of the AKM-PV without RUEM-PV (S/PRI 4.4 §5.5.1.1)");
1312 }
1313 }
1314 let code = m.codes().first().map_or_else(|| Meldungscode::parse(""), |c| (*c).clone());
1315 self.core.pending.clear();
1316 self.core.state = State::Aborted { code };
1317 Ok(())
1318 }
1319
1320 #[allow(clippy::too_many_lines)] fn leg(&mut self, m: &Meldung, typ: Meldungstyp, at: Timestamp) -> Result<(), Refusal> {
1322 if self.fall != GeschaeftsfallCode::Pv {
1323 return refuse(format!("a {typ} belongs to a provider switch (Anl. 7 EPK V.13 p.7)"));
1324 }
1325 let le = self.role == Role::Leistungserbringer;
1326 let ekp_ab = self.role == Role::AbgebenderProvider;
1327 let leg = self.core.pv.clone();
1328 match &m.inhalt {
1329 Meldungsinhalt::AkmPv(a) => {
1330 if leg.is_some() {
1331 return refuse("one AKM-PV per order; no new AKM-PV on a TV (S/PRI 4.4 §5.5.1.3)");
1332 }
1333 if self.core.state != State::Accepted {
1334 return refuse("the AKM-PV follows the QEB, before the ABM (Anl. 7 EPK V.13 p.7)");
1335 }
1336 self.core.pv = Some(PvLeg::AwaitRuem { antwortfrist: a.aufnehmender_provider.antwortfrist });
1337 self.core.pv_ext = Some(a.externe_auftragsnummer.clone());
1338 }
1339 Meldungsinhalt::RuemPv(r) => {
1340 let Some(PvLeg::AwaitRuem { antwortfrist }) = leg else {
1341 return refuse("a RUEM-PV answers the AKM-PV, once (Anl. 7 EPK V.13 p.7)");
1342 };
1343 if deadline::ruem_pv(antwortfrist).is_overdue(at) {
1344 return refuse(
1345 "a RUEM-PV after the antwortfrist comes too late: the network owner aborts (S/PRI 4.4 §5.5.1.1)",
1346 );
1347 }
1348 if le && !self.core.state.is_open() {
1349 return refuse(
1350 "after the order ended the losing provider's messages are discarded (S/PRI 4.4 §5.5.1.2)",
1351 );
1352 }
1353 self.core.pv = Some(if ruem_negative(r) {
1354 PvLeg::Refused { antwortcode: r.abgebender_provider.antwortcode.clone() }
1355 } else {
1356 PvLeg::Agreed
1357 });
1358 }
1359 Meldungsinhalt::AbmPv(a) => {
1360 if !matches!(leg, Some(PvLeg::Agreed | PvLeg::Confirmed { .. })) {
1361 return refuse("an ABM-PV follows a positive RUEM-PV (Anl. 7 EPK V.13 p.7)");
1362 }
1363 if le && !self.core.abm_pv_owed {
1364 return refuse("an ABM-PV is sent together with an ABM (S/PRI 4.4 §8.2.13)");
1365 }
1366 self.core.abm_pv_owed = false;
1367 let uebernahmedatum = a.aufnehmender_provider.uebernahmedatum_verbindlich;
1368 self.core.pv = Some(PvLeg::Confirmed { uebernahmedatum });
1369 if ekp_ab {
1370 self.core.liefertermin = Some(uebernahmedatum);
1371 self.core.state = State::Confirmed { liefertermin: uebernahmedatum };
1372 }
1373 }
1374 Meldungsinhalt::ErlmPv(e) => {
1375 if !matches!(leg, Some(PvLeg::Confirmed { .. })) {
1376 return refuse("an ERLM-PV follows the ABM-PV (Anl. 7 EPK V.13 p.7)");
1377 }
1378 if le && !matches!(self.core.state, State::Completed { .. } | State::Closed) {
1379 return refuse("an ERLM-PV is sent together with the ERLM (Anl. 7 EPK V.13 p.7)");
1380 }
1381 self.core.pv = Some(PvLeg::Completed);
1382 if ekp_ab {
1383 self.core.state = State::Completed { erledigungstermin: e.erledigungstermin };
1384 }
1385 }
1386 Meldungsinhalt::EntmPv(_) => {
1387 if leg != Some(PvLeg::Completed) {
1388 return refuse("an ENTM-PV follows the ERLM-PV (Anl. 7 EPK V.13 p.7)");
1389 }
1390 self.core.pv = Some(PvLeg::Closed);
1391 if ekp_ab {
1392 self.core.state = State::Closed;
1393 }
1394 }
1395 Meldungsinhalt::AbbmPv(_) => {
1396 let Some(open) = leg.filter(PvLeg::is_open) else {
1397 return refuse("an ABBM-PV ends an open provider-switch leg after the AKM-PV (S/PRI 4.4 §5.5.1.2)");
1398 };
1399 let answer = match &open {
1400 PvLeg::Refused { .. } => PvAnswer::Negative,
1401 PvLeg::AwaitRuem { .. } | PvLeg::Missed => PvAnswer::Missing,
1402 _ => PvAnswer::Positive,
1403 };
1404 if le {
1405 let ok = match &open {
1406 PvLeg::Refused { .. } | PvLeg::Missed => true,
1407 PvLeg::AwaitRuem { antwortfrist } => {
1408 deadline::ruem_pv(*antwortfrist).is_overdue(at) || self.ended_without_switch()
1409 }
1410 PvLeg::Agreed | PvLeg::Confirmed { .. } => self.ended_without_switch(),
1411 _ => false,
1412 };
1413 if !ok {
1414 return refuse(
1415 "an ABBM-PV follows the end of the order without switch: ABBM, Storno, negative or missing RUEM-PV (Anl. 7 EPK V.13 p.7)",
1416 );
1417 }
1418 }
1419 self.core.pv = Some(PvLeg::Aborted { answer });
1420 if ekp_ab {
1421 let code = m.codes().first().map_or_else(|| Meldungscode::parse(""), |c| (*c).clone());
1422 self.core.state = State::Aborted { code };
1423 }
1424 }
1425 _ => {}
1426 }
1427 Ok(())
1428 }
1429
1430 const fn ended_without_switch(&self) -> bool {
1431 matches!(self.core.state, State::Aborted { .. } | State::Cancelled)
1432 }
1433
1434 fn teq(&mut self, t: &Teq, direction: Direction) -> Result<Accepted, Refusal> {
1435 let role = self.role;
1436 let pos = match direction {
1437 Direction::Sent => self.awaiting.iter().position(|w| w.to == role),
1438 Direction::Received => self.awaiting.iter().position(|w| w.from == role),
1439 };
1440 let Some(pos) = pos else {
1441 return refuse("a TEQ acknowledges an order or message awaiting one (Anl. 7 EPK V.13 p.10)");
1442 };
1443 let Some(item) = self.awaiting.get(pos).cloned() else {
1444 return refuse("a TEQ acknowledges an order or message awaiting one (Anl. 7 EPK V.13 p.10)");
1445 };
1446 let leg = matches!(item.item, Item::Meldung(typ) if is_leg(typ));
1447 let expected = if leg { self.core.pv_ext.as_ref().unwrap_or(&self.ext) } else { &self.ext };
1448 if t.externe_auftragsnummer.as_ref().is_some_and(|e| e != expected) {
1449 return refuse("a TEQ refers to another order number");
1450 }
1451 if t.is_ok() && item.item == Item::Order && self.core.state == State::Sent {
1452 self.core.state = State::Received;
1453 }
1454 if t.is_ok() || item.from == Role::Leistungserbringer {
1455 self.awaiting.remove(pos);
1458 } else {
1459 let code = t
1461 .positionen
1462 .iter()
1463 .find(|p| !p.code.is_ok())
1464 .map_or(Meldungscode::TECHNISCHER_FEHLER, |p| p.code.clone());
1465 self.core = *item.before;
1466 self.awaiting.truncate(pos);
1467 if item.item == Item::Order && matches!(self.core.state, State::Sent | State::Rejected { .. }) {
1468 self.core.state = State::Rejected { code: code.clone() };
1469 }
1470 self.core.undelivered = Some(Undelivered { from: item.from, code });
1471 }
1472 Ok(Accepted { sender: item.to, hop: None })
1473 }
1474
1475 #[must_use]
1477 #[allow(clippy::too_many_lines)] pub fn next_actions(&self, role: Role) -> Vec<Action> {
1479 use GeschaeftsfallCode as G;
1480 use Meldungstyp as T;
1481 let mut out = Vec::new();
1482 if self.awaiting.iter().any(|w| w.to == role) {
1483 out.push(Action::Acknowledge);
1484 }
1485 if let Some(u) = &self.core.undelivered
1486 && u.from == role
1487 {
1488 out.push(if u.code == Meldungscode::UEBERLASTET { Action::Resend } else { Action::Correct });
1489 }
1490 let fall = self.fall;
1491 let state = &self.core.state;
1492 let pv = self.core.pv.as_ref();
1493 match role {
1494 Role::Auftraggeber => {
1495 if state.is_after_qeb() {
1496 if has_storno(fall) && !self.has_pending(true) {
1497 out.push(Action::Storno);
1498 }
1499 if has_tv(fall) && !self.has_pending(false) && (!self.core.konnektivitaet || self.core.abm_seen) {
1500 out.push(Action::Terminverschiebung);
1501 }
1502 if matches!(fall, G::Neu | G::Est) {
1503 out.push(Action::Send(T::ZwmAg));
1504 }
1505 }
1506 match state {
1507 State::TamOpen { .. } | State::MtamOpen { .. } if has_tam_loop(fall) => {
1508 out.push(Action::Send(T::ErlmK));
1509 }
1510 State::Confirmed { .. } if fall == G::Pv => out.push(Action::Send(T::ErlmK)),
1511 State::TamOpen { .. } if fall == G::Est => out.push(Action::Send(T::TbkAg)),
1512 State::Completed { .. } | State::Closed if fall == G::Est => out.push(Action::Reklamation),
1513 _ => {}
1514 }
1515 }
1516 Role::Leistungserbringer => {
1517 for p in &self.core.pending {
1518 out.push(if p.is_storno() { Action::AnswerStorno } else { Action::AnswerTerminverschiebung });
1519 }
1520 match state {
1521 State::Received if matches!(fall, G::Get | G::Set) => {
1522 out.extend([Action::Send(T::Erlm), Action::Send(T::Abbm)]);
1523 }
1524 State::Received => out.extend([Action::Send(T::Qeb), Action::Send(T::Vzm), Action::Send(T::Abbm)]),
1525 State::Accepted if fall == G::Est => out.extend([
1526 Action::Send(T::Erlm),
1527 Action::Send(T::Tam),
1528 Action::Send(T::TbkLe),
1529 Action::Send(T::ZwmLe),
1530 Action::Send(T::Vzm),
1531 Action::Send(T::Abbm),
1532 ]),
1533 State::Accepted if fall == G::Pv => match pv {
1534 None => out.push(Action::Send(T::AkmPv)),
1535 Some(PvLeg::Agreed) => out.extend([Action::Send(T::Abm), Action::Send(T::Abbm)]),
1536 Some(PvLeg::Refused { .. }) => out.push(Action::Abort(Meldungscode::C0041)),
1537 Some(PvLeg::Missed) => out.push(Action::Abort(Meldungscode::C0042)),
1538 _ => {}
1539 },
1540 State::Accepted => out.extend([Action::Send(T::Abm), Action::Send(T::Vzm), Action::Send(T::Abbm)]),
1541 State::Confirmed { .. } if fall == G::KueLe => out.push(Action::Send(T::Erlm)),
1542 State::Confirmed { .. } | State::ErlmKCheck => {
1543 if !self.core.konnektivitaet || self.core.activated {
1544 out.push(Action::Send(T::Erlm));
1545 }
1546 if has_tam_loop(fall) {
1547 out.push(Action::Send(T::Tam));
1548 }
1549 out.extend([Action::Send(T::Vzm), Action::Send(T::Abbm)]);
1550 }
1551 State::TamOpen { .. } if fall == G::Est => out.push(Action::Abort(Meldungscode::C7015)),
1552 State::TamOpen { .. } => out.push(Action::Send(T::Mtam)),
1553 State::MtamOpen { .. } => out.push(Action::Abort(Meldungscode::C1198)),
1554 State::Completed { .. } | State::Cancelled => out.push(Action::Send(T::Entm)),
1555 _ => {}
1556 }
1557 if self.core.abm_pv_owed {
1558 out.push(Action::Send(T::AbmPv));
1559 }
1560 match pv {
1561 Some(PvLeg::Confirmed { .. }) if matches!(state, State::Completed { .. } | State::Closed) => {
1562 out.push(Action::Send(T::ErlmPv));
1563 }
1564 Some(PvLeg::Completed) => out.push(Action::Send(T::EntmPv)),
1565 Some(PvLeg::Refused { .. } | PvLeg::Missed) => out.push(Action::Send(T::AbbmPv)),
1566 Some(l) if l.is_open() && self.ended_without_switch() => out.push(Action::Send(T::AbbmPv)),
1567 _ => {}
1568 }
1569 }
1570 Role::AbgebenderProvider => {
1571 if matches!(pv, Some(PvLeg::AwaitRuem { .. })) {
1572 out.push(Action::Send(T::RuemPv));
1573 }
1574 }
1575 }
1576 out
1577 }
1578
1579 #[must_use]
1582 pub fn deadlines(&self) -> Vec<Deadline> {
1583 let mut out: Vec<Deadline> =
1584 self.awaiting.iter().map(|w| deadline::teq_response(w.at, w.to, w.attachment)).collect();
1585 match &self.core.state {
1586 State::Confirmed { liefertermin } if self.role != Role::AbgebenderProvider => {
1587 if has_storno(self.fall) && !self.has_pending(true) {
1588 out.push(deadline::storno_latest(*liefertermin));
1589 }
1590 if has_tv(self.fall) && !self.has_pending(false) {
1591 out.push(deadline::terminverschiebung_latest(*liefertermin));
1592 }
1593 }
1594 State::TamOpen { since } if has_tam_loop(self.fall) => out.push(deadline::mtam_due(*since, &self.calendar)),
1595 State::MtamOpen { since } => out.push(deadline::abbm_1198_due(*since, &self.calendar)),
1596 _ => {}
1597 }
1598 if let Some(PvLeg::AwaitRuem { antwortfrist }) = &self.core.pv {
1599 out.push(deadline::ruem_pv(*antwortfrist));
1600 }
1601 out.sort_by_key(|d| d.due);
1602 out
1603 }
1604
1605 #[must_use]
1609 pub fn overdue(&self, now: Timestamp) -> Vec<Deadline> {
1610 self.deadlines().into_iter().filter(|d| !d.is_window() && d.is_overdue(now)).collect()
1611 }
1612}