use jiff::civil::Date;
use crate::error::Rejection;
use crate::msg::agr_dso::nonempty;
use crate::msg::meta::{Metadata, Reply, ResponseHeader, XsDate, named};
use crate::msg::{DecodeOptions, Message, Wire, simple_response, wire_meta};
use crate::types::{
AcceptedRejected, EntityAddress, InternetDomain, MessageUuid, RedispatchBy, TimeZoneName,
};
use crate::xml::attrs::{Attrs, children, in_order, require_one};
use crate::xml::reader::Element;
use crate::xml::writer::Writer;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PortfolioConnection {
pub entity_address: EntityAddress,
pub start_period: Date,
pub end_period: Option<Date>,
}
impl PortfolioConnection {
pub(crate) fn read(el: &Element, path: String) -> Result<Self, Rejection> {
children(el, &path, &[])?;
let mut a = Attrs::new(el, path);
let v = Self {
entity_address: a.req("EntityAddress")?,
start_period: a.req::<XsDate>("StartPeriod")?.0,
end_period: a.opt::<XsDate>("EndPeriod")?.map(|d| d.0),
};
a.finish()?;
Ok(v)
}
pub(crate) fn write(&self, w: &mut Writer) {
w.start("Connection")
.attr("EntityAddress", &self.entity_address)
.attr("StartPeriod", self.start_period)
.opt_attr("EndPeriod", self.end_period.as_ref())
.end();
}
}
fn read_addresses(el: &Element, path: &str) -> Result<Vec<EntityAddress>, Rejection> {
named(el, path, "Connection")
.map(|(p, c)| {
children(c, &p, &[])?;
let mut a = Attrs::new(c, p);
let v = a.req("EntityAddress")?;
a.finish()?;
Ok(v)
})
.collect()
}
fn write_addresses(w: &mut Writer, addresses: &[EntityAddress]) {
for e in addresses {
w.start("Connection").attr("EntityAddress", e).end();
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgrPortfolioUpdate {
pub meta: Metadata,
pub time_zone: TimeZoneName,
pub connections: Vec<PortfolioConnection>,
}
impl Wire for AgrPortfolioUpdate {
const NAME: &'static str = "AGRPortfolioUpdate";
wire_meta!(meta);
fn validate(&self) -> Result<(), Rejection> {
for (i, c) in self.connections.iter().enumerate() {
let path = format!("{}/Connection[{}]", Self::NAME, i + 1);
check_range(c.start_period, c.end_period, None, &path)?;
}
Ok(())
}
fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
children(el, Self::NAME, &["Connection"])?;
require_one(el, Self::NAME, "Connection")?;
let mut a = Attrs::new(el, Self::NAME);
let meta = Metadata::read(&mut a)?;
let time_zone = a.req("TimeZone")?;
a.finish()?;
let connections = named(el, Self::NAME, "Connection")
.map(|(p, c)| PortfolioConnection::read(c, p))
.collect::<Result<_, _>>()?;
Ok(Self {
meta,
time_zone,
connections,
})
}
fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
nonempty(&self.connections, Self::NAME, "Connection")?;
w.start(Self::NAME);
self.meta.write(w);
w.attr("TimeZone", &self.time_zone);
for c in &self.connections {
c.write(w);
}
w.end();
Ok(())
}
fn answer(&self, reply: Reply) -> Option<Message> {
Some(self.reply(reply).into())
}
}
simple_response!(
AgrPortfolioUpdateResponse,
"AGRPortfolioUpdateResponse",
"AGRPortfolioUpdateMessageID",
agr_portfolio_update_message_id,
AgrPortfolioUpdate
);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgrPortfolioQuery {
pub meta: Metadata,
pub time_zone: TimeZoneName,
pub period: Date,
}
impl Wire for AgrPortfolioQuery {
const NAME: &'static str = "AGRPortfolioQuery";
wire_meta!(meta);
fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
children(el, Self::NAME, &[])?;
let mut a = Attrs::new(el, Self::NAME);
let v = Self {
meta: Metadata::read(&mut a)?,
time_zone: a.req("TimeZone")?,
period: a.req::<XsDate>("Period")?.0,
};
a.finish()?;
Ok(v)
}
fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
w.start(Self::NAME);
self.meta.write(w);
w.attr("TimeZone", &self.time_zone)
.attr("Period", self.period)
.end();
Ok(())
}
fn answer(&self, reply: Reply) -> Option<Message> {
(reply.result == AcceptedRejected::Rejected).then(|| self.reply(reply, Vec::new()).into())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PortfolioCongestionPoint {
pub entity_address: EntityAddress,
pub mutex_offers_supported: bool,
pub day_ahead_redispatch_by: RedispatchBy,
pub intraday_redispatch_by: Option<RedispatchBy>,
pub connections: Vec<EntityAddress>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DsoPortfolio {
pub dso_domain: InternetDomain,
pub congestion_points: Vec<PortfolioCongestionPoint>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DsoView {
pub portfolios: Vec<DsoPortfolio>,
pub connections: Vec<EntityAddress>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgrPortfolioQueryResponse {
header: ResponseHeader,
agr_portfolio_query_message_id: MessageUuid,
pub time_zone: TimeZoneName,
pub period: Date,
pub dso_views: Vec<DsoView>,
}
impl AgrPortfolioQueryResponse {
#[must_use]
pub fn header(&self) -> &ResponseHeader {
&self.header
}
#[must_use]
pub fn agr_portfolio_query_message_id(&self) -> MessageUuid {
self.agr_portfolio_query_message_id
}
}
impl AgrPortfolioQuery {
#[must_use]
pub fn reply(&self, reply: Reply, dso_views: Vec<DsoView>) -> AgrPortfolioQueryResponse {
AgrPortfolioQueryResponse {
header: ResponseHeader::reply_to(&self.meta, reply),
agr_portfolio_query_message_id: self.meta.message_id,
time_zone: self.time_zone.clone(),
period: self.period,
dso_views,
}
}
}
fn read_view(el: &Element, path: &str) -> Result<DsoView, Rejection> {
children(el, path, &["DSO-Portfolio", "Connection"])?;
in_order(el, path, &["DSO-Portfolio", "Connection"])?;
require_one(el, path, "DSO-Portfolio")?;
Attrs::new(el, path).finish()?;
let portfolios = named(el, path, "DSO-Portfolio")
.map(|(p, c)| {
children(c, &p, &["CongestionPoint"])?;
require_one(c, &p, "CongestionPoint")?;
let mut a = Attrs::new(c, p.clone());
let dso_domain = a.req("DSO-Domain")?;
a.finish()?;
let congestion_points = named(c, &p, "CongestionPoint")
.map(|(pp, cp)| {
children(cp, &pp, &["Connection"])?;
require_one(cp, &pp, "Connection")?;
let mut a = Attrs::new(cp, pp.clone());
let v = PortfolioCongestionPoint {
entity_address: a.req("EntityAddress")?,
mutex_offers_supported: a.req_bool("MutexOffersSupported")?,
day_ahead_redispatch_by: a.req("DayAheadRedispatchBy")?,
intraday_redispatch_by: a.opt("IntradayRedispatchBy")?,
connections: read_addresses(cp, &pp)?,
};
a.finish()?;
Ok(v)
})
.collect::<Result<_, Rejection>>()?;
Ok(DsoPortfolio {
dso_domain,
congestion_points,
})
})
.collect::<Result<_, Rejection>>()?;
Ok(DsoView {
portfolios,
connections: read_addresses(el, path)?,
})
}
impl Wire for AgrPortfolioQueryResponse {
const NAME: &'static str = "AGRPortfolioQueryResponse";
const RESPONSE: bool = true;
fn meta(&self) -> &Metadata {
self.header.meta()
}
fn meta_mut(&mut self) -> &mut Metadata {
self.header.meta_mut()
}
fn in_reply_to(&self) -> Option<MessageUuid> {
Some(self.agr_portfolio_query_message_id)
}
const REFERENCE: &'static str = "AGRPortfolioQueryMessageID";
fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
children(el, Self::NAME, &["DSO-View"])?;
let mut a = Attrs::new(el, Self::NAME);
let header = ResponseHeader::read(&mut a)?;
let agr_portfolio_query_message_id = a.req("AGRPortfolioQueryMessageID")?;
let time_zone = a.req("TimeZone")?;
let period = a.req::<XsDate>("Period")?.0;
a.finish()?;
if header.result() == AcceptedRejected::Accepted {
require_one(el, Self::NAME, "DSO-View")?;
}
let dso_views = named(el, Self::NAME, "DSO-View")
.map(|(p, c)| read_view(c, &p))
.collect::<Result<_, _>>()?;
Ok(Self {
header,
agr_portfolio_query_message_id,
time_zone,
period,
dso_views,
})
}
fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
if self.header.result() == AcceptedRejected::Accepted {
nonempty(&self.dso_views, Self::NAME, "DSO-View")?;
}
for (i, v) in self.dso_views.iter().enumerate() {
let p = format!("{}/DSO-View[{}]", Self::NAME, i + 1);
nonempty(&v.portfolios, &p, "DSO-Portfolio")?;
for (j, d) in v.portfolios.iter().enumerate() {
let pp = format!("{p}/DSO-Portfolio[{}]", j + 1);
nonempty(&d.congestion_points, &pp, "CongestionPoint")?;
for (k, c) in d.congestion_points.iter().enumerate() {
nonempty(
&c.connections,
&format!("{pp}/CongestionPoint[{}]", k + 1),
"Connection",
)?;
}
}
}
w.start(Self::NAME);
self.header.write(w);
w.attr("TimeZone", &self.time_zone)
.attr(
"AGRPortfolioQueryMessageID",
self.agr_portfolio_query_message_id,
)
.attr("Period", self.period);
for v in &self.dso_views {
w.start("DSO-View");
for d in &v.portfolios {
w.start("DSO-Portfolio").attr("DSO-Domain", &d.dso_domain);
for c in &d.congestion_points {
w.start("CongestionPoint")
.attr("EntityAddress", &c.entity_address)
.attr("MutexOffersSupported", c.mutex_offers_supported)
.attr("DayAheadRedispatchBy", c.day_ahead_redispatch_by)
.opt_attr("IntradayRedispatchBy", c.intraday_redispatch_by.as_ref());
write_addresses(w, &c.connections);
w.end();
}
w.end();
}
write_addresses(w, &v.connections);
w.end();
}
w.end();
Ok(())
}
}
pub(crate) fn check_range(
start: Date,
end: Option<Date>,
within: Option<(Date, Option<Date>)>,
path: &str,
) -> Result<(), Rejection> {
use crate::reason::RejectionReason as R;
let refuse = |message: String| {
Err(Rejection::rule(
R::PeriodOutOfBounds,
"[UFTP §3.5] Period of the message is inappropriate",
message,
)
.at(path.to_owned()))
};
if let Some(end) = end
&& end < start
{
return refuse(format!("EndPeriod {end} is before StartPeriod {start}."));
}
if let Some((outer_start, outer_end)) = within {
let ends_inside = match (end, outer_end) {
(_, None) => true,
(Some(e), Some(oe)) => e <= oe,
(None, Some(_)) => false,
};
if start < outer_start || !ends_inside {
let show = |e: Option<Date>| e.map_or_else(|| "open".to_owned(), |d| d.to_string());
return refuse(format!(
"The range {start} to {} is not inside its congestion point's {outer_start} to {}.",
show(end),
show(outer_end)
));
}
}
Ok(())
}