mako_engine/erp.rs
1//! ERP integration traits and reference implementations.
2//!
3//! ## Role
4//!
5//! `mako-engine` is a protocol processor — it handles EDIFACT parsing, BDEW
6//! process rules, AS4 delivery, and regulatory deadlines. All contract data,
7//! billing logic, and master data live in the operator's ERP.
8//!
9//! This module defines the **stable integration contract** between `mako-engine`
10//! and external ERP or backend systems. The payload contract is **BO4E**, not
11//! raw EDIFACT. ERP adapters never see EDIFACT segment codes or format-version
12//! identifiers — those are absorbed inside `mako-engine`.
13//!
14//! ## Outbound: mako → ERP
15//!
16//! Implement [`ErpAdapter`] and register it at startup. Every domain event
17//! that requires ERP action is delivered as an [`ErpEvent`]. The production
18//! `WebhookErpAdapter` (in `makod`) serialises events as
19//! **[CloudEvents 1.0](https://cloudevents.io) structured-mode JSON** and POSTs
20//! them to the configured ERP endpoint.
21//!
22//! ```text
23//! POST <erp_webhook_url>
24//! Content-Type: application/cloudevents+json
25//! X-Idempotency-Key: <event.idempotency_key>
26//! webhook-id / webhook-timestamp / webhook-signature ← Standard Webhooks,
27//! only when a secret is set
28//!
29//! {
30//! "specversion": "1.0",
31//! "id": "<idempotency_key>",
32//! "source": "urn:mako:makod:tenant:<tenant_id>",
33//! "type": "de.mako.aperak.accepted",
34//! "time": "2026-10-01T10:15:00+02:00",
35//! "subject": "<process_id>",
36//! "dataschema": "https://.../Marktlokation.json",
37//! "datacontenttype": "application/json",
38//! "makoconvid": "<conversation_id>",
39//! "makocausationid": "<causation_id>",
40//! "makopid": 55001,
41//! "data": { "_typ": "MARKTLOKATION", ... }
42//! }
43//! ```
44//!
45//! See [`ErpEventType::cloud_event_type`] for the full type → CE type mapping.
46//! The BO4E payload is always in the `data` field; the `payload_schema` URL
47//! maps to the CloudEvents `dataschema` attribute.
48//!
49//! ## Inbound: ERP → mako (event-driven)
50//!
51//! For ERP systems with a message bus, implement [`ErpCommandSource`] to feed
52//! BO4E business objects into the engine without a synchronous REST round-trip.
53//!
54//! ```rust,ignore
55//! struct MyKafkaSource { consumer: KafkaConsumer }
56//!
57//! impl ErpCommandSource for MyKafkaSource {
58//! async fn next(&self) -> Result<Option<InboundErpCommand>, ErpAdapterError> {
59//! let msg = self.consumer.poll(Duration::from_millis(100)).await;
60//! Ok(msg.map(|m| InboundErpCommand {
61//! idempotency_key: m.offset().to_string(),
62//! tenant_id: TenantId::new(),
63//! payload_schema: "…/Marktlokation.json".into(),
64//! payload: serde_json::from_slice(m.payload()).unwrap(),
65//! }))
66//! }
67//!
68//! async fn ack(&self, id: &str) -> Result<(), ErpAdapterError> {
69//! self.consumer.commit_offset(id.parse().unwrap()).await
70//! .map_err(ErpAdapterError::transport)
71//! }
72//!
73//! async fn nack(&self, _id: &str, _reason: &str) -> Result<(), ErpAdapterError> {
74//! Ok(()) // Kafka auto-redelivers on next poll
75//! }
76//! }
77//! ```
78//!
79//! ## Reference implementations
80//!
81//! | Type | Feature | Use case |
82//! |------|---------|---------|
83//! | `NoopErpAdapter` | `testing` | Unit tests, CI |
84//! | [`LogErpAdapter`] | — | Structured log output; starting point for new integrations |
85//! | `NoopErpCommandSource` | `testing` | No-op inbound source for tests |
86//!
87//! For the production `WebhookErpAdapter` and `POST /api/v1/commands` endpoint,
88//! see `makod/src/erp_adapter.rs`.
89
90use std::sync::Arc;
91
92use serde::{Deserialize, Serialize};
93use time::OffsetDateTime;
94
95use crate::erc::ErcCode;
96use crate::ids::{ConversationId, EventId, ProcessId, TenantId};
97
98// ── ErpAdapterError ───────────────────────────────────────────────────────────
99
100/// Errors produced by [`ErpAdapter`] and [`ErpCommandSource`] implementations.
101#[derive(Debug, thiserror::Error)]
102pub enum ErpAdapterError {
103 /// The ERP response payload could not be deserialised or is semantically
104 /// invalid.
105 #[error("ERP payload error: {0}")]
106 Payload(String),
107
108 /// A transient transport error (network timeout, HTTP 5xx, broker
109 /// disconnect). The delivery worker will retry with exponential backoff.
110 #[error("ERP transport error: {0}")]
111 Transport(String),
112
113 /// A permanent, non-retryable error (e.g. invalid configuration,
114 /// authentication failure). The delivery worker will dead-letter the
115 /// message.
116 #[error("ERP permanent error: {0}")]
117 Permanent(String),
118}
119
120impl ErpAdapterError {
121 /// Construct a [`Payload`](ErpAdapterError::Payload) variant.
122 pub fn payload(e: impl std::fmt::Display) -> Self {
123 Self::Payload(e.to_string())
124 }
125
126 /// Construct a [`Transport`](ErpAdapterError::Transport) variant.
127 pub fn transport(e: impl std::fmt::Display) -> Self {
128 Self::Transport(e.to_string())
129 }
130
131 /// Construct a [`Permanent`](ErpAdapterError::Permanent) variant.
132 pub fn permanent(e: impl std::fmt::Display) -> Self {
133 Self::Permanent(e.to_string())
134 }
135
136 /// Returns `true` for transient errors that warrant a retry.
137 #[must_use]
138 pub fn is_retryable(&self) -> bool {
139 matches!(self, Self::Transport(_))
140 }
141}
142
143// ── ErpEventType ─────────────────────────────────────────────────────────────
144
145/// Semantic classification of an outbound ERP process event.
146///
147/// The ERP uses this to decide which action to take — update an order status,
148/// trigger a billing run, open a complaint ticket, etc.
149#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
150#[serde(rename_all = "snake_case")]
151pub enum ErpEventType {
152 /// A new MaKo process was spawned (e.g. inbound UTILMD received).
153 ProcessInitiated,
154 /// The counterparty sent an APERAK accepting our UTILMD.
155 AperakAccepted,
156 /// The counterparty sent an APERAK rejecting our UTILMD.
157 ///
158 /// `erc_code` is `Some` when the APERAK carried a structured ERC segment
159 /// (BDEW APERAK AHB 1.0 §2.2), and `None` when the counterparty sent none.
160 AperakRejected {
161 /// Structured BDEW ERC error code from the APERAK ERC segment.
162 ///
163 /// Use [`crate::erc::recommended_action`] to derive the
164 /// recommended automated ERP response.
165 #[serde(skip_serializing_if = "Option::is_none")]
166 erc_code: Option<ErcCode>,
167 },
168 /// No APERAK received within the regulatory SLA window (deadline expired).
169 AperakTimeout,
170 /// A CONTRL syntax acknowledgement was received.
171 ContrlReceived,
172 /// The process reached its terminal success state
173 /// (e.g. Lieferbeginn/Lieferende confirmed).
174 ProcessCompleted,
175 /// A MaLo identification request was successfully resolved: the MaLo was
176 /// found and the positive callback was delivered to the requesting LF.
177 ///
178 /// The `payload` field of the associated [`ErpEvent`] carries a BO4E
179 /// `Marktlokation` JSON object with the resolved MaLo data.
180 MaloIdentified,
181 /// The process failed permanently (regulatory timeout, data error, …).
182 ProcessFailed {
183 /// Human-readable failure description.
184 reason: Box<str>,
185 },
186 /// A WiM Steuerungsauftrag (PID 55168) dispatch was positively confirmed by
187 /// the MSB (`EndantwortPositiv`). Triggers downstream VPP settlement billing
188 /// in `billingd` via `POST /api/v1/webhooks/vpp-dispatch`.
189 ///
190 /// Only emitted for `Konfiguration` (load-reduction) commands — not for
191 /// `InitialZustand` (reset) commands, which restore normal operation.
192 ///
193 /// The CE `data` payload carries:
194 /// `tx_id`, `location_id`, `location_type`, `execution_time_from`,
195 /// `execution_time_until`, `max_power_kw`, `command_type`, `sender_mp_id`,
196 /// `produkt_code`.
197 VppDispatchConfirmed,
198 /// The KoV §6.4 final-allocation window closed with no binding final ALOCAT
199 /// on file, so the gas day's imbalance cannot be settled.
200 ///
201 /// Raised from the `gabi-gas-allocation` deadline. The obligation is the
202 /// FNB's/MGV's, not ours — the operator's action is to open a Clearingfall,
203 /// which is why this leaves the platform as an event rather than a message.
204 ///
205 /// The CE `data` payload carries `gas_day`, `deadline_label` and
206 /// `sender_eic` / `receiver_eic` of the last ALOCAT recorded for the stream.
207 GabiFinalAllocationOverdue,
208 /// The LFA answered the NB's Anfrage zur Beendigung der Zuordnung (55011 /
209 /// 55012), or its 09:00 window lapsed unanswered — „gilt dies als
210 /// Bestätigung nach Fall a)".
211 ///
212 /// Consumed by `processd`, which resumes the **Anmeldung** decision on it:
213 /// `E_0623` Prüfschritte 30–50 read the answer, and a Widerspruch that is
214 /// not `A30` refuses the Anmeldung with `A50`.
215 AbmeldeanfrageBeantwortet,
216}
217
218impl ErpEventType {
219 /// Short label for structured logging and metrics.
220 #[must_use]
221 pub fn label(&self) -> &'static str {
222 match self {
223 Self::ProcessInitiated => "process_initiated",
224 Self::AperakAccepted => "aperak_accepted",
225 Self::AperakRejected { .. } => "aperak_rejected",
226 Self::AperakTimeout => "aperak_timeout",
227 Self::ContrlReceived => "contrl_received",
228 Self::ProcessCompleted => "process_completed",
229 Self::MaloIdentified => "malo_identified",
230 Self::ProcessFailed { .. } => "process_failed",
231 Self::VppDispatchConfirmed => "vpp_dispatch_confirmed",
232 Self::GabiFinalAllocationOverdue => "gabi_final_allocation_overdue",
233 Self::AbmeldeanfrageBeantwortet => "abmeldeanfrage_beantwortet",
234 }
235 }
236
237 /// CloudEvents 1.0 `type` attribute for this event.
238 ///
239 /// Follows the reverse-DNS prefix convention (`de.mako.<domain>.<action>`).
240 /// Used by the `WebhookErpAdapter` to populate the `type` field of the
241 /// CloudEvents envelope.
242 #[must_use]
243 pub fn cloud_event_type(&self) -> &'static str {
244 match self {
245 Self::ProcessInitiated => mako_events::mako::PROCESS_INITIATED,
246 Self::AperakAccepted => mako_events::mako::APERAK_ACCEPTED,
247 Self::AperakRejected { .. } => mako_events::mako::APERAK_REJECTED,
248 Self::AperakTimeout => mako_events::mako::APERAK_TIMEOUT,
249 Self::ContrlReceived => mako_events::mako::CONTRL_RECEIVED,
250 Self::ProcessCompleted => mako_events::mako::PROCESS_COMPLETED,
251 Self::MaloIdentified => mako_events::mako::MALO_IDENTIFIED,
252 Self::ProcessFailed { .. } => mako_events::mako::PROCESS_FAILED,
253 Self::VppDispatchConfirmed => mako_events::vpp::DISPATCH_CONFIRMED,
254 Self::GabiFinalAllocationOverdue => mako_events::gabi::ALOCAT_MISSING,
255 Self::AbmeldeanfrageBeantwortet => mako_events::mako::ABMELDEANFRAGE_BEANTWORTET,
256 }
257 }
258}
259
260// ── ErpEvent ──────────────────────────────────────────────────────────────────
261
262/// A structured process event delivered from `mako-engine` to the ERP.
263///
264/// The payload is always a **BO4E-typed JSON object** — the ERP adapter never
265/// receives raw EDIFACT bytes or EDIFACT format-version identifiers.
266///
267/// On the wire (via `WebhookErpAdapter`) this struct is serialised as a
268/// **[CloudEvents 1.0](https://cloudevents.io) structured-mode JSON** envelope
269/// with `Content-Type: application/cloudevents+json`. The BO4E payload lives
270/// in the CloudEvents `data` field; `payload_schema` maps to `dataschema`;
271/// `event_type` maps to the `type` attribute via [`ErpEventType::cloud_event_type`].
272///
273/// ## Idempotency
274///
275/// `idempotency_key` maps to the CloudEvents `id` attribute and is also sent
276/// as `X-Idempotency-Key` for ERP middleware that keys on headers. The ERP
277/// **must** persist this key and return `HTTP 200 OK` for duplicate deliveries.
278#[derive(Debug, Clone, Serialize, Deserialize)]
279pub struct ErpEvent {
280 /// Stable dedup key — store in the ERP to reject duplicate deliveries.
281 ///
282 /// Derived from the outbox `message_id`; stable across retries.
283 pub idempotency_key: String,
284
285 /// Semantic classification of this event.
286 pub event_type: ErpEventType,
287
288 /// The mako process that generated this event.
289 pub process_id: ProcessId,
290
291 /// Tenant (operator GLN) that owns this process.
292 pub tenant_id: TenantId,
293
294 /// BDEW business conversation identifier.
295 pub conversation_id: ConversationId,
296
297 /// The mako domain event that directly caused this ERP notification.
298 pub causation_id: EventId,
299
300 /// Prüfidentifikator of the process.
301 pub pid: u32,
302
303 /// BO4E JSON Schema URL that validates [`payload`](ErpEvent::payload).
304 ///
305 /// Examples:
306 /// - `"https://raw.githubusercontent.com/BO4E/BO4E-Schemas/v202607.1.0/src/bo4e_schemas/bo/Marktlokation.json"`
307 /// - `"https://raw.githubusercontent.com/BO4E/BO4E-Schemas/v202607.1.0/src/bo4e_schemas/bo/Messlokation.json"`
308 ///
309 /// `None` for events where no primary BO4E object is applicable
310 /// (e.g. `ContrlReceived`).
311 #[serde(skip_serializing_if = "Option::is_none")]
312 pub payload_schema: Option<String>,
313
314 /// BO4E-typed payload.
315 ///
316 /// Deserialise using the ERP's own BO4E library. Raw EDIFACT structures
317 /// are never exposed here. `null` when no payload is applicable.
318 pub payload: serde_json::Value,
319
320 /// Wall-clock time when the domain event was persisted.
321 pub occurred_at: OffsetDateTime,
322
323 /// W3C `traceparent` propagated from the request that caused this event.
324 ///
325 /// Copied from `OutboxMessage::trace_context`; injected into the webhook
326 /// delivery as the `traceparent` HTTP header and the CloudEvents
327 /// `traceparent` extension attribute (CloudEvents distributed-tracing
328 /// extension), so the ERP joins the same trace as the inbound transport.
329 #[serde(default, skip_serializing_if = "Option::is_none")]
330 pub trace_context: Option<Box<str>>,
331
332 /// Workflow family name that produced this event (e.g. `"gpke-sperrung"`).
333 ///
334 /// Carried through from `OutboxMessage::workflow_name`. Emitted as the
335 /// `makoworkflow` CloudEvents extension attribute by `WebhookErpAdapter`.
336 /// `marktd` maps this to `marktrole` for role-scoped ERP subscriber fan-out.
337 pub workflow_name: Box<str>,
338}
339
340// ── ErpAdapter trait ──────────────────────────────────────────────────────────
341
342/// Outbound notification sink — `mako-engine` calls this when a process event
343/// should be reported to the ERP.
344///
345/// The payload is always a BO4E-typed JSON object; the adapter never receives
346/// raw EDIFACT bytes or format-version identifiers.
347///
348/// ## Contract
349///
350/// - Must be **idempotent** on `event.idempotency_key`. Called twice with the
351/// same key must succeed without double-posting.
352/// - Return [`ErpAdapterError::Transport`] for transient failures — the caller
353/// will retry with exponential backoff.
354/// - Return [`ErpAdapterError::Permanent`] for non-retryable failures — the
355/// caller will dead-letter the event.
356#[allow(async_fn_in_trait)]
357pub trait ErpAdapter: Send + Sync + 'static {
358 /// Deliver `event` to the ERP.
359 async fn notify(&self, event: ErpEvent) -> Result<(), ErpAdapterError>;
360}
361
362/// Blanket `Arc` implementation so `ErpAdapter` can be shared across tasks.
363impl<T: ErpAdapter> ErpAdapter for Arc<T> {
364 async fn notify(&self, event: ErpEvent) -> Result<(), ErpAdapterError> {
365 (**self).notify(event).await
366 }
367}
368
369// ── InboundErpCommand ─────────────────────────────────────────────────────────
370
371/// A BO4E business object received from the ERP, intended to trigger a mako
372/// process.
373///
374/// `mako-engine` maps the BO4E payload to an internal `Command` via the
375/// domain crate's command mapper.
376#[derive(Debug, Clone, Serialize, Deserialize)]
377pub struct InboundErpCommand {
378 /// Stable dedup key — forwarded to [`InboxStore::accept`].
379 ///
380 /// The ERP must supply a stable, unique identifier per command so that
381 /// retransmissions do not double-execute the workflow.
382 ///
383 /// [`InboxStore::accept`]: crate::inbox::InboxStore::accept
384 pub idempotency_key: String,
385
386 /// Tenant (operator GLN) that owns the target process.
387 pub tenant_id: TenantId,
388
389 /// BO4E JSON Schema URL — identifies the object type without inspecting
390 /// `payload`.
391 ///
392 /// Example:
393 /// `"https://raw.githubusercontent.com/BO4E/BO4E-Schemas/v202607.1.0/src/bo4e_schemas/bo/Vertrag.json"`
394 pub payload_schema: String,
395
396 /// BO4E-typed JSON payload. `mako-engine` maps this to an internal
397 /// `Command` via the registered domain command mapper.
398 pub payload: serde_json::Value,
399}
400
401// ── ErpCommandSource trait ────────────────────────────────────────────────────
402
403/// Inbound command source — `mako-engine` polls this for new BO4E objects
404/// from the ERP.
405///
406/// Implement this for broker-based inbound flows (Kafka consumer, SFTP poll,
407/// database change feed, …) to make the entire integration fully event-driven
408/// — no synchronous REST round-trip required.
409///
410/// ## Contract
411///
412/// - [`next`](ErpCommandSource::next) must be **non-blocking** when idle —
413/// return `Ok(None)` immediately when no command is available.
414/// - [`ack`](ErpCommandSource::ack) must suppress re-delivery of `id` after
415/// a successful ack (idempotent).
416/// - [`nack`](ErpCommandSource::nack) should allow re-delivery of `id` after
417/// an appropriate backoff.
418#[allow(async_fn_in_trait)]
419pub trait ErpCommandSource: Send + Sync + 'static {
420 /// Return the next pending BO4E command, or `None` when the source is idle.
421 async fn next(&self) -> Result<Option<InboundErpCommand>, ErpAdapterError>;
422
423 /// Acknowledge successful processing of `id`.
424 ///
425 /// After a successful ack the source must not re-deliver `id`.
426 async fn ack(&self, id: &str) -> Result<(), ErpAdapterError>;
427
428 /// Negative-acknowledge — allow re-delivery of `id` after backoff.
429 async fn nack(&self, id: &str, reason: &str) -> Result<(), ErpAdapterError>;
430}
431
432/// Blanket `Arc` implementation so `ErpCommandSource` can be shared across tasks.
433impl<S: ErpCommandSource> ErpCommandSource for Arc<S> {
434 async fn next(&self) -> Result<Option<InboundErpCommand>, ErpAdapterError> {
435 (**self).next().await
436 }
437 async fn ack(&self, id: &str) -> Result<(), ErpAdapterError> {
438 (**self).ack(id).await
439 }
440 async fn nack(&self, id: &str, reason: &str) -> Result<(), ErpAdapterError> {
441 (**self).nack(id, reason).await
442 }
443}
444
445// ── NoopErpAdapter ────────────────────────────────────────────────────────────
446
447/// An [`ErpAdapter`] that succeeds immediately without notifying anything.
448///
449/// Use in unit tests and CI where no real ERP endpoint is available.
450#[cfg(feature = "testing")]
451#[derive(Debug, Clone, Default)]
452pub struct NoopErpAdapter;
453
454#[cfg(feature = "testing")]
455impl ErpAdapter for NoopErpAdapter {
456 async fn notify(&self, _event: ErpEvent) -> Result<(), ErpAdapterError> {
457 Ok(())
458 }
459}
460
461// ── LogErpAdapter ─────────────────────────────────────────────────────────────
462
463/// An [`ErpAdapter`] that logs every event at `info` level without delivering
464/// it.
465///
466/// Useful as a development starting point — replace it with your concrete ERP
467/// adapter in production.
468#[derive(Debug, Clone, Default)]
469pub struct LogErpAdapter;
470
471impl ErpAdapter for LogErpAdapter {
472 async fn notify(&self, event: ErpEvent) -> Result<(), ErpAdapterError> {
473 tracing::info!(
474 idempotency_key = %event.idempotency_key,
475 event_type = event.event_type.label(),
476 process_id = %event.process_id,
477 tenant_id = %event.tenant_id,
478 pid = event.pid,
479 "ErpAdapter: event logged (no delivery configured)",
480 );
481 Ok(())
482 }
483}
484
485// ── NoopErpCommandSource ──────────────────────────────────────────────────────
486
487/// An [`ErpCommandSource`] that is always idle (returns `Ok(None)`).
488///
489/// Use in tests where no inbound ERP command flow is needed.
490#[cfg(feature = "testing")]
491#[derive(Debug, Clone, Default)]
492pub struct NoopErpCommandSource;
493
494#[cfg(feature = "testing")]
495impl ErpCommandSource for NoopErpCommandSource {
496 async fn next(&self) -> Result<Option<InboundErpCommand>, ErpAdapterError> {
497 Ok(None)
498 }
499 async fn ack(&self, _id: &str) -> Result<(), ErpAdapterError> {
500 Ok(())
501 }
502 async fn nack(&self, _id: &str, _reason: &str) -> Result<(), ErpAdapterError> {
503 Ok(())
504 }
505}
506
507// ── ErpAdapterTestHarness ─────────────────────────────────────────────────────
508
509/// A recording [`ErpAdapter`] for use in tests.
510///
511/// Records every [`ErpEvent`] delivered via [`notify`](ErpAdapter::notify) so
512/// tests can assert on event types, ordering, and BO4E payload shapes.
513///
514/// ```rust,ignore
515/// let harness = ErpAdapterTestHarness::new();
516/// my_workflow.run_with_adapter(harness.adapter()).await?;
517///
518/// let events = harness.events();
519/// assert_eq!(events[0].event_type, ErpEventType::ProcessInitiated);
520/// assert_eq!(events[1].event_type, ErpEventType::AperakAccepted);
521/// ```
522#[cfg(feature = "testing")]
523#[derive(Debug, Clone, Default)]
524pub struct ErpAdapterTestHarness {
525 events: Arc<tokio::sync::Mutex<Vec<ErpEvent>>>,
526}
527
528#[cfg(feature = "testing")]
529impl ErpAdapterTestHarness {
530 /// Create a new empty harness.
531 #[must_use]
532 pub fn new() -> Self {
533 Self::default()
534 }
535
536 /// Return a snapshot of all recorded events in delivery order.
537 pub async fn events(&self) -> Vec<ErpEvent> {
538 self.events.lock().await.clone()
539 }
540
541 /// Drain all recorded events, resetting the harness.
542 pub async fn drain(&self) -> Vec<ErpEvent> {
543 std::mem::take(&mut *self.events.lock().await)
544 }
545}
546
547#[cfg(feature = "testing")]
548impl ErpAdapter for ErpAdapterTestHarness {
549 async fn notify(&self, event: ErpEvent) -> Result<(), ErpAdapterError> {
550 self.events.lock().await.push(event);
551 Ok(())
552 }
553}
554
555// ── ErpCommandSourceTestHarness ───────────────────────────────────────────────
556
557/// A controllable [`ErpCommandSource`] for use in tests.
558///
559/// Inject canned [`InboundErpCommand`] payloads and verify that the engine
560/// processes them correctly.
561///
562/// ```text
563/// let source = ErpCommandSourceTestHarness::new();
564/// source.inject(InboundErpCommand {
565/// idempotency_key: "order-42".into(),
566/// tenant_id: TenantId::new(),
567/// payload_schema: ".../Vertrag.json".into(),
568/// payload: serde_json::json!({ "_typ": "VERTRAG", ... }),
569/// }).await;
570///
571/// // The engine picks up the command on the next poll.
572/// ```
573#[cfg(feature = "testing")]
574#[derive(Debug, Clone, Default)]
575pub struct ErpCommandSourceTestHarness {
576 queue: Arc<tokio::sync::Mutex<std::collections::VecDeque<InboundErpCommand>>>,
577 acked: Arc<tokio::sync::Mutex<Vec<String>>>,
578 nacked: Arc<tokio::sync::Mutex<Vec<(String, String)>>>,
579}
580
581#[cfg(feature = "testing")]
582impl ErpCommandSourceTestHarness {
583 /// Create a new empty harness.
584 #[must_use]
585 pub fn new() -> Self {
586 Self::default()
587 }
588
589 /// Enqueue a command to be returned by the next [`next`](ErpCommandSource::next) call.
590 pub async fn inject(&self, cmd: InboundErpCommand) {
591 self.queue.lock().await.push_back(cmd);
592 }
593
594 /// Return all acked command IDs.
595 pub async fn acked(&self) -> Vec<String> {
596 self.acked.lock().await.clone()
597 }
598
599 /// Return all nacked `(id, reason)` pairs.
600 pub async fn nacked(&self) -> Vec<(String, String)> {
601 self.nacked.lock().await.clone()
602 }
603}
604
605#[cfg(feature = "testing")]
606impl ErpCommandSource for ErpCommandSourceTestHarness {
607 async fn next(&self) -> Result<Option<InboundErpCommand>, ErpAdapterError> {
608 Ok(self.queue.lock().await.pop_front())
609 }
610
611 async fn ack(&self, id: &str) -> Result<(), ErpAdapterError> {
612 self.acked.lock().await.push(id.to_owned());
613 Ok(())
614 }
615
616 async fn nack(&self, id: &str, reason: &str) -> Result<(), ErpAdapterError> {
617 self.nacked
618 .lock()
619 .await
620 .push((id.to_owned(), reason.to_owned()));
621 Ok(())
622 }
623}
624
625// ── BO4E schema URL constants ─────────────────────────────────────────────────
626
627/// BO4E schema URL base for the pinned snapshot.
628///
629/// Use `bo4e_schema_url!(Marktlokation)` to construct typed schema URLs at
630/// compile time.
631///
632/// **The `v` belongs here and only here.** BO4E prefixes its git *tags* with
633/// one, so a raw.githubusercontent URL needs `v202607.1.0`; the `_version`
634/// field inside a payload never has it and reads `202607.1.0`.
635/// `mako_markt::bo4e::schema_version` is the payload spelling, and
636/// `services/makod/tests/bo4e_version_guard.rs` pins the two together — this
637/// crate cannot derive the tag itself because it does not depend on rubo4e.
638pub const BO4E_V202607_BASE: &str =
639 "https://raw.githubusercontent.com/BO4E/BO4E-Schemas/v202607.1.0/src/bo4e_schemas";
640
641/// Construct a BO4E JSON Schema URL for a Business Object.
642///
643/// ```rust
644/// use mako_engine::bo4e_schema_url;
645/// assert!(bo4e_schema_url!("bo", "Marktlokation").contains("Marktlokation"));
646/// ```
647#[macro_export]
648macro_rules! bo4e_schema_url {
649 ($category:literal, $name:literal) => {
650 concat!(
651 "https://raw.githubusercontent.com/BO4E/BO4E-Schemas/v202607.1.0/src/bo4e_schemas/",
652 $category,
653 "/",
654 $name,
655 ".json",
656 )
657 };
658}
659
660/// BO4E JSON Schema URL for `Marktlokation`.
661pub const BO4E_SCHEMA_MARKTLOKATION: &str = bo4e_schema_url!("bo", "Marktlokation");
662
663/// BO4E JSON Schema URL for `Messlokation`.
664pub const BO4E_SCHEMA_MESSLOKATION: &str = bo4e_schema_url!("bo", "Messlokation");
665
666/// BO4E JSON Schema URL for `Vertrag`.
667pub const BO4E_SCHEMA_VERTRAG: &str = bo4e_schema_url!("bo", "Vertrag");
668
669/// BO4E JSON Schema URL for `Energiemenge`.
670pub const BO4E_SCHEMA_ENERGIEMENGE: &str = bo4e_schema_url!("bo", "Energiemenge");
671
672/// BO4E JSON Schema URL for `Rechnung`.
673pub const BO4E_SCHEMA_RECHNUNG: &str = bo4e_schema_url!("bo", "Rechnung");
674
675/// BO4E JSON Schema URL for `Zaehler`.
676pub const BO4E_SCHEMA_ZAEHLER: &str = bo4e_schema_url!("bo", "Zaehler");
677
678/// BO4E JSON Schema URL for `Geschaeftspartner`.
679pub const BO4E_SCHEMA_GESCHAEFTSPARTNER: &str = bo4e_schema_url!("bo", "Geschaeftspartner");