refactor(router): include currency conversion utility functions as Currency methods (#1790)

This commit is contained in:
udev
2023-08-01 12:33:29 +05:30
committed by GitHub
parent d06adc705c
commit 2c9c8f081d
5 changed files with 73 additions and 74 deletions

View File

@ -1,3 +1,5 @@
use std::num::TryFromIntError;
use router_derive;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
@ -289,6 +291,40 @@ pub enum Currency {
}
impl Currency {
/// Convert the amount to its base denomination based on Currency and return String
pub fn to_currency_base_unit(&self, amount: i64) -> Result<String, TryFromIntError> {
let amount_f64 = self.to_currency_base_unit_asf64(amount)?;
Ok(format!("{amount_f64:.2}"))
}
/// Convert the amount to its base denomination based on Currency and return f64
pub fn to_currency_base_unit_asf64(&self, amount: i64) -> Result<f64, TryFromIntError> {
let amount_f64: f64 = u32::try_from(amount)?.into();
let amount = if self.is_zero_decimal_currency() {
amount_f64
} else if self.is_three_decimal_currency() {
amount_f64 / 1000.00
} else {
amount_f64 / 100.00
};
Ok(amount)
}
/// Convert the amount to its base denomination based on Currency and check for zero decimal currency and return String
/// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies.
/// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/
pub fn to_currency_base_unit_with_zero_decimal_check(
&self,
amount: i64,
) -> Result<String, TryFromIntError> {
let amount_f64 = self.to_currency_base_unit_asf64(amount)?;
if self.is_zero_decimal_currency() {
Ok(amount_f64.to_string())
} else {
Ok(format!("{amount_f64:.2}"))
}
}
pub fn iso_4217(&self) -> &'static str {
match *self {
Self::AED => "784",