diff --git a/src/types/currency.rs b/src/types/currency.rs index c476512..e005242 100644 --- a/src/types/currency.rs +++ b/src/types/currency.rs @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: AGPL-3.0-or-later -use std::str::FromStr; +use std::{ops::Add, str::FromStr}; use async_trait::async_trait; use cqrs_es::Aggregate; @@ -62,6 +62,16 @@ impl Price { } } +impl Add for Price { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { + let self_minor = self.major_as_minor() + self.minor; + let rhs_minor = rhs.major_as_minor() + rhs.minor; + + Self::from_minor(self_minor + rhs_minor, self.currency) + } +} + #[cfg(test)] mod tests { use super::*; @@ -110,4 +120,70 @@ mod tests { } ); } + + #[test] + fn test_price_add() { + let a = Price { + minor: 10, + major: 100, + currency: Currency::INR, + }; + + let b = Price { + minor: 1, + major: 200, + currency: Currency::INR, + }; + + assert_eq!( + a + b, + Price { + minor: 11, + major: 300, + currency: Currency::INR + } + ); + } + + #[test] + fn test_price_add_zero() { + let a = Price { + minor: 0, + major: 0, + currency: Currency::INR, + }; + + assert_eq!( + a.clone() + a, + Price { + minor: 0, + major: 0, + currency: Currency::INR + } + ); + } + + #[test] + fn test_price_add_overflow() { + let a = Price { + minor: 80, + major: 100, + currency: Currency::INR, + }; + + let b = Price { + minor: 80, + major: 200, + currency: Currency::INR, + }; + + assert_eq!( + a + b, + Price { + minor: 60, + major: 301, + currency: Currency::INR + } + ); + } }