use jiff::Timestamp;
use jiff::civil::Date;
use crate::error::Rejection;
use crate::isp::IspSpan;
use crate::msg::PowerIsp;
use crate::msg::{
FlexHeader, FlexOffer, FlexOfferRevocation, FlexOrder, FlexRequest, Message, Metadata,
OfferOption,
};
use crate::reason::RejectionReason as R;
use crate::types::{ActivationFactor, Amount, Currency, IspDuration, MessageUuid, TimeZoneName};
impl FlexRequest {
#[must_use]
pub fn offer(
&self,
message_id: MessageUuid,
timestamp: Timestamp,
expiration: Timestamp,
currency: Currency,
options: Vec<OfferOption>,
) -> FlexOffer {
FlexOffer {
header: follow(&self.header, message_id, timestamp),
expiration,
unsolicited: Some(false),
flex_request_message_id: Some(self.header.meta.message_id),
contract_id: self.contract_id.clone(),
d_prognosis_message_id: None,
baseline_reference: None,
currency,
options,
}
}
}
impl FlexOffer {
#[must_use]
pub fn unsolicited(
header: FlexHeader,
expiration: Timestamp,
currency: Currency,
options: Vec<OfferOption>,
) -> Self {
Self {
header,
expiration,
unsolicited: Some(true),
flex_request_message_id: None,
contract_id: None,
d_prognosis_message_id: None,
baseline_reference: None,
currency,
options,
}
}
#[must_use]
pub fn revoke(&self, message_id: MessageUuid, timestamp: Timestamp) -> FlexOfferRevocation {
let m = &self.header.meta;
FlexOfferRevocation {
meta: Metadata::new(
m.sender_domain.clone(),
m.recipient_domain.clone(),
timestamp,
message_id,
)
.in_conversation(m.conversation_id),
flex_offer_message_id: m.message_id,
}
}
}
impl FlexOrder {
#[must_use]
pub fn unsolicited(
header: FlexHeader,
isps: Vec<PowerIsp>,
price: Amount,
currency: Currency,
order_reference: impl Into<String>,
) -> Self {
Self {
header,
isps,
unsolicited: Some(true),
flex_offer_message_id: None,
service_type: None,
contract_id: None,
d_prognosis_message_id: None,
baseline_reference: None,
price,
currency,
order_reference: order_reference.into(),
option_reference: None,
activation_factor: ActivationFactor::FULL,
}
}
}
impl OfferOption {
#[must_use]
pub fn new(option_reference: impl Into<String>, price: Amount, isps: Vec<PowerIsp>) -> Self {
Self {
option_reference: option_reference.into(),
price,
min_activation_factor: ActivationFactor::FULL,
isps,
}
}
#[must_use]
pub fn with_min_activation_factor(mut self, factor: ActivationFactor) -> Self {
self.min_activation_factor = factor;
self
}
}
impl FlexOffer {
pub fn order(
&self,
option_reference: Option<&str>,
activation_factor: ActivationFactor,
message_id: MessageUuid,
timestamp: Timestamp,
order_reference: impl Into<String>,
) -> Result<FlexOrder, Rejection> {
let option = self.option(option_reference)?;
check_factor(option, activation_factor)?;
Ok(FlexOrder {
header: follow(&self.header, message_id, timestamp),
isps: option.isps.clone(),
unsolicited: Some(false),
flex_offer_message_id: Some(self.header.meta.message_id),
service_type: None,
contract_id: self.contract_id.clone(),
d_prognosis_message_id: self.d_prognosis_message_id,
baseline_reference: self.baseline_reference.clone(),
price: option.price,
currency: self.currency,
order_reference: order_reference.into(),
option_reference: Some(option.option_reference.clone()),
activation_factor,
})
}
pub fn option(&self, reference: Option<&str>) -> Result<&OfferOption, Rejection> {
match reference {
Some(r) => self.options.iter().find(|o| o.option_reference == r),
None if self.options.len() == 1 => self.options.first(),
None => None,
}
.ok_or_else(|| {
Rejection::because(
R::UnknownReference("OptionReference"),
match reference {
Some(r) => format!("Offer {} has no option {r}.", self.header.meta.message_id),
None => format!(
"Offer {} has {} options; the order must name one.",
self.header.meta.message_id,
self.options.len()
),
},
)
.at("FlexOrder/@OptionReference")
})
}
pub fn check_against(&self, request: &FlexRequest) -> Result<(), Rejection> {
let path = "FlexOffer";
if self.flex_request_message_id != Some(request.header.meta.message_id) {
return Err(unknown(
"FlexRequestMessageID",
self.flex_request_message_id,
request.header.meta.message_id,
path,
));
}
parties(
&self.header.meta,
&request.header.meta,
"FlexRequestMessageID",
path,
)?;
same_day(&self.header, &request.header, path)?;
if self.header.meta.timestamp > request.expiration {
return Err(expired(
"FlexRequest",
request.expiration,
self.header.meta.timestamp,
path,
));
}
if self.expiration <= self.header.meta.timestamp {
return Err(Rejection::because(
R::ExpirationOutOfBounds,
format!(
"The offer expires at {}, before it was made at {}.",
self.expiration, self.header.meta.timestamp
),
)
.at(format!("{path}/@ExpirationDateTime")));
}
let requested: Vec<IspSpan> = request
.isps
.iter()
.filter(|i| i.disposition == Some(crate::AvailableRequested::Requested))
.map(|i| i.span)
.collect();
let overlaps = |a: IspSpan, b: IspSpan| a.start() <= b.end() && b.start() <= a.end();
let touches = self
.options
.iter()
.flat_map(|o| &o.isps)
.any(|i| requested.iter().any(|&r| overlaps(r, i.span)));
if !requested.is_empty() && !touches {
return Err(Rejection::because(
R::RequestMismatch,
"No option covers an ISP the request marks Requested; an offer answers at least one of them.",
)
.at(path));
}
Ok(())
}
}
impl FlexOrder {
pub fn check_against(&self, offer: &FlexOffer) -> Result<(), Rejection> {
let path = "FlexOrder";
if self.flex_offer_message_id != Some(offer.header.meta.message_id) {
return Err(unknown(
"FlexOfferMessageID",
self.flex_offer_message_id,
offer.header.meta.message_id,
path,
));
}
parties(
&self.header.meta,
&offer.header.meta,
"FlexOfferMessageID",
path,
)?;
same_day(&self.header, &offer.header, path)?;
if self.currency != offer.currency {
return Err(Rejection::because(
R::PriceMismatch,
format!(
"The order is in {} but the offer is in {}.",
self.currency, offer.currency
),
)
.at(format!("{path}/@Currency")));
}
if self.header.meta.timestamp > offer.expiration {
return Err(expired(
"FlexOffer",
offer.expiration,
self.header.meta.timestamp,
path,
));
}
let option = offer.option(self.option_reference.as_deref())?;
let spans = |isps: &[crate::PowerIsp]| isps.iter().map(|i| i.span).collect::<Vec<_>>();
if spans(&self.isps) != spans(&option.isps) {
return Err(Rejection::because(
R::IspMismatch,
format!(
"The ISPs differ from those of option {}; an order copies them unchanged.",
option.option_reference
),
)
.at(path));
}
if self.isps != option.isps {
return Err(Rejection::because(
R::PowerMismatch,
format!(
"The ordered power differs from option {}'s; an order copies it unchanged.",
option.option_reference
),
)
.at(path));
}
if self.price != option.price {
return Err(Rejection::because(
R::PriceMismatch,
format!(
"Price {} is not option {}'s price {}.",
self.price, option.option_reference, option.price
),
)
.at(format!("{path}/@Price")));
}
check_factor(option, self.activation_factor)
}
}
impl FlexOfferRevocation {
pub fn check_against(&self, offer: &FlexOffer) -> Result<(), Rejection> {
let path = "FlexOfferRevocation";
if self.flex_offer_message_id != offer.header.meta.message_id {
return Err(unknown(
"FlexOfferMessageID",
Some(self.flex_offer_message_id),
offer.header.meta.message_id,
path,
));
}
if self.meta.sender_domain != offer.header.meta.sender_domain
|| self.meta.recipient_domain != offer.header.meta.recipient_domain
{
return Err(Rejection::because(
R::UnknownReference("FlexOfferMessageID"),
"The offer was exchanged between other parties.",
)
.at(path));
}
if self.meta.timestamp > offer.expiration {
return Err(expired(
"FlexOffer",
offer.expiration,
self.meta.timestamp,
path,
));
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Market {
pub isp_duration: IspDuration,
pub time_zone: TimeZoneName,
}
impl Market {
pub fn check(&self, message: &Message) -> Result<(), Rejection> {
let (isp, zone, period) = timing(message);
let name = message.type_name();
if let Some(isp) = isp
&& isp != self.isp_duration
{
return Err(Rejection::because(
R::IspDurationRejected,
format!(
"ISP-Duration {isp} is not the market's {}.",
self.isp_duration
),
)
.at(format!("{name}/@ISP-Duration")));
}
if let Some(zone) = zone
&& !self.same_offsets(zone, period, message.meta().timestamp)
{
return Err(Rejection::because(
R::TimeZoneRejected,
format!(
"{zone} has another UTC offset than the market's {}.",
self.time_zone
),
)
.at(format!("{name}/@TimeZone")));
}
if let Message::FlexSettlement(s) = message {
self.check_settlement(s)?;
}
Ok(())
}
fn check_settlement(&self, s: &crate::FlexSettlement) -> Result<(), Rejection> {
let days = s
.order_settlements
.iter()
.enumerate()
.map(|(i, o)| {
(
format!("FlexSettlement/FlexOrderSettlement[{}]", i + 1),
o.period,
o.isps.iter().map(|x| x.span).collect::<Vec<_>>(),
)
})
.chain(
s.contract_settlements
.iter()
.enumerate()
.flat_map(|(i, c)| {
c.periods.iter().enumerate().map(move |(j, p)| {
(
format!(
"FlexSettlement/ContractSettlement[{}]/Period[{}]",
i + 1,
j + 1
),
p.period,
p.isps.iter().map(|x| x.span).collect::<Vec<_>>(),
)
})
}),
);
for (path, day, spans) in days {
crate::DayGrid::new(day, self.time_zone.clone(), self.isp_duration)
.and_then(|grid| grid.check(&spans))
.map_err(|e| e.at(path))?;
}
Ok(())
}
fn same_offsets(&self, zone: &TimeZoneName, period: Option<Date>, at: Timestamp) -> bool {
let offset = |z: &TimeZoneName, t: Timestamp| z.zone().to_offset(t);
let instants = match period {
Some(d) => [d, d.tomorrow().unwrap_or(d)]
.into_iter()
.filter_map(|d| {
d.to_zoned_datetime(self.time_zone.zone().clone())
.and_then(|z| z.start_of_day())
.ok()
})
.map(|z| z.timestamp())
.collect(),
None => vec![at],
};
instants
.into_iter()
.all(|t| offset(zone, t) == offset(&self.time_zone, t))
}
}
type Timing<'a> = (Option<IspDuration>, Option<&'a TimeZoneName>, Option<Date>);
fn flex(h: &FlexHeader) -> Timing<'_> {
(Some(h.isp_duration), Some(&h.time_zone), Some(h.period))
}
fn timing(m: &Message) -> Timing<'_> {
match m {
Message::FlexRequest(x) => flex(&x.header),
Message::FlexOffer(x) => flex(&x.header),
Message::FlexOrder(x) => flex(&x.header),
Message::DPrognosis(x) => flex(&x.header),
Message::FlexReservationUpdate(x) => flex(&x.header),
Message::Metering(x) => (Some(x.isp_duration), Some(&x.time_zone), Some(x.period)),
Message::AgrPortfolioUpdate(x) => (None, Some(&x.time_zone), None),
Message::AgrPortfolioQuery(x) => (None, Some(&x.time_zone), Some(x.period)),
Message::AgrPortfolioQueryResponse(x) => (None, Some(&x.time_zone), Some(x.period)),
Message::DsoPortfolioUpdate(x) => (None, Some(&x.time_zone), None),
Message::DsoPortfolioQuery(x) => (None, Some(&x.time_zone), Some(x.period)),
Message::DsoPortfolioQueryResponse(x) => (None, Some(&x.time_zone), Some(x.period)),
_ => (None, None, None),
}
}
fn follow(previous: &FlexHeader, message_id: MessageUuid, timestamp: Timestamp) -> FlexHeader {
FlexHeader {
meta: previous.meta.reply(message_id, timestamp),
..previous.clone()
}
}
fn check_factor(option: &OfferOption, factor: ActivationFactor) -> Result<(), Rejection> {
if factor < option.min_activation_factor {
return Err(Rejection::because(
R::InvalidSender,
format!(
"ActivationFactor {factor} is below option {}'s MinActivationFactor {}.",
option.option_reference, option.min_activation_factor
),
)
.at("FlexOrder/@ActivationFactor"));
}
Ok(())
}
fn unknown(
field: &'static str,
named: Option<MessageUuid>,
expected: MessageUuid,
path: &str,
) -> Rejection {
let named = named.map_or_else(|| "missing".to_owned(), |id| format!("{id}"));
Rejection::because(
R::UnknownReference(field),
format!("{field} is {named}, but the message it is checked against is {expected}."),
)
.at(format!("{path}/@{field}"))
}
fn parties(
follow_up: &Metadata,
referenced: &Metadata,
field: &'static str,
path: &str,
) -> Result<(), Rejection> {
if follow_up.sender_domain != referenced.recipient_domain
|| follow_up.recipient_domain != referenced.sender_domain
{
return Err(Rejection::because(
R::UnknownReference(field),
format!(
"The referenced message went from {} to {}, not between these parties.",
referenced.sender_domain, referenced.recipient_domain
),
)
.at(path.to_owned()));
}
Ok(())
}
fn same_day(a: &FlexHeader, b: &FlexHeader, path: &str) -> Result<(), Rejection> {
let mismatch = |reason, attr: &str, ours: String, theirs: String| {
Err(Rejection::because(
reason,
format!("{attr} is {ours}; the referenced message has {theirs}."),
)
.at(format!("{path}/@{attr}")))
};
if a.period != b.period {
return mismatch(
R::ReferencePeriodMismatch,
"Period",
a.period.to_string(),
b.period.to_string(),
);
}
if a.congestion_point != b.congestion_point {
return mismatch(
R::InvalidCongestionPoint,
"CongestionPoint",
a.congestion_point.to_string(),
b.congestion_point.to_string(),
);
}
if a.isp_duration != b.isp_duration {
return mismatch(
R::IspDurationRejected,
"ISP-Duration",
a.isp_duration.to_string(),
b.isp_duration.to_string(),
);
}
if a.time_zone != b.time_zone {
return mismatch(
R::TimeZoneRejected,
"TimeZone",
a.time_zone.to_string(),
b.time_zone.to_string(),
);
}
Ok(())
}
fn expired(what: &str, expiration: Timestamp, at: Timestamp, path: &str) -> Rejection {
Rejection::because(
R::ReferenceMessageExpired,
format!("The {what} expired at {expiration}, before this message was made at {at}."),
)
.at(path.to_owned())
}
impl Message {
pub fn check_time(&self, now: Timestamp) -> Result<(), Rejection> {
let (header, expiration) = match self {
Message::FlexRequest(x) => (&x.header, Some(x.expiration)),
Message::FlexOffer(x) => (&x.header, Some(x.expiration)),
Message::FlexOrder(x) => (&x.header, None),
Message::DPrognosis(x) => (&x.header, None),
Message::FlexReservationUpdate(x) => (&x.header, None),
_ => return Ok(()),
};
let name = self.type_name();
let grid = header.grid().map_err(|e| e.at(name))?;
let (_, day_end) = grid.interval(grid.count()).map_err(|e| e.at(name))?;
if day_end <= now {
return Err(Rejection::because(
R::PeriodOutOfBounds,
format!(
"Period {} in {} ended at {day_end}, before {now}.",
header.period, header.time_zone
),
)
.at(format!("{name}/@Period")));
}
if let Some(expiration) = expiration
&& expiration < now
{
return Err(Rejection::because(
R::ExpirationOutOfBounds,
format!("The {name} expired at {expiration}, before {now}."),
)
.at(format!("{name}/@ExpirationDateTime")));
}
Ok(())
}
}