Skip to main content

entsoe_edi/
schedule.rs

1use std::collections::{HashMap, HashSet};
2use std::fmt::Write;
3
4use jiff::tz::{self, TimeZone};
5use thiserror::Error;
6use time::{Date, OffsetDateTime, UtcOffset, macros::format_description};
7
8use crate::{BilanzierungsgebietId, BilanzkreisId, EicCode, ScheduleQuantity};
9
10/// One German ESS 2.3 schedule for trades inside a single control area (A02).
11#[derive(Clone, Debug)]
12pub struct ScheduleMessage {
13    /// Sender-assigned ID shared by revisions of this schedule.
14    pub id: String,
15    /// Message revision, from 1 through 999.
16    pub revision: u16,
17    /// Nominating Bilanzkreis.
18    pub sender: BilanzkreisId,
19    /// Receiving ÜNB's party EIC (10X).
20    pub receiver: EicCode,
21    /// Receiving ÜNB's control-area EIC (10Y).
22    pub area: BilanzierungsgebietId,
23    /// Delivery day in Europe/Berlin.
24    pub day: Date,
25    /// Preparation instant, emitted in UTC to whole seconds.
26    pub created_at: OffsetDateTime,
27    /// All directional trades for this nomination in wire order.
28    pub series: Vec<TradeSeries>,
29}
30
31/// Netted physical delivery from one Bilanzkreis to another within the same area.
32#[derive(Clone, Debug)]
33pub struct TradeSeries {
34    /// Sender-assigned time series ID.
35    pub id: String,
36    /// Message revision in which the series last changed.
37    pub revision: u16,
38    /// Source Bilanzkreis, the ESS OutParty.
39    pub delivering: BilanzkreisId,
40    /// Destination Bilanzkreis, the ESS InParty.
41    pub receiving: BilanzkreisId,
42    /// Consecutive quarter-hours starting at Berlin midnight, in elapsed time order.
43    pub quantities: Vec<ScheduleQuantity>,
44}
45
46/// Reason a nomination cannot be encoded as a German ESS 2.3 schedule.
47#[derive(Debug, Error, PartialEq, Eq)]
48pub enum ScheduleError {
49    /// The shortest exact MW representation is wider than the wire field.
50    #[error("{0} kW exceeds the ESS quantity field width")]
51    QuantityTooLong(u64),
52    /// Message or series ID violates the ESS alphanumeric grammar.
53    #[error("{0} must contain 1 to 35 ASCII letters or digits")]
54    InvalidId(&'static str),
55    /// Revision lies outside the permitted range.
56    #[error("{field} must be between 1 and {maximum}, got {value}")]
57    InvalidRevision {
58        /// Offending field.
59        field: &'static str,
60        /// Highest allowed value.
61        maximum: u16,
62        /// Supplied revision.
63        value: u16,
64    },
65    /// The EIC supplied for a control area or recipient belongs to the wrong class.
66    #[error("{0}")]
67    InvalidRecipient(&'static str),
68    /// The XML time format cannot represent an instant or day boundary.
69    #[error("{0} cannot be represented in the ESS UTC format")]
70    InvalidTime(&'static str),
71    /// The interval falls outside the contiguous years qualified against the ESS core schema.
72    #[error("the delivery interval must start in UTC year 2000 through 2099")]
73    DayOutsideSchemaRange,
74    /// An A02 trade nomination requires at least one series.
75    #[error("the nomination needs at least one trade series")]
76    EmptySchedule,
77    /// The series ID appears more than once in the document.
78    #[error("duplicate series ID {0}")]
79    DuplicateId(String),
80    /// A series must connect the sender and a distinct Bilanzkreis.
81    #[error("series {0} must connect the sender and a different Bilanzkreis")]
82    InvalidParties(String),
83    /// Two series describe the same directional flow.
84    #[error("series {0} repeats a directional trade")]
85    DuplicateTrade(String),
86    /// Series coverage differs from the length of the delivery day.
87    #[error("series {id} needs {expected} quarter-hours, got {actual}")]
88    IntervalCount {
89        /// Sender-assigned series ID.
90        id: String,
91        /// Length of the Berlin delivery day in quarter-hours.
92        expected: usize,
93        /// Number of supplied quantities.
94        actual: usize,
95    },
96    /// A quarter-hour contains delivery in both directions for a pair.
97    #[error("series {id} and its reverse both deliver at position {position}")]
98    OverlappingFlows {
99        /// Series ID of the second direction.
100        id: String,
101        /// One-based quarter-hour position.
102        position: usize,
103    },
104}
105
106/// UTC boundaries of a Berlin delivery day whose UTC start year is 2000–2099, with an exclusive end.
107#[must_use = "the delivery day must have representable ESS boundaries"]
108pub fn delivery_window(day: Date) -> Result<std::ops::Range<OffsetDateTime>, ScheduleError> {
109    static BERLIN: TimeZone = tz::get!("Europe/Berlin");
110    let invalid = || ScheduleError::InvalidTime("delivery day");
111    let midnight = |date: Date| {
112        let year = date.year().try_into().map_err(|_| invalid())?;
113        let local = jiff::civil::Date::new(year, date.month() as i8, date.day() as i8)
114            .map_err(|_| invalid())?;
115        let time = BERLIN
116            .to_ambiguous_timestamp(local.at(0, 0, 0, 0))
117            .unambiguous()
118            .map_err(|_| invalid())?;
119        let utc = OffsetDateTime::from_unix_timestamp(time.as_second()).map_err(|_| invalid())?;
120        if !(1..=9999).contains(&utc.year()) || utc.second() != 0 {
121            return Err(invalid());
122        }
123        Ok(utc)
124    };
125    let start = midnight(day)?;
126    // The published ESS core TimeIntervalType limits 31-day start months to 20xx.
127    // Qualify one continuous range so adjacent months follow the same contract.
128    if !(2000..=2099).contains(&start.year()) {
129        return Err(ScheduleError::DayOutsideSchemaRange);
130    }
131    let end = midnight(day.next_day().ok_or_else(invalid)?)?;
132    let seconds = (end - start).whole_seconds();
133    if !matches!(seconds, 82_800 | 86_400 | 90_000) {
134        return Err(invalid());
135    }
136    Ok(start..end)
137}
138
139impl ScheduleMessage {
140    /// Encodes a validated snapshot. A refusal returns no partial XML.
141    #[must_use = "the schedule must pass the ESS profile"]
142    pub fn to_xml(&self) -> Result<String, ScheduleError> {
143        let window = delivery_window(self.day)?;
144        validate_id("message ID", &self.id)?;
145        validate_revision("message revision", self.revision, 999)?;
146        if !self.receiver.starts_with("10X") {
147            return Err(ScheduleError::InvalidRecipient(
148                "receiver must be a 10X ÜNB EIC",
149            ));
150        }
151        if !self.area.starts_with("10Y") {
152            return Err(ScheduleError::InvalidRecipient(
153                "area must be a 10Y control-area EIC",
154            ));
155        }
156        self.validate_series(((window.end - window.start).whole_minutes() / 15) as usize)?;
157        let minute = format_description!("[year]-[month]-[day]T[hour]:[minute]Z");
158        let format_boundary = |instant: OffsetDateTime| {
159            instant
160                .format(minute)
161                .map_err(|_| ScheduleError::InvalidTime("delivery day"))
162        };
163        let interval = format!(
164            "{}/{}",
165            format_boundary(window.start)?,
166            format_boundary(window.end)?
167        );
168        let invalid = || ScheduleError::InvalidTime("message timestamp");
169        let utc = self
170            .created_at
171            .checked_to_offset(UtcOffset::UTC)
172            .ok_or_else(invalid)?;
173        if !(1..=9999).contains(&utc.year()) {
174            return Err(invalid());
175        }
176        let created_at = utc
177            .format(format_description!(
178                "[year]-[month]-[day]T[hour]:[minute]:[second]Z"
179            ))
180            .map_err(|_| invalid())?;
181
182        // Every interpolated attribute is a checked identifier, a number, or a generated UTC time.
183        let mut xml = format!(
184            r#"<?xml version="1.0" encoding="UTF-8"?>
185<ScheduleMessage DtdVersion="2" DtdRelease="3">
186<MessageIdentification v="{}"/><MessageVersion v="{}"/>
187<MessageType v="A01"/><ProcessType v="A17"/><ScheduleClassificationType v="A01"/>
188<SenderIdentification v="{}" codingScheme="A01"/><SenderRole v="A08"/>
189<ReceiverIdentification v="{}" codingScheme="A01"/><ReceiverRole v="A04"/>
190<MessageDateTime v="{created_at}"/><ScheduleTimeInterval v="{}"/>
191"#,
192            self.id, self.revision, self.sender, self.receiver, interval
193        );
194        for series in &self.series {
195            series.write_xml(&mut xml, &self.area, &interval);
196        }
197        xml.push_str("</ScheduleMessage>\n");
198        Ok(xml)
199    }
200
201    fn validate_series(&self, positions: usize) -> Result<(), ScheduleError> {
202        if self.series.is_empty() {
203            return Err(ScheduleError::EmptySchedule);
204        }
205        let mut ids = HashSet::new();
206        let mut trades = HashMap::new();
207        for series in &self.series {
208            validate_id("series ID", &series.id)?;
209            validate_revision("series revision", series.revision, self.revision)?;
210            if !ids.insert(&series.id) {
211                return Err(ScheduleError::DuplicateId(series.id.clone()));
212            }
213            if series.delivering == series.receiving
214                || (series.delivering != self.sender && series.receiving != self.sender)
215            {
216                return Err(ScheduleError::InvalidParties(series.id.clone()));
217            }
218            if series.quantities.len() != positions {
219                return Err(ScheduleError::IntervalCount {
220                    id: series.id.clone(),
221                    expected: positions,
222                    actual: series.quantities.len(),
223                });
224            }
225            if trades
226                .insert((&series.delivering, &series.receiving), &series.quantities)
227                .is_some()
228            {
229                return Err(ScheduleError::DuplicateTrade(series.id.clone()));
230            }
231            if let Some(reverse) = trades.get(&(&series.receiving, &series.delivering))
232                && let Some(index) = series
233                    .quantities
234                    .iter()
235                    .zip(*reverse)
236                    .position(|(a, b)| a.0 > 0 && b.0 > 0)
237            {
238                return Err(ScheduleError::OverlappingFlows {
239                    id: series.id.clone(),
240                    position: index + 1,
241                });
242            }
243        }
244        Ok(())
245    }
246}
247
248fn validate_id(field: &'static str, value: &str) -> Result<(), ScheduleError> {
249    if !(1..=35).contains(&value.len()) || !value.bytes().all(|b| b.is_ascii_alphanumeric()) {
250        return Err(ScheduleError::InvalidId(field));
251    }
252    Ok(())
253}
254
255fn validate_revision(field: &'static str, value: u16, maximum: u16) -> Result<(), ScheduleError> {
256    if !(1..=maximum).contains(&value) {
257        return Err(ScheduleError::InvalidRevision {
258            field,
259            maximum,
260            value,
261        });
262    }
263    Ok(())
264}
265
266impl TradeSeries {
267    fn write_xml(&self, xml: &mut String, area: &BilanzierungsgebietId, interval: &str) {
268        write!(
269            xml,
270            r#"<ScheduleTimeSeries>
271<SendersTimeSeriesIdentification v="{}"/><SendersTimeSeriesVersion v="{}"/>
272<BusinessType v="A02"/><Product v="8716867000016"/><ObjectAggregation v="A01"/>
273<InArea v="{area}" codingScheme="A01"/><OutArea v="{area}" codingScheme="A01"/>
274<InParty v="{}" codingScheme="A01"/><OutParty v="{}" codingScheme="A01"/>
275<MeasurementUnit v="MAW"/><Period><TimeInterval v="{interval}"/><Resolution v="PT15M"/>
276"#,
277            self.id, self.revision, self.receiving, self.delivering
278        )
279        .expect("writing to String is infallible");
280        for (index, qty) in self.quantities.iter().enumerate() {
281            writeln!(
282                xml,
283                r#"<Interval><Pos v="{}"/><Qty v="{qty}"/></Interval>"#,
284                index + 1
285            )
286            .expect("writing to String is infallible");
287        }
288        xml.push_str("</Period></ScheduleTimeSeries>\n");
289    }
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295    use time::macros::{date, datetime};
296
297    fn schedule() -> ScheduleMessage {
298        let sender = BilanzkreisId::new("11XSUEDWESTSTRO8").unwrap();
299        ScheduleMessage {
300            id: "Msg".into(),
301            revision: 2,
302            sender: sender.clone(),
303            receiver: "10XDE-EON-NETZ-C".parse().unwrap(),
304            area: "10YDE-EON------1".parse().unwrap(),
305            day: date!(2026 - 03 - 29),
306            created_at: datetime!(2026-03-28 11:22 UTC),
307            series: vec![TradeSeries {
308                id: "Sale".into(),
309                revision: 1,
310                delivering: sender,
311                receiving: "11XENERGIE2----H".parse().unwrap(),
312                quantities: vec![ScheduleQuantity::from_kw(1).unwrap(); 92],
313            }],
314        }
315    }
316
317    #[test]
318    fn ids_and_revisions_must_fit_the_wire_fields() {
319        let mut doc = schedule();
320        for invalid in ["", "one two", "A&B", "A\"B", "ä", &"Z".repeat(36)] {
321            doc.id = invalid.into();
322            assert_eq!(doc.to_xml(), Err(ScheduleError::InvalidId("message ID")));
323        }
324        doc.id = "A".repeat(35);
325        doc.series[0].id = "bad/id".into();
326        assert_eq!(doc.to_xml(), Err(ScheduleError::InvalidId("series ID")));
327        doc.series[0].id = "a9".repeat(17);
328        for (message, series) in [(0, 1), (1000, 1), (2, 0), (2, 3)] {
329            doc.revision = message;
330            doc.series[0].revision = series;
331            assert!(matches!(
332                doc.to_xml(),
333                Err(ScheduleError::InvalidRevision { .. })
334            ));
335        }
336        doc.revision = 999;
337        doc.series[0].revision = 999;
338        assert!(doc.to_xml().is_ok());
339    }
340
341    #[test]
342    fn header_and_trade_parties_have_distinct_roles() {
343        let mut doc = schedule();
344        doc.receiver = "10YDE-EON------1".parse().unwrap();
345        assert!(matches!(
346            doc.to_xml(),
347            Err(ScheduleError::InvalidRecipient(_))
348        ));
349        doc = schedule();
350        doc.area = "11YN-0000-0001-Q".parse().unwrap();
351        assert!(matches!(
352            doc.to_xml(),
353            Err(ScheduleError::InvalidRecipient(_))
354        ));
355        doc = schedule();
356        doc.series[0].receiving = doc.sender.clone();
357        assert!(matches!(
358            doc.to_xml(),
359            Err(ScheduleError::InvalidParties(_))
360        ));
361        doc = schedule();
362        doc.sender = "11XENAGISME----J".parse().unwrap();
363        assert!(matches!(
364            doc.to_xml(),
365            Err(ScheduleError::InvalidParties(_))
366        ));
367    }
368
369    #[test]
370    fn delivery_days_stay_inside_the_qualified_schema_range() {
371        assert_eq!(
372            delivery_window(date!(2000 - 01 - 01)),
373            Err(ScheduleError::DayOutsideSchemaRange)
374        );
375        for day in [date!(2000 - 01 - 02), date!(2100 - 01 - 01)] {
376            let window = delivery_window(day).unwrap();
377            assert_eq!((window.end - window.start).whole_hours(), 24);
378        }
379        assert_eq!(
380            delivery_window(date!(2100 - 01 - 02)),
381            Err(ScheduleError::DayOutsideSchemaRange)
382        );
383    }
384
385    #[test]
386    fn complete_day_is_required_even_for_an_explicit_zero() {
387        let mut doc = schedule();
388        doc.series[0].quantities.pop();
389        assert!(matches!(
390            doc.to_xml(),
391            Err(ScheduleError::IntervalCount {
392                expected: 92,
393                actual: 91,
394                ..
395            })
396        ));
397        doc.series[0].quantities.extend([ScheduleQuantity(0); 2]);
398        assert!(matches!(
399            doc.to_xml(),
400            Err(ScheduleError::IntervalCount {
401                expected: 92,
402                actual: 93,
403                ..
404            })
405        ));
406        doc.series.clear();
407        assert_eq!(doc.to_xml(), Err(ScheduleError::EmptySchedule));
408        assert!(delivery_window(Date::MAX).is_err());
409        assert!(delivery_window(Date::MIN).is_err());
410    }
411
412    #[test]
413    fn a_bilateral_trade_has_at_most_one_flow_per_position() {
414        let mut doc = schedule();
415        doc.series.push(doc.series[0].clone());
416        assert!(matches!(doc.to_xml(), Err(ScheduleError::DuplicateId(_))));
417        doc.series[1].id = "Return".into();
418        assert!(matches!(
419            doc.to_xml(),
420            Err(ScheduleError::DuplicateTrade(_))
421        ));
422        let reverse = &mut doc.series[1];
423        std::mem::swap(&mut reverse.receiving, &mut reverse.delivering);
424        reverse.quantities.fill(ScheduleQuantity(0));
425        reverse.quantities[91] = ScheduleQuantity(1);
426        assert!(matches!(
427            doc.to_xml(),
428            Err(ScheduleError::OverlappingFlows { position: 92, .. })
429        ));
430        doc.series[0].quantities[91] = ScheduleQuantity(0);
431        let xml = doc.to_xml().unwrap();
432        assert_eq!(xml.matches("<ScheduleTimeSeries>").count(), 2);
433        assert_eq!(doc.to_xml().unwrap(), xml);
434    }
435}