checkout_core 0.0.147

core traits and structs for the checkout_controller crate
Documentation
use rust_decimal::prelude::*;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize, JsonSchema)]
pub struct Money {
    pub currency: Currency,
    pub amount: Decimal,
}

impl Money {
    pub fn new(currency: Currency, amount: &str) -> Self {
        let mut amount = Decimal::from_str(amount).unwrap();
        amount.rescale(currency.scale);

        Self { currency, amount }
    }

    pub fn add(&self, money: &Money) -> Money {
        if self.currency.iso_code != money.currency.iso_code {
            panic!("mismatched currencies: can't add units of different currencies")
        }

        Money {
            currency: self.currency.clone(),
            amount: self.amount + money.amount,
        }
    }

    pub fn sub(&self, money: &Money) -> Money {
        if self.currency.iso_code != money.currency.iso_code {
            panic!("mismatched currencies: can't subtract units of different currencies")
        }

        Money {
            currency: self.currency.clone(),
            amount: self.amount - money.amount,
        }
    }

    pub fn mul(&self, factor: &Decimal) -> Money {
        Money {
            currency: self.currency.clone(),
            amount: self.amount * factor,
        }
    }

    pub fn div(&self, factor: &Decimal) -> Money {
        Money {
            currency: self.currency.clone(),
            amount: self.amount / factor,
        }
    }
}

#[derive(Clone, Serialize, Deserialize, JsonSchema)]
pub struct Currency {
    pub iso_code: String,
    pub scale: u32,
}

impl Currency {
    pub fn new(iso_code: &str, scale: u32) -> Self {
        Self {
            iso_code: iso_code.to_string(),
            scale,
        }
    }
}