delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
//! Currency-aware amounts.
//!
//! Every amount the API sends or accepts is in the **minor units** of some
//! currency, and the number of minor units in a major unit is not always 100.
//! JPY, KRW and VND have no fractional part at all; KWD, BHD and OMR have
//! three digits. A bare integer therefore does not mean anything until it is
//! paired with its currency, and treating one as if it were another is a 100×
//! error in the direction nobody notices until the month closes.
//!
//! So [`Money`] carries the currency with the amount, and every conversion to
//! a human-facing figure goes through [`currency_exponent`], which answers
//! `None` for a code it does not know rather than guessing two. A `None` is a
//! prompt to look the currency up — a guess is a silent miscalculation.
//!
//! Lives in `core`, so it is available in the `default-features = false`
//! build: a webhook payload carries amounts too.

use serde::{Deserialize, Serialize};

/// Currencies with **no** minor unit — one major unit is one minor unit.
///
/// ISO 4217 exponent 0.
const ZERO_EXPONENT: &[&str] = &[
    "BIF", "CLP", "DJF", "GNF", "ISK", "JPY", "KMF", "KRW", "PYG", "RWF", "UGX", "UYI", "VND",
    "VUV", "XAF", "XOF", "XPF",
];

/// Currencies with **three** minor digits — 1000 minor units per major unit.
///
/// ISO 4217 exponent 3.
const THREE_EXPONENT: &[&str] = &["BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND"];

/// Currencies with two minor digits. Listed explicitly rather than assumed as
/// a default, so an unrecognised code answers `None` instead of silently
/// behaving like a two-digit currency.
///
/// Superseded codes stay in the table beside their replacements — `ANG` next
/// to `XCG`, `ZWL` next to `ZWG` — because a settlement line written before
/// the changeover still carries the old code, and a statement that stopped
/// rendering when a currency was renamed would be a regression in the exact
/// place this module exists to protect. Adding a code is always safe;
/// removing one turns rendered history into `None`.
const TWO_EXPONENT: &[&str] = &[
    "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT",
    "BGN", "BMD", "BND", "BOB", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", "CAD", "CDF", "CHF",
    "CNY", "COP", "CRC", "CUP", "CVE", "CZK", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR",
    "FJD", "FKP", "GBP", "GEL", "GHS", "GIP", "GMD", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG",
    "HUF", "IDR", "ILS", "INR", "IRR", "JMD", "KES", "KGS", "KHR", "KPW", "KYD", "KZT", "LAK",
    "LBP", "LKR", "LRD", "LSL", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRU", "MUR",
    "MVR", "MWK", "MXN", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "PAB", "PEN",
    "PGK", "PHP", "PKR", "PLN", "QAR", "RON", "RSD", "RUB", "SAR", "SBD", "SCR", "SDG", "SEK",
    "SGD", "SHP", "SLE", "SOS", "SRD", "SSP", "STN", "SVC", "SYP", "SZL", "THB", "TJS", "TMT",
    "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "USD", "UZS", "VES", "WST", "XCD", "XCG", "YER",
    "ZAR", "ZMW", "ZWG", "ZWL",
];

/// How many decimal digits `currency`'s minor unit has: `2` for EUR, `0` for
/// JPY, `3` for KWD.
///
/// `None` means this SDK does not know the code — **do not fall back to 2**.
/// A wrong exponent is a factor-of-100 error in a money figure, and the
/// failure is silent: the number still looks like a plausible amount.
///
/// The comparison is case-insensitive; the API sends uppercase ISO 4217.
///
/// ```
/// use delopay::money::currency_exponent;
///
/// assert_eq!(currency_exponent("EUR"), Some(2));
/// assert_eq!(currency_exponent("jpy"), Some(0));
/// assert_eq!(currency_exponent("KWD"), Some(3));
/// assert_eq!(currency_exponent("XYZ"), None);
/// ```
#[must_use]
pub fn currency_exponent(currency: &str) -> Option<u32> {
    let code = currency.trim();
    if code.len() != 3 {
        return None;
    }
    let upper = code.to_ascii_uppercase();
    let matches = |set: &[&str]| set.iter().any(|c| *c == upper);
    if matches(ZERO_EXPONENT) {
        Some(0)
    } else if matches(THREE_EXPONENT) {
        Some(3)
    } else if matches(TWO_EXPONENT) {
        Some(2)
    } else {
        None
    }
}

/// An amount in the minor units of a currency, carried together.
///
/// Construct one from the two wire fields that belong together — never from
/// the integer alone:
///
/// ```
/// use delopay::money::Money;
///
/// let fee = Money::new(1999, "EUR");
/// assert_eq!(fee.to_major_string(), Some("19.99".to_string()));
///
/// // The same integer is a different amount in a zero-exponent currency.
/// assert_eq!(Money::new(1999, "JPY").to_major_string(), Some("1999".to_string()));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Money {
    /// The amount, in `currency`'s minor units. Signed: settlement
    /// adjustments and refunds are legitimately negative.
    pub amount: i64,
    /// ISO 4217 currency code, as the API sent it.
    pub currency: String,
}

impl Money {
    /// An amount of `amount` minor units in `currency`.
    pub fn new(amount: i64, currency: impl Into<String>) -> Self {
        Self {
            amount,
            currency: currency.into(),
        }
    }

    /// How many decimal digits this amount's minor unit has — see
    /// [`currency_exponent`]. `None` for a currency this SDK does not know.
    #[must_use]
    pub fn exponent(&self) -> Option<u32> {
        currency_exponent(&self.currency)
    }

