use rust_decimal::Decimal;
use serde_json::Value;
use std::sync::Arc;
use crate::error::{IssueCode, PathSegment, StringValidation, VldError, absent_field_error};
use crate::primitives::ZDecimal;
use crate::primitives::decimal::scale_too_big;
use crate::primitives::minor_units;
use crate::schema::VldSchema;
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Money {
pub amount: Decimal,
pub currency: String,
}
#[derive(Clone)]
pub struct ZMoney {
amount: ZDecimal,
currencies: Option<Vec<String>>,
messages: crate::primitives::Messages,
}
impl ZMoney {
pub fn new() -> Self {
Self {
amount: ZDecimal::new(),
currencies: None,
messages: None,
}
}
pub fn amount(mut self, schema: ZDecimal) -> Self {
self.amount = schema;
self
}
pub fn currencies(mut self, codes: &[&str]) -> Self {
for c in codes {
assert!(minor_units(c).is_some(), "Unknown ISO 4217 code: {}", c);
}
self.currencies = Some(codes.iter().map(|c| c.to_string()).collect());
self
}
pub fn with_messages<F>(mut self, f: F) -> Self
where
F: Fn(&str) -> Option<String> + Send + Sync + 'static,
{
let f = Arc::new(f);
let g = f.clone();
self.amount = self.amount.with_messages(move |k| g(k));
self.messages = Some(f);
self
}
fn currency(&self, value: &Value) -> Result<(String, u32), VldError> {
let code = value
.as_str()
.ok_or_else(|| crate::primitives::type_error(&None, "string", value))?;
let msg = self.messages.as_ref().and_then(|f| f("currency"));
let units = minor_units(code).ok_or_else(|| {
let code = IssueCode::InvalidString {
validation: StringValidation::Currency,
};
crate::error::issue_error(code, msg.as_ref(), value)
})?;
if let Some(allowed) = self
.currencies
.as_ref()
.filter(|a| !a.iter().any(|c| c == code))
{
let code = IssueCode::InvalidEnumValue {
options: allowed.clone(),
};
return Err(crate::error::issue_error(code, msg.as_ref(), value));
}
Ok((code.to_string(), units))
}
}
impl Default for ZMoney {
fn default() -> Self {
Self::new()
}
}
fn field<T>(
obj: &serde_json::Map<String, Value>,
key: &str,
parse: impl Fn(&Value) -> Result<T, VldError>,
) -> Result<T, VldError> {
match obj.get(key) {
Some(v) => parse(v),
None => Err(absent_field_error(
parse(&Value::Null).err().unwrap_or_default(),
)),
}
.map_err(|e| e.with_prefix(PathSegment::Field(key.to_string())))
}
impl VldSchema for ZMoney {
type Output = Money;
fn parse_value(&self, value: &Value) -> Result<Money, VldError> {
let obj = crate::error::expect_object(value)?;
let currency = field(obj, "currency", |v| self.currency(v));
let amount = field(obj, "amount", |v| {
let n = self.amount.parse_value(v)?;
match ¤cy {
Ok((_, units)) if n.scale() > *units => {
Err(self.amount.fail("max_scale", scale_too_big(*units), v))
}
_ => Ok(n),
}
});
match (amount, currency) {
(Ok(amount), Ok((currency, _))) => Ok(Money { amount, currency }),
(a, c) => Err(a
.err()
.unwrap_or_default()
.merge(c.err().unwrap_or_default())),
}
}
}
#[cfg(feature = "openapi")]
impl crate::openapi::JsonSchema for ZMoney {
fn json_schema(&self) -> Value {
let currency = match &self.currencies {
Some(c) => serde_json::json!({"type": "string", "enum": c}),
None => serde_json::json!({"type": "string", "format": "currency-code"}),
};
serde_json::json!({
"type": "object",
"properties": {"amount": self.amount.json_schema(), "currency": currency},
"required": ["amount", "currency"],
"x-money": true,
})
}
}
#[cfg(feature = "openapi")]
impl crate::openapi::CollectNestedSchemas for ZMoney {}