#[cfg(test)]
mod test;
#[cfg(test)]
mod test_every_field_set;
#[cfg(test)]
mod test_tariffs;
use std::{fmt, ops::Range};
use jiff::{Timestamp, tz::TimeZone};
use crate::{
FromSchema as _, Verdict, country, currency, datetime, duration, from_warning_all, generate,
json, money, number, price,
schema::{self, HasElement as _},
string, tariff, version,
warning::{self, Caveat},
};
pub fn infer_version(json: json::Document<'_>) -> VersionGuess<'_> {
version::cdr_version(json)
}
pub type VersionGuess<'buf> = version::Guess<VersionedJson<'buf>, Unversioned<'buf>>;
pub fn check(
json: json::Document<'_>,
version: crate::Version,
) -> Caveat<Checked<'_>, schema::Warning> {
let mut warnings = warning::Gatherer::new();
let version = match version {
crate::Version::V221 => Version::V221(schema::v221::build_cdr(&json, &mut warnings)),
crate::Version::V211 => Version::V211(schema::v211::build_cdr(&json, &mut warnings)),
};
let checked = Checked { doc: json, version };
Caveat::new(checked, warnings.into_set())
}
pub fn build(checked: Checked<'_>) -> Verdict<Cdr<'_>, Warning> {
let mut warnings = warning::Gatherer::new();
let cdr = checked.lower_to_v221(&mut warnings);
let cdr = cdr.map(|cdr| Cdr { checked, cdr });
warnings.into_verdict(cdr)
}
pub fn generate_from_tariff(
tariff: &tariff::Tariff<'_>,
config: &generate::Config,
) -> Verdict<generate::Report, generate::Warning> {
let mut warnings = warning::Gatherer::new();
let report = generate::cdr_from_tariff(tariff, config, &mut warnings);
warnings.into_verdict(report)
}
pub fn price(
cdr: &Cdr<'_>,
tariffs: &[tariff::Tariff<'_>],
timezone: &TimeZone,
) -> Verdict<price::Report, price::Warning> {
price::cdr(cdr, tariffs, timezone)
}
pub struct Cdr<'buf> {
checked: Checked<'buf>,
cdr: price::v221::Cdr,
}
impl fmt::Debug for Cdr<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.cdr, f)
}
}
impl<'buf> Cdr<'buf> {
pub fn tariffs(&self) -> Verdict<Vec<tariff::Tariff<'buf>>, tariff::Warning> {
let mut warnings = warning::Gatherer::new();
let tariffs = self.checked.tariffs_to_v221(&mut warnings);
warnings.into_verdict(tariffs)
}
pub(crate) fn as_checked(&self) -> &Checked<'buf> {
&self.checked
}
pub(crate) fn as_v221(&self) -> &price::v221::Cdr {
&self.cdr
}
}
#[derive(Debug)]
pub enum Warning {
Country(country::Warning),
CountryShouldBeAlpha2,
Currency(currency::Warning),
DateTime(datetime::Warning),
Decode(json::decode::Warning),
Duration(duration::Warning),
Money(money::Warning),
NoPeriods,
Number(number::Warning),
PeriodsOutsideStartEndDateTime {
cdr_range: Range<Timestamp>,
period_range: PeriodRange,
},
String(string::Warning),
Rejected,
}
#[derive(Debug)]
pub enum PeriodRange {
Many(Range<Timestamp>),
Single(Timestamp),
}
impl fmt::Display for PeriodRange {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PeriodRange::Many(Range { start, end }) => write!(f, "[start: {start}, end: {end}]"),
PeriodRange::Single(date_time) => write!(f, "{date_time}"),
}
}
}
impl fmt::Display for Warning {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Country(warning) => write!(f, "{warning}"),
Self::CountryShouldBeAlpha2 => {
f.write_str("The `$.country_code` field should be an alpha-2 country code.")
}
Self::Currency(warning) => write!(f, "{warning}"),
Self::DateTime(warning) => write!(f, "{warning}"),
Self::Decode(warning) => write!(f, "{warning}"),
Self::Duration(warning) => write!(f, "{warning}"),
Self::Money(warning) => write!(f, "{warning}"),
Self::NoPeriods => f.write_str("The CDR has no charging periods"),
Self::Number(warning) => write!(f, "{warning}"),
Self::PeriodsOutsideStartEndDateTime {
cdr_range: Range { start, end },
period_range,
} => {
write!(
f,
"The CDR's charging period time range is not contained within the `start_date_time` \
and `end_date_time`; cdr: [start: {start}, end: {end}], period: {period_range}",
)
}
Self::String(warning) => write!(f, "{warning}"),
Self::Rejected => f.write_str(
"The schema IR for a CDR object was rejected; see the schema validation warnings.",
),
}
}
}
impl crate::Warning for Warning {
fn id(&self) -> warning::Id {
match self {
Self::Country(warning) => warning.id(),
Self::CountryShouldBeAlpha2 => warning::Id::from_static("country_should_be_alpha_2"),
Self::Currency(warning) => warning.id(),
Self::DateTime(warning) => warning.id(),
Self::Decode(warning) => warning.id(),
Self::Duration(warning) => warning.id(),
Self::Money(warning) => warning.id(),
Self::NoPeriods => warning::Id::from_static("no_periods"),
Self::Number(warning) => warning.id(),
Self::PeriodsOutsideStartEndDateTime {
cdr_range: _,
period_range: _,
} => warning::Id::from_static("periods_outside_start_end_date_time"),
Self::String(warning) => warning.id(),
Self::Rejected => warning::Id::from_static("rejected"),
}
}
fn is_rejected(&self) -> bool {
matches!(self, Self::Rejected)
}
}
impl From<warning::Rejected> for Warning {
fn from(_: warning::Rejected) -> Self {
Self::Rejected
}
}
from_warning_all!(
country::Warning => Warning::Country,
currency::Warning => Warning::Currency,
datetime::Warning => Warning::DateTime,
duration::Warning => Warning::Duration,
json::decode::Warning => Warning::Decode,
money::Warning => Warning::Money,
number::Warning => Warning::Number,
string::Warning => Warning::String
);
#[derive(Clone)]
pub struct Checked<'buf> {
doc: json::Document<'buf>,
version: Version<'buf>,
}
impl fmt::Debug for Checked<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
match &self.version {
Version::V211(cdr) => fmt::Debug::fmt(&cdr, f),
Version::V221(cdr) => fmt::Debug::fmt(&cdr, f),
}
} else {
match &self.version {
Version::V211(_) => f.write_str("V211"),
Version::V221(_) => f.write_str("V221"),
}
}
}
}
impl version::Versioned for Checked<'_> {
fn version(&self) -> crate::Version {
match self.version {
Version::V211(_) => crate::Version::V211,
Version::V221(_) => crate::Version::V221,
}
}
}
impl<'buf> Checked<'buf> {
pub(crate) fn lower_to_v221(
&self,
warnings: &mut dyn warning::Gather<Warning>,
) -> Result<price::v221::Cdr, warning::Error<Warning>> {
let cdr = match &self.version {
Version::V211(cdr) => {
let cdr = price::v211::Cdr::from_schema(cdr, warnings)?;
price::v221::Cdr::from(cdr)
}
Version::V221(cdr) => price::v221::Cdr::from_schema(cdr, warnings)?,
};
if cdr.charging_periods.is_empty() {
return Err(warning::Error::new(self.as_element(), Warning::NoPeriods));
}
let cdr_range = cdr.start_date_time..cdr.end_date_time;
let period_range = match cdr.charging_periods.as_slice() {
[] => None,
[period] => Some(PeriodRange::Single(period.start_date_time)),
[earliest, .., latest] => Some(PeriodRange::Many(
earliest.start_date_time..latest.start_date_time,
)),
};
let outside = match &period_range {
None => false,
Some(PeriodRange::Single(start)) => !cdr_range.contains(start),
Some(PeriodRange::Many(range)) => {
!(cdr_range.contains(&range.start) && cdr_range.contains(&range.end))
}
};
if let (true, Some(period_range)) = (outside, period_range) {
warnings.insert(
self.as_element(),
Warning::PeriodsOutsideStartEndDateTime {
cdr_range,
period_range,
},
);
}
Ok(cdr)
}
pub(crate) fn tariffs_to_v221(
&self,
warnings: &mut dyn warning::Gather<tariff::Warning>,
) -> Result<Vec<tariff::Tariff<'buf>>, warning::Error<tariff::Warning>> {
let mut built = Vec::new();
match &self.version {
Version::V211(cdr) => {
let Some(tariffs) = warnings.ok_or_reject(&cdr.tariffs)? else {
return Ok(built);
};
let items = tariffs.element().value().as_array().unwrap_or(&[]);
for (index, tariff) in tariffs.into_iter().enumerate() {
let tariff = warnings.ok_or_reject(tariff)?;
let lowered = tariff::v211::Tariff::from_schema(tariff, warnings)?;
let lowered = tariff::v221::Tariff::from(lowered);
let element = items.get(index).unwrap_or(tariffs.element());
let tariff = with_element(lowered, element)?;
built.push(tariff);
}
}
Version::V221(cdr) => {
let Some(tariffs) = warnings.ok_or_reject(&cdr.tariffs)? else {
return Ok(built);
};
let items = tariffs.element().value().as_array().unwrap_or(&[]);
for (index, tariff) in tariffs.into_iter().enumerate() {
let tariff = warnings.ok_or_reject(tariff)?;
let lowered = tariff::v221::Tariff::from_schema(tariff, warnings)?;
let element = items.get(index).unwrap_or(tariffs.element());
let tariff = with_element(lowered, element)?;
built.push(tariff);
}
}
}
Ok(built)
}
pub(crate) fn schema(&self) -> &Version<'buf> {
&self.version
}
pub fn into_doc(self) -> json::Document<'buf> {
self.doc
}
pub(crate) fn as_element(&self) -> &json::Element<'buf> {
self.doc.root()
}
pub fn as_doc(&self) -> &json::Document<'buf> {
&self.doc
}
pub fn as_json_str(&self) -> &'buf str {
self.doc.source()
}
}
#[expect(
clippy::large_enum_variant,
reason = "the v2.1.1 and v2.2.1 CDR IRs differ in size; this short-lived versioned \
value is not worth boxing"
)]
#[derive(Clone)]
pub(crate) enum Version<'buf> {
V211(schema::v211::Cdr<'buf>),
V221(schema::v221::Cdr<'buf>),
}
pub struct VersionedJson<'buf> {
doc: json::Document<'buf>,
version: crate::Version,
}
impl fmt::Debug for VersionedJson<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
fmt::Debug::fmt(&self.doc, f)
} else {
match self.version {
crate::Version::V211 => f.write_str("V211"),
crate::Version::V221 => f.write_str("V221"),
}
}
}
}
impl version::Versioned for VersionedJson<'_> {
fn version(&self) -> crate::Version {
self.version
}
}
impl<'buf> VersionedJson<'buf> {
pub(crate) fn new(element: json::Document<'buf>, version: crate::Version) -> Self {
Self {
doc: element,
version,
}
}
pub fn into_doc(self) -> json::Document<'buf> {
self.doc
}
pub fn as_doc(&self) -> &json::Document<'buf> {
&self.doc
}
pub fn as_json_str(&self) -> &'buf str {
self.doc.source()
}
}
#[derive(Debug)]
pub struct Unversioned<'buf> {
doc: json::Document<'buf>,
}
impl<'buf> Unversioned<'buf> {
pub(crate) fn new(doc: json::Document<'buf>) -> Self {
Self { doc }
}
pub fn into_doc(self) -> json::Document<'buf> {
self.doc
}
}
impl<'buf> version::Unversioned for Unversioned<'buf> {
type Versioned = VersionedJson<'buf>;
fn force_into_versioned(self, version: crate::Version) -> VersionedJson<'buf> {
let Self { doc } = self;
VersionedJson { doc, version }
}
}
fn with_element<'buf>(
tariff: tariff::v221::Tariff<'buf>,
element: &json::Element<'buf>,
) -> Result<tariff::Tariff<'buf>, warning::Error<tariff::Warning>> {
if tariff.elements.is_empty() {
return Err(warning::Error::new(element, tariff::Warning::NoElements));
}
Ok(tariff::Tariff::new(tariff, element.clone()))
}