    /// The amount rendered in major units, e.g. `1999 EUR` → `"19.99"`,
    /// `1999 JPY` → `"1999"`, `-500 USD` → `"-5.00"`.
    ///
    /// `None` when the currency's exponent is unknown, because rendering it
    /// would mean guessing where the decimal point goes.
    ///
    /// Decimal string rather than `f64` on purpose: a binary float cannot
    /// represent most decimal amounts exactly, and money that is off by a
    /// half-cent after a round trip is money that fails reconciliation.
    #[must_use]
    pub fn to_major_string(&self) -> Option<String> {
        let exponent = self.exponent()?;
        if exponent == 0 {
            return Some(self.amount.to_string());
        }
        let sign = if self.amount < 0 { "-" } else { "" };
        // `unsigned_abs` rather than `abs`: `i64::MIN.abs()` overflows.
        let magnitude = self.amount.unsigned_abs();
        let divisor = 10_u64.pow(exponent);
        let whole = magnitude / divisor;
        let fraction = magnitude % divisor;
        Some(format!(
            "{sign}{whole}.{fraction:0width$}",
            width = exponent as usize
        ))
    }

    /// Add two amounts of the same currency.
    ///
    /// `None` when the currencies differ (there is no exchange rate here) or
    /// the sum would overflow. Deliberately not `std::ops::Add`: an operator
    /// that can be wrong for a reason the caller must handle should not look
    /// infallible.
    #[must_use]
    pub fn checked_add(&self, other: &Self) -> Option<Self> {
        if !self.currency.eq_ignore_ascii_case(&other.currency) {
            return None;
        }
        Some(Self {
            amount: self.amount.checked_add(other.amount)?,
            currency: self.currency.clone(),
        })
    }
}

impl std::fmt::Display for Money {
    /// `"19.99 EUR"`, or `"1999 (minor units) XYZ"` when the exponent is
    /// unknown — an unknown currency prints an honest minor-unit figure
    /// rather than a plausible-looking wrong one.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.to_major_string() {
            Some(major) => write!(f, "{major} {}", self.currency),
            None => write!(f, "{} (minor units) {}", self.amount, self.currency),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn exponent_is_looked_up_not_defaulted() {
        assert_eq!(currency_exponent("USD"), Some(2));
        assert_eq!(currency_exponent("JPY"), Some(0));
        assert_eq!(currency_exponent("KWD"), Some(3));
        // The whole point: an unknown code is not silently two digits.
        assert_eq!(currency_exponent("XYZ"), None);
        assert_eq!(currency_exponent(""), None);
        assert_eq!(currency_exponent("EURO"), None);
    }

    #[test]
    fn a_renamed_currency_and_its_predecessor_both_resolve() {
        // A line written before the changeover carries the old code; one
        // written after carries the new. Both must render, or a statement
        // silently stops printing amounts it printed last month.
        assert_eq!(currency_exponent("ANG"), Some(2)); // → XCG, 2025
        assert_eq!(currency_exponent("XCG"), Some(2));
        assert_eq!(currency_exponent("ZWL"), Some(2)); // → ZWG, 2024
        assert_eq!(currency_exponent("ZWG"), Some(2));
    }

    #[test]
    fn exponent_lookup_is_case_and_space_insensitive() {
        assert_eq!(currency_exponent("jpy"), Some(0));
        assert_eq!(currency_exponent(" eur "), Some(2));
    }

    #[test]
    fn major_string_places_the_point_per_currency() {
        assert_eq!(
            Money::new(1999, "EUR").to_major_string().as_deref(),
            Some("19.99")
        );
        assert_eq!(
            Money::new(1999, "JPY").to_major_string().as_deref(),
            Some("1999")
        );
        assert_eq!(
            Money::new(1999, "KWD").to_major_string().as_deref(),
            Some("1.999")
        );
    }

    #[test]
    fn major_string_pads_the_fraction() {
        // 5 minor units is 0.05, not 0.5 — a mutation dropping the zero-pad
        // fails here.
        assert_eq!(
            Money::new(5, "USD").to_major_string().as_deref(),
            Some("0.05")
        );
        assert_eq!(
            Money::new(50, "USD").to_major_string().as_deref(),
            Some("0.50")
        );
    }

    #[test]
    fn major_string_keeps_the_sign_on_negatives() {
        assert_eq!(
            Money::new(-500, "USD").to_major_string().as_deref(),
            Some("-5.00")
        );
        assert_eq!(
            Money::new(-5, "USD").to_major_string().as_deref(),
            Some("-0.05")
        );
    }

    #[test]
    fn major_string_survives_i64_min() {
        // `abs()` would panic here; `unsigned_abs()` does not.
        assert!(Money::new(i64::MIN, "USD").to_major_string().is_some());
    }

    #[test]
    fn major_string_is_none_for_an_unknown_currency() {
        assert_eq!(Money::new(1999, "XYZ").to_major_string(), None);
    }

    #[test]
    fn add_refuses_to_mix_currencies() {
        let eur = Money::new(100, "EUR");
        let usd = Money::new(100, "USD");
        assert_eq!(eur.checked_add(&usd), None);
        assert_eq!(
            eur.checked_add(&Money::new(23, "eur")),
            Some(Money::new(123, "EUR"))
        );
    }

    #[test]
    fn add_refuses_to_overflow() {
        let big = Money::new(i64::MAX, "USD");
        assert_eq!(big.checked_add(&Money::new(1, "USD")), None);
    }

    #[test]
    fn display_never_prints_a_guessed_decimal_point() {
        assert_eq!(Money::new(1999, "EUR").to_string(), "19.99 EUR");
        assert_eq!(
            Money::new(1999, "XYZ").to_string(),
            "1999 (minor units) XYZ"
        );
    }
}