use std::collections::{HashMap, HashSet};
use std::fmt::Write;
use jiff::tz::{self, TimeZone};
use thiserror::Error;
use time::{Date, OffsetDateTime, UtcOffset, macros::format_description};
use crate::{BilanzierungsgebietId, BilanzkreisId, EicCode, ScheduleQuantity};
#[derive(Clone, Debug)]
pub struct ScheduleMessage {
pub id: String,
pub revision: u16,
pub sender: BilanzkreisId,
pub receiver: EicCode,
pub area: BilanzierungsgebietId,
pub day: Date,
pub created_at: OffsetDateTime,
pub series: Vec<TradeSeries>,
}
#[derive(Clone, Debug)]
pub struct TradeSeries {
pub id: String,
pub revision: u16,
pub delivering: BilanzkreisId,
pub receiving: BilanzkreisId,
pub quantities: Vec<ScheduleQuantity>,
}
#[derive(Debug, Error, PartialEq, Eq)]
pub enum ScheduleError {
#[error("{0} kW exceeds the ESS quantity field width")]
QuantityTooLong(u64),
#[error("{0} must contain 1 to 35 ASCII letters or digits")]
InvalidId(&'static str),
#[error("{field} must be between 1 and {maximum}, got {value}")]
InvalidRevision {
field: &'static str,
maximum: u16,
value: u16,
},
#[error("{0}")]
InvalidRecipient(&'static str),
#[error("{0} cannot be represented in the ESS UTC format")]
InvalidTime(&'static str),
#[error("the delivery interval must start in UTC year 2000 through 2099")]
DayOutsideSchemaRange,
#[error("the nomination needs at least one trade series")]
EmptySchedule,
#[error("duplicate series ID {0}")]
DuplicateId(String),
#[error("series {0} must connect the sender and a different Bilanzkreis")]
InvalidParties(String),
#[error("series {0} repeats a directional trade")]
DuplicateTrade(String),
#[error("series {id} needs {expected} quarter-hours, got {actual}")]
IntervalCount {
id: String,
expected: usize,
actual: usize,
},
#[error("series {id} and its reverse both deliver at position {position}")]
OverlappingFlows {
id: String,
position: usize,
},
}
#[must_use = "the delivery day must have representable ESS boundaries"]
pub fn delivery_window(day: Date) -> Result<std::ops::Range<OffsetDateTime>, ScheduleError> {
static BERLIN: TimeZone = tz::get!("Europe/Berlin");
let invalid = || ScheduleError::InvalidTime("delivery day");
let midnight = |date: Date| {
let year = date.year().try_into().map_err(|_| invalid())?;
let local = jiff::civil::Date::new(year, date.month() as i8, date.day() as i8)
.map_err(|_| invalid())?;
let time = BERLIN
.to_ambiguous_timestamp(local.at(0, 0, 0, 0))
.unambiguous()
.map_err(|_| invalid())?;
let utc = OffsetDateTime::from_unix_timestamp(time.as_second()).map_err(|_| invalid())?;
if !(1..=9999).contains(&utc.year()) || utc.second() != 0 {
return Err(invalid());
}
Ok(utc)
};
let start = midnight(day)?;
if !(2000..=2099).contains(&start.year()) {
return Err(ScheduleError::DayOutsideSchemaRange);
}
let end = midnight(day.next_day().ok_or_else(invalid)?)?;
let seconds = (end - start).whole_seconds();
if !matches!(seconds, 82_800 | 86_400 | 90_000) {
return Err(invalid());
}
Ok(start..end)
}
impl ScheduleMessage {
#[must_use = "the schedule must pass the ESS profile"]
pub fn to_xml(&self) -> Result<String, ScheduleError> {
let window = delivery_window(self.day)?;
validate_id("message ID", &self.id)?;
validate_revision("message revision", self.revision, 999)?;
if !self.receiver.starts_with("10X") {
return Err(ScheduleError::InvalidRecipient(
"receiver must be a 10X ÜNB EIC",
));
}
if !self.area.starts_with("10Y") {
return Err(ScheduleError::InvalidRecipient(
"area must be a 10Y control-area EIC",
));
}
self.validate_series(((window.end - window.start).whole_minutes() / 15) as usize)?;
let minute = format_description!("[year]-[month]-[day]T[hour]:[minute]Z");
let format_boundary = |instant: OffsetDateTime| {
instant
.format(minute)
.map_err(|_| ScheduleError::InvalidTime("delivery day"))
};
let interval = format!(
"{}/{}",
format_boundary(window.start)?,
format_boundary(window.end)?
);
let invalid = || ScheduleError::InvalidTime("message timestamp");
let utc = self
.created_at
.checked_to_offset(UtcOffset::UTC)
.ok_or_else(invalid)?;
if !(1..=9999).contains(&utc.year()) {
return Err(invalid());
}
let created_at = utc
.format(format_description!(
"[year]-[month]-[day]T[hour]:[minute]:[second]Z"
))
.map_err(|_| invalid())?;
let mut xml = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<ScheduleMessage DtdVersion="2" DtdRelease="3">
<MessageIdentification v="{}"/><MessageVersion v="{}"/>
<MessageType v="A01"/><ProcessType v="A17"/><ScheduleClassificationType v="A01"/>
<SenderIdentification v="{}" codingScheme="A01"/><SenderRole v="A08"/>
<ReceiverIdentification v="{}" codingScheme="A01"/><ReceiverRole v="A04"/>
<MessageDateTime v="{created_at}"/><ScheduleTimeInterval v="{}"/>
"#,
self.id, self.revision, self.sender, self.receiver, interval
);
for series in &self.series {
series.write_xml(&mut xml, &self.area, &interval);
}
xml.push_str("</ScheduleMessage>\n");
Ok(xml)
}
fn validate_series(&self, positions: usize) -> Result<(), ScheduleError> {
if self.series.is_empty() {
return Err(ScheduleError::EmptySchedule);
}
let mut ids = HashSet::new();
let mut trades = HashMap::new();
for series in &self.series {
validate_id("series ID", &series.id)?;
validate_revision("series revision", series.revision, self.revision)?;
if !ids.insert(&series.id) {
return Err(ScheduleError::DuplicateId(series.id.clone()));
}
if series.delivering == series.receiving
|| (series.delivering != self.sender && series.receiving != self.sender)
{
return Err(ScheduleError::InvalidParties(series.id.clone()));
}
if series.quantities.len() != positions {
return Err(ScheduleError::IntervalCount {
id: series.id.clone(),
expected: positions,
actual: series.quantities.len(),
});
}
if trades
.insert((&series.delivering, &series.receiving), &series.quantities)
.is_some()
{
return Err(ScheduleError::DuplicateTrade(series.id.clone()));
}
if let Some(reverse) = trades.get(&(&series.receiving, &series.delivering))
&& let Some(index) = series
.quantities
.iter()
.zip(*reverse)
.position(|(a, b)| a.0 > 0 && b.0 > 0)
{
return Err(ScheduleError::OverlappingFlows {
id: series.id.clone(),
position: index + 1,
});
}
}
Ok(())
}
}
fn validate_id(field: &'static str, value: &str) -> Result<(), ScheduleError> {
if !(1..=35).contains(&value.len()) || !value.bytes().all(|b| b.is_ascii_alphanumeric()) {
return Err(ScheduleError::InvalidId(field));
}
Ok(())
}
fn validate_revision(field: &'static str, value: u16, maximum: u16) -> Result<(), ScheduleError> {
if !(1..=maximum).contains(&value) {
return Err(ScheduleError::InvalidRevision {
field,
maximum,
value,
});
}
Ok(())
}
impl TradeSeries {
fn write_xml(&self, xml: &mut String, area: &BilanzierungsgebietId, interval: &str) {
write!(
xml,
r#"<ScheduleTimeSeries>
<SendersTimeSeriesIdentification v="{}"/><SendersTimeSeriesVersion v="{}"/>
<BusinessType v="A02"/><Product v="8716867000016"/><ObjectAggregation v="A01"/>
<InArea v="{area}" codingScheme="A01"/><OutArea v="{area}" codingScheme="A01"/>
<InParty v="{}" codingScheme="A01"/><OutParty v="{}" codingScheme="A01"/>
<MeasurementUnit v="MAW"/><Period><TimeInterval v="{interval}"/><Resolution v="PT15M"/>
"#,
self.id, self.revision, self.receiving, self.delivering
)
.expect("writing to String is infallible");
for (index, qty) in self.quantities.iter().enumerate() {
writeln!(
xml,
r#"<Interval><Pos v="{}"/><Qty v="{qty}"/></Interval>"#,
index + 1
)
.expect("writing to String is infallible");
}
xml.push_str("</Period></ScheduleTimeSeries>\n");
}
}
#[cfg(test)]
mod tests {
use super::*;
use time::macros::{date, datetime};
fn schedule() -> ScheduleMessage {
let sender = BilanzkreisId::new("11XSUEDWESTSTRO8").unwrap();
ScheduleMessage {
id: "Msg".into(),
revision: 2,
sender: sender.clone(),
receiver: "10XDE-EON-NETZ-C".parse().unwrap(),
area: "10YDE-EON------1".parse().unwrap(),
day: date!(2026 - 03 - 29),
created_at: datetime!(2026-03-28 11:22 UTC),
series: vec![TradeSeries {
id: "Sale".into(),
revision: 1,
delivering: sender,
receiving: "11XENERGIE2----H".parse().unwrap(),
quantities: vec![ScheduleQuantity::from_kw(1).unwrap(); 92],
}],
}
}
#[test]
fn ids_and_revisions_must_fit_the_wire_fields() {
let mut doc = schedule();
for invalid in ["", "one two", "A&B", "A\"B", "ä", &"Z".repeat(36)] {
doc.id = invalid.into();
assert_eq!(doc.to_xml(), Err(ScheduleError::InvalidId("message ID")));
}
doc.id = "A".repeat(35);
doc.series[0].id = "bad/id".into();
assert_eq!(doc.to_xml(), Err(ScheduleError::InvalidId("series ID")));
doc.series[0].id = "a9".repeat(17);
for (message, series) in [(0, 1), (1000, 1), (2, 0), (2, 3)] {
doc.revision = message;
doc.series[0].revision = series;
assert!(matches!(
doc.to_xml(),
Err(ScheduleError::InvalidRevision { .. })
));
}
doc.revision = 999;
doc.series[0].revision = 999;
assert!(doc.to_xml().is_ok());
}
#[test]
fn header_and_trade_parties_have_distinct_roles() {
let mut doc = schedule();
doc.receiver = "10YDE-EON------1".parse().unwrap();
assert!(matches!(
doc.to_xml(),
Err(ScheduleError::InvalidRecipient(_))
));
doc = schedule();
doc.area = "11YN-0000-0001-Q".parse().unwrap();
assert!(matches!(
doc.to_xml(),
Err(ScheduleError::InvalidRecipient(_))
));
doc = schedule();
doc.series[0].receiving = doc.sender.clone();
assert!(matches!(
doc.to_xml(),
Err(ScheduleError::InvalidParties(_))
));
doc = schedule();
doc.sender = "11XENAGISME----J".parse().unwrap();
assert!(matches!(
doc.to_xml(),
Err(ScheduleError::InvalidParties(_))
));
}
#[test]
fn delivery_days_stay_inside_the_qualified_schema_range() {
assert_eq!(
delivery_window(date!(2000 - 01 - 01)),
Err(ScheduleError::DayOutsideSchemaRange)
);
for day in [date!(2000 - 01 - 02), date!(2100 - 01 - 01)] {
let window = delivery_window(day).unwrap();
assert_eq!((window.end - window.start).whole_hours(), 24);
}
assert_eq!(
delivery_window(date!(2100 - 01 - 02)),
Err(ScheduleError::DayOutsideSchemaRange)
);
}
#[test]
fn complete_day_is_required_even_for_an_explicit_zero() {
let mut doc = schedule();
doc.series[0].quantities.pop();
assert!(matches!(
doc.to_xml(),
Err(ScheduleError::IntervalCount {
expected: 92,
actual: 91,
..
})
));
doc.series[0].quantities.extend([ScheduleQuantity(0); 2]);
assert!(matches!(
doc.to_xml(),
Err(ScheduleError::IntervalCount {
expected: 92,
actual: 93,
..
})
));
doc.series.clear();
assert_eq!(doc.to_xml(), Err(ScheduleError::EmptySchedule));
assert!(delivery_window(Date::MAX).is_err());
assert!(delivery_window(Date::MIN).is_err());
}
#[test]
fn a_bilateral_trade_has_at_most_one_flow_per_position() {
let mut doc = schedule();
doc.series.push(doc.series[0].clone());
assert!(matches!(doc.to_xml(), Err(ScheduleError::DuplicateId(_))));
doc.series[1].id = "Return".into();
assert!(matches!(
doc.to_xml(),
Err(ScheduleError::DuplicateTrade(_))
));
let reverse = &mut doc.series[1];
std::mem::swap(&mut reverse.receiving, &mut reverse.delivering);
reverse.quantities.fill(ScheduleQuantity(0));
reverse.quantities[91] = ScheduleQuantity(1);
assert!(matches!(
doc.to_xml(),
Err(ScheduleError::OverlappingFlows { position: 92, .. })
));
doc.series[0].quantities[91] = ScheduleQuantity(0);
let xml = doc.to_xml().unwrap();
assert_eq!(xml.matches("<ScheduleTimeSeries>").count(), 2);
assert_eq!(doc.to_xml().unwrap(), xml);
}
}