use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use super::attachment::Attachment;
use super::macros::{tmf_struct, tmf_value};
use super::time::Timestamp;
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)
}
}
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),
}
#[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_is_exact_or_rejected() {
for (wire, expected) in [
("9007199254740992.01", "9007199254740992.01"),
("-9007199254740992.01", "-9007199254740992.01"),
(
"79228162514264337593543950335",
"79228162514264337593543950335",
),
(
"-79228162514264337593543950335",
"-79228162514264337593543950335",
),
("11.90", "11.9"),
("0", "0"),
("10e-29", "0.0000000000000000000000000001"),
("900719925474099201e-2", "9007199254740992.01"),
("0e9999999999999999999999999", "0"),
] {
let exact = Decimal::from_str_exact(expected).unwrap();
for token in [wire.to_owned(), format!(r#""{wire}""#)] {
let money: Money =
serde_json::from_str(&format!(r#"{{"value":{token}}}"#)).unwrap();
assert_eq!(money.value, Some(exact), "{token}");
}
let value = serde_json::to_value(Money::new("EUR", exact)).unwrap();
assert_eq!(value["value"].as_number().unwrap().as_str(), expected);
}
for token in [
"1e-29",
"1e99999999999999999999",
"79228162514264337593543950336",
"11.90000000000000000000000000001",
"true",
"{}",
"[]",
r#""NaN""#,
] {
assert!(
serde_json::from_str::<Money>(&format!(r#"{{"value":{token}}}"#)).is_err(),
"{token}"
);
}
for wire in ["{}", r#"{"value":null}"#] {
assert_eq!(serde_json::from_str::<Money>(wire).unwrap().value, None);
}
}
#[test]
fn money_in_an_untagged_envelope_keeps_its_numeric_token() {
#[derive(Deserialize)]
#[serde(untagged)]
enum Entry {
Amount(Money),
Empty,
}
let Entry::Amount(money) =
serde_json::from_str(r#"{"value":9007199254740992.01}"#).unwrap()
else {
panic!("expected money");
};
assert_eq!(money.value, Some("9007199254740992.01".parse().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()
}
}