use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use super::attachment::Attachment;
use super::macros::{tmf_struct, tmf_value};
tmf_value! {
pub struct Money {
unit: String,
@decimal {
value: Decimal,
}
}
}
impl Money {
pub fn new(unit: impl Into<String>, value: Decimal) -> Self {
Self::builder().unit(unit).value(value).build()
}
}
tmf_struct! {
@name = "Price";
pub struct Price {
duty_free_amount: Money,
tax_included_amount: Money,
@decimal {
tax_rate: Decimal,
percentage: Decimal,
}
}
}
tmf_value! {
pub struct Quantity {
units: String,
@decimal {
amount: Decimal,
}
}
}
tmf_value! {
pub struct Duration {
amount: i64,
units: String,
}
}
tmf_value! {
pub struct TimePeriod {
start_date_time: Timestamp,
end_date_time: Timestamp,
}
}
impl TimePeriod {
pub fn starting(start: impl Into<Timestamp>) -> Self {
Self::builder().start_date_time(start.into()).build()
}
pub fn until(end: impl Into<Timestamp>) -> Self {
Self::builder().end_date_time(end.into()).build()
}
pub fn between(start: impl Into<Timestamp>, end: impl Into<Timestamp>) -> Self {
Self::builder()
.start_date_time(start.into())
.end_date_time(end.into())
.build()
}
pub fn contains(&self, at: impl Into<Timestamp>) -> bool {
let at = at.into();
self.start_date_time.is_none_or(|s| at >= s) && self.end_date_time.is_none_or(|e| at < e)
}
}
pub type Timestamp = chrono::DateTime<chrono::FixedOffset>;
tmf_struct! {
@name = "TaxDefinition";
pub struct TaxDefinition {
id: String,
name: String,
tax_type: String,
jurisdiction_level: String,
jurisdiction_name: String,
valid_for: TimePeriod,
}
}
tmf_struct! {
@name = "TaxExemptionCertificate";
pub struct TaxExemptionCertificate {
id: String,
certificate_number: String,
issuing_jurisdiction: String,
reason: String,
tax_definition: Vec<TaxDefinition>,
valid_for: TimePeriod,
attachment: Attachment,
}
}
tmf_struct! {
@name = "RelatedPlaceRefOrValue";
pub struct RelatedPlace {
place: PlaceRefOrValue,
role: String,
}
}
tmf_struct! {
@name = "CreditProfile";
pub struct CreditProfile {
id: String,
href: String,
credit_profile_date: Timestamp,
credit_score: i64,
credit_risk_rating: i64,
valid_for: TimePeriod,
}
}
tmf_struct! {
@name = "TaxItem";
pub struct TaxItem {
tax_category: String,
tax_amount: Money,
@decimal {
tax_rate: Decimal,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum TaskState {
#[serde(rename = "acknowledged")]
Acknowledged,
#[serde(rename = "rejected")]
Rejected,
#[serde(rename = "inProgress")]
InProgress,
#[serde(rename = "cancelled")]
Cancelled,
#[serde(rename = "done")]
Done,
#[serde(rename = "terminatedWithError")]
TerminatedWithError,
#[serde(untagged)]
Other(String),
}
impl TaskState {
#[must_use]
pub fn is_finished(&self) -> bool {
matches!(
self,
Self::Done | Self::Rejected | Self::Cancelled | Self::TerminatedWithError
)
}
#[must_use]
pub fn is_success(&self) -> bool {
matches!(self, Self::Done)
}
}
tmf_struct! {
@name = "PlaceRefOrValue", @ref = "PlaceRef";
pub struct PlaceRefOrValue {
id: String,
href: String,
name: String,
@renamed {
"@referredType" referred_type: String,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum FeatureRelationshipType {
#[serde(rename = "excluded")]
Excluded,
#[serde(rename = "includes")]
Includes,
#[serde(rename = "may include")]
MayInclude,
#[serde(rename = "requires")]
Requires,
#[serde(untagged)]
Other(String),
}
pub mod decimal_opt {
use std::fmt;
use std::str::FromStr;
use rust_decimal::Decimal;
use rust_decimal::prelude::ToPrimitive;
use serde::de::{self, Visitor};
use serde::{Deserializer, Serializer};
pub fn serialize<S: Serializer>(
value: &Option<Decimal>,
serializer: S,
) -> Result<S::Ok, S::Error> {
let Some(d) = value else {
return serializer.serialize_none();
};
if d.is_integer() {
if let Some(i) = d.to_i64() {
return serializer.serialize_i64(i);
}
if let Some(u) = d.to_u64() {
return serializer.serialize_u64(u);
}
}
serializer.serialize_f64(
d.to_string()
.parse::<f64>()
.map_err(serde::ser::Error::custom)?,
)
}
pub fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Option<Decimal>, D::Error> {
struct V;
impl<'de> Visitor<'de> for V {
type Value = Option<Decimal>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a number or numeric string")
}
fn visit_f64<E: de::Error>(self, v: f64) -> Result<Self::Value, E> {
Decimal::from_str(&v.to_string())
.map(Some)
.map_err(de::Error::custom)
}
fn visit_i64<E: de::Error>(self, v: i64) -> Result<Self::Value, E> {
Ok(Some(Decimal::from(v)))
}
fn visit_u64<E: de::Error>(self, v: u64) -> Result<Self::Value, E> {
Ok(Some(Decimal::from(v)))
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
Decimal::from_str(v).map(Some).map_err(de::Error::custom)
}
fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_some<D: Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
d.deserialize_any(V)
}
}
deserializer.deserialize_option(V)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
#[test]
fn a_feature_relationship_type_keeps_the_space_the_wire_has() {
let value = FeatureRelationshipType::MayInclude;
assert_eq!(serde_json::to_string(&value).unwrap(), r#""may include""#);
assert_eq!(
serde_json::from_str::<FeatureRelationshipType>(r#""may include""#).unwrap(),
value
);
let unknown: FeatureRelationshipType = serde_json::from_str(r#""supersedes""#).unwrap();
assert_eq!(unknown, FeatureRelationshipType::Other("supersedes".into()));
assert_eq!(serde_json::to_string(&unknown).unwrap(), r#""supersedes""#);
}
#[test]
fn money_accepts_number_and_string() {
let a: Money = serde_json::from_str(r#"{"unit":"EUR","value":12.34}"#).unwrap();
let b: Money = serde_json::from_str(r#"{"unit":"EUR","value":"12.34"}"#).unwrap();
assert_eq!(a.value, b.value);
assert_eq!(a.value, Some(Decimal::from_str("12.34").unwrap()));
}
#[test]
fn money_emits_json_number() {
let m = Money::new("EUR", Decimal::from_str("12.34").unwrap());
assert_eq!(
serde_json::to_string(&m).unwrap(),
r#"{"unit":"EUR","value":12.34}"#
);
}
#[test]
fn integral_money_stays_integral() {
let m: Money = serde_json::from_str(r#"{"unit":"EUR","value":50}"#).unwrap();
assert_eq!(
serde_json::to_string(&m).unwrap(),
r#"{"unit":"EUR","value":50}"#,
"50 must not come back as 50.0"
);
}
#[test]
fn value_objects_keep_the_type_their_examples_send() {
let json = r#"{"amount":30,"units":"day","@type":"Duration"}"#;
let d: Duration = serde_json::from_str(json).unwrap();
assert_eq!(d.extensions.get("@type").unwrap(), "Duration");
assert_eq!(
serde_json::to_value(&d).unwrap(),
serde_json::from_str::<serde_json::Value>(json).unwrap()
);
}
#[test]
fn a_timestamp_keeps_the_offset_it_arrived_with() {
let json = r#""2020-09-23T16:42:23-04:00""#;
let t: Timestamp = serde_json::from_str(json).unwrap();
assert_eq!(serde_json::to_string(&t).unwrap(), json);
}
#[test]
fn a_task_state_answers_the_same_question_its_siblings_do() {
for state in [
TaskState::Done,
TaskState::Rejected,
TaskState::Cancelled,
TaskState::TerminatedWithError,
] {
assert!(state.is_finished(), "{state:?}");
}
for state in [TaskState::Acknowledged, TaskState::InProgress] {
assert!(!state.is_finished(), "{state:?}");
}
let unknown: TaskState = serde_json::from_str(r#""awaitingApproval""#).unwrap();
assert_eq!(unknown, TaskState::Other("awaitingApproval".into()));
assert!(!unknown.is_finished());
assert!(TaskState::Done.is_success());
assert!(!TaskState::Cancelled.is_success());
}
#[test]
fn time_period_containment_is_half_open() {
let start = Timestamp::from_str("2020-01-01T00:00:00Z").unwrap();
let end = Timestamp::from_str("2021-01-01T00:00:00Z").unwrap();
let p = TimePeriod::between(start, end);
assert!(p.contains(start));
assert!(!p.contains(end));
}
}
tmf_struct! {
@name = "Note";
pub struct Note {
id: String,
author: String,
date: Timestamp,
text: String,
}
}
impl Note {
pub fn new(text: impl Into<String>) -> Self {
Self::builder().text(text).build()
}
}