use jiff::civil::Date;
use rust_decimal::Decimal;
use crate::error::Rejection;
use crate::isp::DayGrid;
use crate::msg::agr_dso::nonempty;
use crate::msg::meta::{Metadata, Reply, ResponseHeader, XsDate, child_path, named};
use crate::msg::{DecodeOptions, Message, Wire, simple_response, wire_meta};
use crate::reason::RejectionReason as R;
use crate::types::{
Currency, Ean, IspDuration, MessageUuid, MeteringProfileType, MeteringUnit, TimeZoneName,
};
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 MeteringIsp {
pub start: i64,
pub value: Decimal,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MeteringProfile {
pub profile_type: MeteringProfileType,
pub unit: MeteringUnit,
pub isps: Vec<MeteringIsp>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Metering {
pub meta: Metadata,
pub revision: i64,
pub isp_duration: IspDuration,
pub time_zone: TimeZoneName,
pub currency: Option<Currency>,
pub period: Date,
pub ean: Ean,
pub profiles: Vec<MeteringProfile>,
}
impl Metering {
pub fn grid(&self) -> Result<DayGrid, Rejection> {
DayGrid::new(self.period, self.time_zone.clone(), self.isp_duration)
}
}
impl Wire for Metering {
const NAME: &'static str = "Metering";
wire_meta!(meta);
fn read(el: &Element, _: DecodeOptions) -> Result<Self, Rejection> {
children(el, Self::NAME, &["Profile"])?;
require_one(el, Self::NAME, "Profile")?;
let mut a = Attrs::new(el, Self::NAME);
let meta = Metadata::read(&mut a)?;
let revision = a.req::<XsInteger>("Revision")?.0;
let isp_duration = a.req("ISP-Duration")?;
let time_zone = a.req("TimeZone")?;
let currency = a.opt("Currency")?;
let period = a.req::<XsDate>("Period")?.0;
let ean = a.req("EAN")?;
a.finish()?;
let profiles = named(el, Self::NAME, "Profile")
.map(|(p, c)| {
children(c, &p, &["ISP"])?;
require_one(c, &p, "ISP")?;
let mut a = Attrs::new(c, p.clone());
let profile_type = a.req("ProfileType")?;
let unit = a.req("Unit")?;
a.finish()?;
let isps = named(c, &p, "ISP")
.map(|(pp, i)| {
children(i, &pp, &[])?;
let mut a = Attrs::new(i, pp);
let v = MeteringIsp {
start: a.req::<XsInteger>("Start")?.0,
value: a.req::<XsDecimal>("Value")?.0,
};
a.finish()?;
Ok(v)
})
.collect::<Result<_, Rejection>>()?;
Ok(MeteringProfile {
profile_type,
unit,
isps,
})
})
.collect::<Result<_, Rejection>>()?;
Ok(Self {
meta,
revision,
isp_duration,
time_zone,
currency,
period,
ean,
profiles,
})
}
fn validate(&self) -> Result<(), Rejection> {
let grid = self.grid().map_err(|e| e.at(Self::NAME))?;
for (i, p) in self.profiles.iter().enumerate() {
let path = child_path(Self::NAME, "Profile", i);
if p.unit != p.profile_type.unit() {
return Err(Rejection::rule(
R::InvalidSender,
"[UFTP §4.2.26] kW for Power, kWh for energy profile types",
format!(
"A {} profile is in {}, not {}.",
p.profile_type,
p.profile_type.unit(),
p.unit
),
)
.at(format!("{path}/@Unit")));
}
let mut seen = vec![false; grid.count() as usize];
for (j, isp) in p.isps.iter().enumerate() {
let at = || child_path(&path, "ISP", j);
let n = usize::try_from(isp.start)
.ok()
.filter(|&n| (1..=seen.len()).contains(&n))
.ok_or_else(|| {
Rejection::rule(
R::IspsOutOfBounds,
"[UFTP §4.2.1]",
format!(
"ISP {} is not in {} ({} ISPs).",
isp.start,
self.period,
grid.count()
),
)
.at(at())
})?;
if std::mem::replace(&mut seen[n - 1], true) {
return Err(Rejection::rule(
R::IspConflict,
"[UFTP §4.2.1] each ISP in a period may only be addressed once",
format!("ISP {n} is addressed twice."),
)
.at(at()));
}
}
}
Ok(())
}
fn write(&self, w: &mut Writer) -> Result<(), Rejection> {
nonempty(&self.profiles, Self::NAME, "Profile")?;
for (i, p) in self.profiles.iter().enumerate() {
nonempty(&p.isps, &child_path(Self::NAME, "Profile", i), "ISP")?;
}
w.start(Self::NAME);
self.meta.write(w);
w.attr("Revision", self.revision)
.attr("ISP-Duration", self.isp_duration)
.attr("TimeZone", &self.time_zone)
.opt_attr("Currency", self.currency.as_ref())
.attr("Period", self.period)
.attr("EAN", &self.ean);
for p in &self.profiles {
w.start("Profile")
.attr("ProfileType", p.profile_type)
.attr("Unit", p.unit);
for i in &p.isps {
w.start("ISP")
.attr("Start", i.start)
.attr("Value", i.value)
.end();
}
w.end();
}
w.end();
Ok(())
}
fn answer(&self, reply: Reply) -> Option<Message> {
Some(self.reply(reply).into())
}
}
simple_response!(
MeteringResponse,
"MeteringResponse",
"MeteringMessageID",
metering_message_id,
Metering
);
struct XsDecimal(Decimal);
impl std::str::FromStr for XsDecimal {
type Err = Rejection;
fn from_str(s: &str) -> Result<Self, Rejection> {
let body = s.strip_prefix(['+', '-']).unwrap_or(s);
let (int, frac) = body.split_once('.').unwrap_or((body, ""));
let digits = |p: &str| p.bytes().all(|b| b.is_ascii_digit());
if (int.is_empty() && frac.is_empty()) || !digits(int) || !digits(frac) {
return Err(Rejection::schema(
"[XSD xs:decimal]",
format!("{s} is not a decimal number.", s = crate::error::quote(&s)),
));
}
s.trim_start_matches('+')
.parse::<Decimal>()
.map(Self)
.map_err(|_| {
Rejection::schema(
"[XSD xs:decimal]",
format!(
"{s} has more digits than this library keeps (28).",
s = crate::error::quote(&s)
),
)
})
}
}