use jiff::Timestamp;
use jiff::civil::Date;
use crate::error::Rejection;
use crate::isp::IspSpan;
use crate::msg::meta::{
FlexHeader, Metadata, Reply, ResponseHeader, XsDate, XsDateTime, child_path, named, read_span,
write_span,
};
use crate::msg::{DecodeOptions, Message, Wire, simple_response, wire_meta};
use crate::reason::RejectionReason as R;
use crate::types::{
AcceptedDisputed, AcceptedRejected, ActivationFactor, Amount, AvailableRequested, Currency,
EntityAddress, MessageUuid,
};
use crate::xml::attrs::{Attrs, XsInteger, children, require_one};
use crate::xml::reader::Element;
use crate::xml::writer::Writer;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PowerIsp {
pub span: IspSpan,
pub power: i64,
}
impl PowerIsp {
fn read(a: &mut Attrs<'_>) -> Result<Self, Rejection> {
Ok(Self {
power: a.req::<XsInteger>("Power")?.0,
span: read_span(a)?,
})
}
fn write(&self, w: &mut Writer) {
w.start("ISP").attr("Power", self.power);
write_span(w, self.span);
w.end();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FlexRequestIsp {
pub span: IspSpan,
pub disposition: Option<AvailableRequested>,
pub min_power: i64,
pub max_power: i64,
}
impl FlexRequestIsp {
#[must_use]
pub fn requested(span: IspSpan, min_power: i64, max_power: i64) -> Self {
Self {
span,
disposition: Some(AvailableRequested::Requested),
min_power,
max_power,
}
}
#[must_use]
pub fn available(span: IspSpan, min_power: i64, max_power: i64) -> Self {
Self {
span,
disposition: Some(AvailableRequested::Available),
min_power,
max_power,
}
}
fn read(a: &mut Attrs<'_>) -> Result<Self, Rejection> {
let isp = Self {
disposition: a.opt("Disposition")?,
min_power: a.req::<XsInteger>("MinPower")?.0,
max_power: a.req::<XsInteger>("MaxPower")?.0,
span: read_span(a)?,
};
Ok(isp)
}
fn check(&self) -> Result<(), Rejection> {
if self.min_power > self.max_power {
return Err(Rejection::rule(
R::PowerDiscrepancy,
"[UFTP ยง3.8.2] MinPower โค MaxPower",
format!(
"MinPower {} is greater than MaxPower {}.",
self.min_power, self.max_power
),
));
}
if self.disposition == Some(AvailableRequested::Requested)
&& self.min_power < 0
&& self.max_power > 0
{
return Err(Rejection::rule(
R::RequestedPowerDiscrepancy,
"[UFTP ยง3.8.2] a Requested ISP has a direction",
format!(
"MinPower {} and MaxPower {} point both ways; a Requested ISP asks for less (MaxPower โค 0) or more (MinPower โฅ 0).",
self.min_power, self.max_power
),
));
}
Ok(())
}
fn write(&self, w: &mut Writer) {
w.start("ISP")
.opt_attr("Disposition", self.disposition.as_ref())
.attr("MinPower", self.min_power)
.attr("MaxPower", self.max_power);
write_span(w, self.span);
w.end();
}
}
fn read_isps<T>(
el: &Element,
path: &str,
read: impl Fn(&mut Attrs<'_>) -> Result<T, Rejection>,
) -> Result<Vec<T>, Rejection> {
children(el, path, &["ISP"])?;
require_one(el, path, "ISP")?;
named(el, path, "ISP")
.map(|(p, c)| {
let mut a = Attrs::new(c, p);
let v = read(&mut a)?;
a.finish()?;
Ok(v)
})
.collect()
}
pub(crate) fn nonempty<T>(items: &[T], path: &str, name: &str) -> Result<(), Rejection> {
if items.is_empty() {
Err(Rejection::schema(
"[XSD] minOccurs=1",
format!("<{path}> needs at least one <{name}>."),
)
.at(path.to_owned()))
} else {
Ok(())
}
}
fn check_grid(
header: &FlexHeader,
spans: impl Iterator<Item = IspSpan>,
path: &str,
) -> Result<(), Rejection> {
let spans: Vec<IspSpan> = spans.collect();
header
.grid()
.map_err(|e| e.at(path.to_owned()))?
.check(&spans)
.map_err(|e| e.at(path.to_owned()))
}
fn check_expiration(
header: &FlexHeader,
expiration: Timestamp,
spans: impl Iterator<Item = IspSpan>,
name: &str,
) -> Result<(), Rejection> {
let Some(last) = spans.map(|s| s.end()).max() else {
return Ok(());
};
let grid = header.grid().map_err(|e| e.at(name.to_owned()))?;
let (_, end) = grid.interval(last).map_err(|e| e.at(name.to_owned()))?;
if expiration > end {
return Err(Rejection::rule(
R::ExpirationOutOfBounds,
"[UFTP ยง3.5] ExpirationDateTime does not exceed the ISPs in the message",
format!("ExpirationDateTime {expiration} is after the end of the last ISP ({last}) at {end}."),
)
.at(format!("{name}/@ExpirationDateTime")));
}
Ok(())
}
fn check_unique(spans: impl Iterator<Item = IspSpan>, path: &str) -> Result<(), Rejection> {
let mut v: Vec<IspSpan> = spans.collect();
v.sort();
for w in v.windows(2) {
if w[1].start() <= w[0].end() {
return Err(Rejection::rule(
R::IspConflict,
"[UFTP ยง4.2.1] each ISP in a period may only be addressed once",
format!(
"ISP {} is addressed twice ({} and {}).",
w[1].start(),
w[0],
w[1]
),
)
.at(path.to_owned()));
}
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DPrognosis {
pub header: FlexHeader,
pub revision: i64,
pub isps: Vec<PowerIsp>,
}
impl Wire for DPrognosis {
const NAME: &'static str = "D-Prognosis";
wire_meta!(header.meta);
fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
let mut a = Attrs::new(el, Self::NAME);
let v = Self {
header: FlexHeader::read(&mut a)?,
revision: a.req::<XsInteger>("Revision")?.0,
isps: read_isps(el, Self::NAME, PowerIsp::read)?,
};
a.finish()?;
Ok(v)
}
fn validate(&self) -> Result<(), Rejection> {
check_grid(&self.header, self.isps.iter().map(|i| i.span), Self::NAME)?;
let grid = self.header.grid().map_err(|e| e.at(Self::NAME))?;
let mut covered = vec![false; grid.count() as usize];
for isp in &self.isps {
for n in isp.span.start()..=isp.span.end() {
covered[n as usize - 1] = true;
}
}
if let Some(gap) = covered.iter().position(|c| !c) {
return Err(Rejection::rule(
R::LackingIsps,
"[UFTP ยง3.8.1] a prognosis covers every ISP of its Period",
format!(
"ISP {} of {} ({} ISPs) has no value.",
gap + 1,
self.header.period,
grid.count()
),
)
.at(Self::NAME));
}
Ok(())
}
fn answer(&self, reply: Reply) -> Option<Message> {
Some(self.reply(reply, Vec::new()).into())
}
fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
nonempty(&self.isps, Self::NAME, "ISP")?;
w.start(Self::NAME);
self.header.write(w);
w.attr("Revision", self.revision);
for i in &self.isps {
i.write(w);
}
w.end();
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FlexOrderStatus {
pub flex_order_message_id: MessageUuid,
pub is_validated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DPrognosisResponse {
header: ResponseHeader,
d_prognosis_message_id: MessageUuid,
pub flex_order_statuses: Vec<FlexOrderStatus>,
}
impl DPrognosisResponse {
#[must_use]
pub fn header(&self) -> &ResponseHeader {
&self.header
}
#[must_use]
pub fn d_prognosis_message_id(&self) -> MessageUuid {
self.d_prognosis_message_id
}
}
impl DPrognosis {
#[must_use]
pub fn reply(
&self,
reply: Reply,
flex_order_statuses: Vec<FlexOrderStatus>,
) -> DPrognosisResponse {
DPrognosisResponse {
header: ResponseHeader::reply_to(&self.header.meta, reply),
d_prognosis_message_id: self.header.meta.message_id,
flex_order_statuses,
}
}
}
impl Wire for DPrognosisResponse {
const NAME: &'static str = "D-PrognosisResponse";
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.d_prognosis_message_id)
}
const REFERENCE: &'static str = "D-PrognosisMessageID";
fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
children(el, Self::NAME, &["FlexOrderStatus"])?;
let mut a = Attrs::new(el, Self::NAME);
let header = ResponseHeader::read(&mut a)?;
let d_prognosis_message_id = a.req("D-PrognosisMessageID")?;
a.finish()?;
let flex_order_statuses = named(el, Self::NAME, "FlexOrderStatus")
.map(|(p, c)| {
children(c, &p, &[])?;
let mut a = Attrs::new(c, p);
let s = FlexOrderStatus {
flex_order_message_id: a.req("FlexOrderMessageID")?,
is_validated: a.opt_bool("IsValidated")?.ok_or_else(|| {
Rejection::schema(
"[XSD] required attribute",
"The required attribute IsValidated is missing.",
)
.at(a.path().to_owned())
})?,
};
a.finish()?;
Ok(s)
})
.collect::<Result<_, Rejection>>()?;
Ok(Self {
header,
d_prognosis_message_id,
flex_order_statuses,
})
}
fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
w.start(Self::NAME);
self.header.write(w);
w.attr("D-PrognosisMessageID", self.d_prognosis_message_id);
for s in &self.flex_order_statuses {
w.start("FlexOrderStatus")
.attr("FlexOrderMessageID", s.flex_order_message_id)
.attr("IsValidated", s.is_validated)
.end();
}
w.end();
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlexReservationUpdate {
pub header: FlexHeader,
pub contract_id: String,
pub reference: String,
pub isps: Vec<PowerIsp>,
}
impl Wire for FlexReservationUpdate {
const NAME: &'static str = "FlexReservationUpdate";
wire_meta!(header.meta);
fn validate(&self) -> Result<(), Rejection> {
check_grid(&self.header, self.isps.iter().map(|i| i.span), Self::NAME)
}
fn answer(&self, reply: Reply) -> Option<Message> {
Some(self.reply(reply).into())
}
fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
let mut a = Attrs::new(el, Self::NAME);
let v = Self {
header: FlexHeader::read(&mut a)?,
contract_id: a.req_string("ContractID")?,
reference: a.req_string("Reference")?,
isps: read_isps(el, Self::NAME, PowerIsp::read)?,
};
a.finish()?;
Ok(v)
}
fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
nonempty(&self.isps, Self::NAME, "ISP")?;
w.start(Self::NAME);
self.header.write(w);
w.attr("ContractID", &self.contract_id)
.attr("Reference", &self.reference);
for i in &self.isps {
i.write(w);
}
w.end();
Ok(())
}
}
simple_response!(
FlexReservationUpdateResponse,
"FlexReservationUpdateResponse",
"FlexReservationUpdateMessageID",
flex_reservation_update_message_id,
FlexReservationUpdate
);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlexRequest {
pub header: FlexHeader,
pub revision: i64,
pub expiration: Timestamp,
pub contract_id: Option<String>,
pub service_type: Option<String>,
pub isps: Vec<FlexRequestIsp>,
}
impl FlexRequest {
#[must_use]
pub fn new(header: FlexHeader, expiration: Timestamp, isps: Vec<FlexRequestIsp>) -> Self {
Self {
header,
revision: 1,
expiration,
contract_id: None,
service_type: None,
isps,
}
}
}
impl Wire for FlexRequest {
const NAME: &'static str = "FlexRequest";
wire_meta!(header.meta);
fn validate(&self) -> Result<(), Rejection> {
for (i, isp) in self.isps.iter().enumerate() {
isp.check()
.map_err(|e| e.at(child_path(Self::NAME, "ISP", i)))?;
}
if !self
.isps
.iter()
.any(|i| i.disposition == Some(AvailableRequested::Requested))
{
return Err(Rejection::rule(
R::LackingRequestedDisposition,
"[UFTP ยง4.2.18] at least one ISP should have Disposition = Requested",
"No ISP has Disposition=\"Requested\"; a FlexRequest asks for flexibility in at least one.",
)
.at(Self::NAME));
}
check_grid(&self.header, self.isps.iter().map(|i| i.span), Self::NAME)?;
check_expiration(
&self.header,
self.expiration,
self.isps.iter().map(|i| i.span),
Self::NAME,
)
}
fn answer(&self, reply: Reply) -> Option<Message> {
Some(self.reply(reply).into())
}
fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
let mut a = Attrs::new(el, Self::NAME);
let v = Self {
header: FlexHeader::read(&mut a)?,
revision: a.req::<XsInteger>("Revision")?.0,
expiration: a.req::<XsDateTime>("ExpirationDateTime")?.0,
contract_id: a.opt_string("ContractID"),
service_type: a.opt_string("ServiceType"),
isps: read_isps(el, Self::NAME, FlexRequestIsp::read)?,
};
a.finish()?;
Ok(v)
}
fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
nonempty(&self.isps, Self::NAME, "ISP")?;
w.start(Self::NAME);
self.header.write(w);
w.attr("Revision", self.revision)
.attr("ExpirationDateTime", self.expiration)
.opt_attr("ContractID", self.contract_id.as_ref())
.opt_attr("ServiceType", self.service_type.as_ref());
for i in &self.isps {
i.write(w);
}
w.end();
Ok(())
}
}
simple_response!(
FlexRequestResponse,
"FlexRequestResponse",
"FlexRequestMessageID",
flex_request_message_id,
FlexRequest
);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OfferOption {
pub option_reference: String,
pub price: Amount,
pub min_activation_factor: ActivationFactor,
pub isps: Vec<PowerIsp>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlexOffer {
pub header: FlexHeader,
pub expiration: Timestamp,
pub unsolicited: Option<bool>,
pub flex_request_message_id: Option<MessageUuid>,
pub contract_id: Option<String>,
pub d_prognosis_message_id: Option<MessageUuid>,
pub baseline_reference: Option<String>,
pub currency: Currency,
pub options: Vec<OfferOption>,
}
fn check_solicited(
unsolicited: Option<bool>,
reference: Option<&MessageUuid>,
attr: &'static str,
path: &str,
) -> Result<(), Rejection> {
if unsolicited == Some(false) && reference.is_none() {
return Err(Rejection::rule(
R::UnknownReference(attr),
"[XSD] mandatory if Unsolicited=false",
format!("Unsolicited is false, so {attr} must name the message this answers."),
)
.at(path.to_owned()));
}
Ok(())
}
impl Wire for FlexOffer {
const NAME: &'static str = "FlexOffer";
wire_meta!(header.meta);
fn validate(&self) -> Result<(), Rejection> {
check_solicited(
self.unsolicited,
self.flex_request_message_id.as_ref(),
"FlexRequestMessageID",
Self::NAME,
)?;
for (i, o) in self.options.iter().enumerate() {
let p = child_path(Self::NAME, "OfferOption", i);
check_grid(&self.header, o.isps.iter().map(|i| i.span), &p)?;
}
check_expiration(
&self.header,
self.expiration,
self.options
.iter()
.flat_map(|o| o.isps.iter().map(|i| i.span)),
Self::NAME,
)
}
fn answer(&self, reply: Reply) -> Option<Message> {
Some(self.reply(reply).into())
}
fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
children(el, Self::NAME, &["OfferOption"])?;
require_one(el, Self::NAME, "OfferOption")?;
let mut a = Attrs::new(el, Self::NAME);
let header = FlexHeader::read(&mut a)?;
let expiration = a.req::<XsDateTime>("ExpirationDateTime")?.0;
let unsolicited = a.opt_bool("Unsolicited")?;
let flex_request_message_id = a.opt("FlexRequestMessageID")?;
let contract_id = a.opt_string("ContractID");
let d_prognosis_message_id = a.opt("D-PrognosisMessageID")?;
let baseline_reference = a.opt_string("BaselineReference");
let currency = a.req("Currency")?;
a.finish()?;
let options = named(el, Self::NAME, "OfferOption")
.map(|(p, c)| {
let mut a = Attrs::new(c, p.clone());
let o = OfferOption {
option_reference: a.req_string("OptionReference")?,
price: a.req("Price")?,
min_activation_factor: a.opt("MinActivationFactor")?.unwrap_or_default(),
isps: read_isps(c, &p, PowerIsp::read)?,
};
a.finish()?;
Ok(o)
})
.collect::<Result<Vec<_>, Rejection>>()?;
Ok(Self {
header,
expiration,
unsolicited,
flex_request_message_id,
contract_id,
d_prognosis_message_id,
baseline_reference,
currency,
options,
})
}
fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
nonempty(&self.options, Self::NAME, "OfferOption")?;
for (i, o) in self.options.iter().enumerate() {
nonempty(&o.isps, &child_path(Self::NAME, "OfferOption", i), "ISP")?;
}
w.start(Self::NAME);
self.header.write(w);
w.attr("ExpirationDateTime", self.expiration)
.opt_attr("Unsolicited", self.unsolicited.as_ref())
.opt_attr(
"FlexRequestMessageID",
self.flex_request_message_id.as_ref(),
)
.opt_attr("ContractID", self.contract_id.as_ref())
.opt_attr("D-PrognosisMessageID", self.d_prognosis_message_id.as_ref())
.opt_attr("BaselineReference", self.baseline_reference.as_ref())
.attr("Currency", self.currency);
for o in &self.options {
w.start("OfferOption")
.attr("OptionReference", &o.option_reference)
.attr("Price", o.price)
.attr("MinActivationFactor", o.min_activation_factor);
for i in &o.isps {
i.write(w);
}
w.end();
}
w.end();
Ok(())
}
}
simple_response!(
FlexOfferResponse,
"FlexOfferResponse",
"FlexOfferMessageID",
flex_offer_message_id,
FlexOffer
);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlexOfferRevocation {
pub meta: Metadata,
pub flex_offer_message_id: MessageUuid,
}
impl Wire for FlexOfferRevocation {
const NAME: &'static str = "FlexOfferRevocation";
wire_meta!(meta);
fn answer(&self, reply: Reply) -> Option<Message> {
Some(self.reply(reply).into())
}
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)?,
flex_offer_message_id: a.req("FlexOfferMessageID")?,
};
a.finish()?;
Ok(v)
}
fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
w.start(Self::NAME);
self.meta.write(w);
w.attr("FlexOfferMessageID", self.flex_offer_message_id)
.end();
Ok(())
}
}
simple_response!(
FlexOfferRevocationResponse,
"FlexOfferRevocationResponse",
"FlexOfferRevocationMessageID",
flex_offer_revocation_message_id,
FlexOfferRevocation
);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlexOrder {
pub header: FlexHeader,
pub isps: Vec<PowerIsp>,
pub unsolicited: Option<bool>,
pub flex_offer_message_id: Option<MessageUuid>,
pub service_type: Option<String>,
pub contract_id: Option<String>,
pub d_prognosis_message_id: Option<MessageUuid>,
pub baseline_reference: Option<String>,
pub price: Amount,
pub currency: Currency,
pub order_reference: String,
pub option_reference: Option<String>,
pub activation_factor: ActivationFactor,
}
impl Wire for FlexOrder {
const NAME: &'static str = "FlexOrder";
wire_meta!(header.meta);
fn validate(&self) -> Result<(), Rejection> {
check_solicited(
self.unsolicited,
self.flex_offer_message_id.as_ref(),
"FlexOfferMessageID",
Self::NAME,
)?;
check_grid(&self.header, self.isps.iter().map(|i| i.span), Self::NAME)
}
fn answer(&self, reply: Reply) -> Option<Message> {
Some(self.reply(reply).into())
}
fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
let mut a = Attrs::new(el, Self::NAME);
let v = Self {
header: FlexHeader::read(&mut a)?,
unsolicited: a.opt_bool("Unsolicited")?,
flex_offer_message_id: a.opt("FlexOfferMessageID")?,
service_type: a.opt_string("ServiceType"),
contract_id: a.opt_string("ContractID"),
d_prognosis_message_id: a.opt("D-PrognosisMessageID")?,
baseline_reference: a.opt_string("BaselineReference"),
price: a.req("Price")?,
currency: a.req("Currency")?,
order_reference: a.req_string("OrderReference")?,
option_reference: a.opt_string("OptionReference"),
activation_factor: a.opt("ActivationFactor")?.unwrap_or_default(),
isps: read_isps(el, Self::NAME, PowerIsp::read)?,
};
a.finish()?;
Ok(v)
}
fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
nonempty(&self.isps, Self::NAME, "ISP")?;
w.start(Self::NAME);
self.header.write(w);
w.opt_attr("Unsolicited", self.unsolicited.as_ref())
.opt_attr("FlexOfferMessageID", self.flex_offer_message_id.as_ref())
.opt_attr("ServiceType", self.service_type.as_ref())
.opt_attr("ContractID", self.contract_id.as_ref())
.opt_attr("D-PrognosisMessageID", self.d_prognosis_message_id.as_ref())
.opt_attr("BaselineReference", self.baseline_reference.as_ref())
.attr("Price", self.price)
.attr("Currency", self.currency)
.attr("OrderReference", &self.order_reference)
.opt_attr("OptionReference", self.option_reference.as_ref())
.attr("ActivationFactor", self.activation_factor);
for i in &self.isps {
i.write(w);
}
w.end();
Ok(())
}
}
simple_response!(
FlexOrderResponse,
"FlexOrderResponse",
"FlexOrderMessageID",
flex_order_message_id,
FlexOrder
);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SettlementIsp {
pub span: IspSpan,
pub baseline_power: i64,
pub ordered_flex_power: i64,
pub actual_power: i64,
pub delivered_flex_power: i64,
pub power_deficiency: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlexOrderSettlement {
pub order_reference: Option<String>,
pub period: Date,
pub contract_id: Option<String>,
pub d_prognosis_message_id: Option<MessageUuid>,
pub baseline_reference: Option<String>,
pub congestion_point: EntityAddress,
pub price: Amount,
pub penalty: Amount,
pub net_settlement: Amount,
pub isps: Vec<SettlementIsp>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContractSettlementIsp {
pub span: IspSpan,
pub reserved_power: i64,
pub requested_power: Option<i64>,
pub available_power: Option<i64>,
pub offered_power: Option<i64>,
pub ordered_power: Option<i64>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContractSettlementPeriod {
pub period: Date,
pub isps: Vec<ContractSettlementIsp>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContractSettlement {
pub contract_id: Option<String>,
pub periods: Vec<ContractSettlementPeriod>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlexSettlement {
pub meta: Metadata,
pub result: AcceptedRejected,
pub rejection_reason: Option<String>,
pub period_start: Date,
pub period_end: Date,
pub currency: Currency,
pub order_settlements: Vec<FlexOrderSettlement>,
pub contract_settlements: Vec<ContractSettlement>,
}
fn read_order_settlement(c: &Element, p: &str) -> Result<FlexOrderSettlement, Rejection> {
let mut a = Attrs::new(c, p.to_owned());
let s = FlexOrderSettlement {
order_reference: a.opt_string("OrderReference"),
period: a.req::<XsDate>("Period")?.0,
contract_id: a.opt_string("ContractID"),
d_prognosis_message_id: a.opt("D-PrognosisMessageID")?,
baseline_reference: a.opt_string("BaselineReference"),
congestion_point: a.req("CongestionPoint")?,
price: a.req("Price")?,
penalty: a.opt("Penalty")?.unwrap_or(Amount::ZERO),
net_settlement: a.req("NetSettlement")?,
isps: read_isps(c, p, |a| {
Ok(SettlementIsp {
span: read_span(a)?,
baseline_power: a.req::<XsInteger>("BaselinePower")?.0,
ordered_flex_power: a.req::<XsInteger>("OrderedFlexPower")?.0,
actual_power: a.req::<XsInteger>("ActualPower")?.0,
delivered_flex_power: a.req::<XsInteger>("DeliveredFlexPower")?.0,
power_deficiency: a.opt::<XsInteger>("PowerDeficiency")?.map_or(0, |v| v.0),
})
})?,
};
a.finish()?;
Ok(s)
}
fn read_contract_settlement(c: &Element, p: &str) -> Result<ContractSettlement, Rejection> {
children(c, p, &["Period"])?;
require_one(c, p, "Period")?;
let mut a = Attrs::new(c, p.to_owned());
let contract_id = a.opt_string("ContractID");
a.finish()?;
let periods = named(c, p, "Period")
.map(|(pp, pe)| {
let mut a = Attrs::new(pe, pp.clone());
let period = a.req::<XsDate>("Period")?.0;
a.finish()?;
let isps = read_isps(pe, &pp, |a| {
Ok(ContractSettlementIsp {
span: read_span(a)?,
reserved_power: a.req::<XsInteger>("ReservedPower")?.0,
requested_power: a.opt::<XsInteger>("RequestedPower")?.map(|v| v.0),
available_power: a.opt::<XsInteger>("AvailablePower")?.map(|v| v.0),
offered_power: a.opt::<XsInteger>("OfferedPower")?.map(|v| v.0),
ordered_power: a.opt::<XsInteger>("OrderedPower")?.map(|v| v.0),
})
})?;
Ok(ContractSettlementPeriod { period, isps })
})
.collect::<Result<_, Rejection>>()?;
Ok(ContractSettlement {
contract_id,
periods,
})
}
impl Wire for FlexSettlement {
const NAME: &'static str = "FlexSettlement";
wire_meta!(meta);
fn validate(&self) -> Result<(), Rejection> {
if self.period_end < self.period_start {
return Err(Rejection::rule(
R::PeriodOutOfBounds,
"[XSD FlexSettlementType] PeriodStart โค PeriodEnd",
format!(
"PeriodEnd {} is before PeriodStart {}.",
self.period_end, self.period_start
),
)
.at(Self::NAME));
}
let within = |day: Date, path: &str| {
if day < self.period_start || day > self.period_end {
return Err(Rejection::rule(
R::PeriodOutOfBounds,
"[XSD FlexSettlementType] PeriodStart and PeriodEnd bound the settlement",
format!(
"Period {day} is outside the settlement's {} to {}.",
self.period_start, self.period_end
),
)
.at(format!("{path}/@Period")));
}
Ok(())
};
for (i, s) in self.order_settlements.iter().enumerate() {
let p = child_path(Self::NAME, "FlexOrderSettlement", i);
within(s.period, &p)?;
check_unique(s.isps.iter().map(|i| i.span), &p)?;
}
for (i, c) in self.contract_settlements.iter().enumerate() {
let p = child_path(Self::NAME, "ContractSettlement", i);
for (j, pe) in c.periods.iter().enumerate() {
let pp = child_path(&p, "Period", j);
within(pe.period, &pp)?;
check_unique(pe.isps.iter().map(|i| i.span), &pp)?;
}
}
Ok(())
}
fn answer(&self, reply: Reply) -> Option<Message> {
let statuses = self
.order_settlements
.iter()
.map(|s| FlexOrderSettlementStatus {
order_reference: s.order_reference.clone(),
disposition: match reply.result {
AcceptedRejected::Accepted => AcceptedDisputed::Accepted,
AcceptedRejected::Rejected => AcceptedDisputed::Disputed,
},
dispute_reason: reply.rejection_reason.clone(),
})
.collect();
Some(self.reply(reply, statuses).into())
}
fn read(el: &Element, opts: DecodeOptions) -> Result<Self, Rejection> {
children(
el,
Self::NAME,
&["FlexOrderSettlement", "ContractSettlement"],
)?;
require_one(el, Self::NAME, "FlexOrderSettlement")?;
if !opts.allow_empty_contract_settlement {
require_one(el, Self::NAME, "ContractSettlement")?;
}
if let Some(first_contract) = el
.children
.iter()
.position(|c| c.name == "ContractSettlement")
&& el.children[first_contract..]
.iter()
.any(|c| c.name == "FlexOrderSettlement")
{
return Err(Rejection::schema(
"[XSD] xs:sequence order",
"FlexOrderSettlement elements must come before ContractSettlement elements.",
)
.at(Self::NAME));
}
let mut a = Attrs::new(el, Self::NAME);
let meta = Metadata::read(&mut a)?;
let result = a.req("Result")?;
let rejection_reason = a.opt_string("RejectionReason");
let period_start = a.req::<XsDate>("PeriodStart")?.0;
let period_end = a.req::<XsDate>("PeriodEnd")?.0;
let currency = a.req("Currency")?;
a.finish()?;
let order_settlements = named(el, Self::NAME, "FlexOrderSettlement")
.map(|(p, c)| read_order_settlement(c, &p))
.collect::<Result<_, _>>()?;
let contract_settlements = named(el, Self::NAME, "ContractSettlement")
.map(|(p, c)| read_contract_settlement(c, &p))
.collect::<Result<_, _>>()?;
Ok(Self {
meta,
result,
rejection_reason,
period_start,
period_end,
currency,
order_settlements,
contract_settlements,
})
}
fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
nonempty(&self.order_settlements, Self::NAME, "FlexOrderSettlement")?;
if self.contract_settlements.is_empty() {
return Err(Rejection::schema(
"[XSD FlexSettlementType] ContractSettlement minOccurs=1 (spec note SS-02)",
"The 3.1.0 XSD requires at least one ContractSettlement; a settlement without bilateral contracts cannot be encoded validly.",
)
.at(Self::NAME));
}
w.start(Self::NAME);
self.meta.write(w);
w.attr("Result", self.result)
.opt_attr("RejectionReason", self.rejection_reason.as_ref())
.attr("PeriodStart", self.period_start)
.attr("PeriodEnd", self.period_end)
.attr("Currency", self.currency);
for (i, s) in self.order_settlements.iter().enumerate() {
let p = format!("{}/FlexOrderSettlement[{}]", Self::NAME, i + 1);
nonempty(&s.isps, &p, "ISP")?;
w.start("FlexOrderSettlement")
.opt_attr("OrderReference", s.order_reference.as_ref())
.attr("Period", s.period)
.opt_attr("ContractID", s.contract_id.as_ref())
.opt_attr("D-PrognosisMessageID", s.d_prognosis_message_id.as_ref())
.opt_attr("BaselineReference", s.baseline_reference.as_ref())
.attr("CongestionPoint", &s.congestion_point)
.attr("Price", s.price)
.attr("Penalty", s.penalty)
.attr("NetSettlement", s.net_settlement);
for i in &s.isps {
w.start("ISP");
write_span(w, i.span);
w.attr("BaselinePower", i.baseline_power)
.attr("OrderedFlexPower", i.ordered_flex_power)
.attr("ActualPower", i.actual_power)
.attr("DeliveredFlexPower", i.delivered_flex_power)
.attr("PowerDeficiency", i.power_deficiency)
.end();
}
w.end();
}
for (i, c) in self.contract_settlements.iter().enumerate() {
let p = format!("{}/ContractSettlement[{}]", Self::NAME, i + 1);
nonempty(&c.periods, &p, "Period")?;
w.start("ContractSettlement")
.opt_attr("ContractID", c.contract_id.as_ref());
for (j, pe) in c.periods.iter().enumerate() {
let pp = format!("{p}/Period[{}]", j + 1);
nonempty(&pe.isps, &pp, "ISP")?;
w.start("Period").attr("Period", pe.period);
for i in &pe.isps {
w.start("ISP");
write_span(w, i.span);
w.attr("ReservedPower", i.reserved_power)
.opt_attr("RequestedPower", i.requested_power.as_ref())
.opt_attr("AvailablePower", i.available_power.as_ref())
.opt_attr("OfferedPower", i.offered_power.as_ref())
.opt_attr("OrderedPower", i.ordered_power.as_ref())
.end();
}
w.end();
}
w.end();
}
w.end();
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlexOrderSettlementStatus {
pub order_reference: Option<String>,
pub disposition: AcceptedDisputed,
pub dispute_reason: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlexSettlementResponse {
header: ResponseHeader,
flex_settlement_message_id: MessageUuid,
pub statuses: Vec<FlexOrderSettlementStatus>,
}
impl FlexSettlementResponse {
#[must_use]
pub fn header(&self) -> &ResponseHeader {
&self.header
}
#[must_use]
pub fn flex_settlement_message_id(&self) -> MessageUuid {
self.flex_settlement_message_id
}
}
impl FlexSettlement {
#[must_use]
pub fn reply(
&self,
reply: Reply,
statuses: Vec<FlexOrderSettlementStatus>,
) -> FlexSettlementResponse {
FlexSettlementResponse {
header: ResponseHeader::reply_to(&self.meta, reply),
flex_settlement_message_id: self.meta.message_id,
statuses,
}
}
}
impl Wire for FlexSettlementResponse {
const NAME: &'static str = "FlexSettlementResponse";
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.flex_settlement_message_id)
}
const REFERENCE: &'static str = "FlexSettlementMessageID";
fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
children(el, Self::NAME, &["FlexOrderSettlementStatus"])?;
require_one(el, Self::NAME, "FlexOrderSettlementStatus")?;
let mut a = Attrs::new(el, Self::NAME);
let header = ResponseHeader::read(&mut a)?;
let flex_settlement_message_id = a.req("FlexSettlementMessageID")?;
a.finish()?;
let statuses = named(el, Self::NAME, "FlexOrderSettlementStatus")
.map(|(p, c)| {
children(c, &p, &[])?;
let mut a = Attrs::new(c, p);
let s = FlexOrderSettlementStatus {
order_reference: a.opt_string("OrderReference"),
disposition: a.req("Disposition")?,
dispute_reason: a.opt_string("DisputeReason"),
};
a.finish()?;
Ok(s)
})
.collect::<Result<_, Rejection>>()?;
Ok(Self {
header,
flex_settlement_message_id,
statuses,
})
}
fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
nonempty(&self.statuses, Self::NAME, "FlexOrderSettlementStatus")?;
w.start(Self::NAME);
self.header.write(w);
w.attr("FlexSettlementMessageID", self.flex_settlement_message_id);
for s in &self.statuses {
w.start("FlexOrderSettlementStatus")
.opt_attr("OrderReference", s.order_reference.as_ref())
.attr("Disposition", s.disposition)
.opt_attr("DisputeReason", s.dispute_reason.as_ref())
.end();
}
w.end();
Ok(())
}
}