Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
refactor(payments): changed formula for interest calculation for card installments (#11680)
Muditbhatia12b1146c2f9f59
diff --git a/Cargo.lock b/Cargo.lockindex cdd1853f4e..0f7de3dea8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -474,6 +474,7 @@ dependencies = ["nutype","reqwest 0.11.27","router_derive",+ "rust_decimal","serde","serde_json","smithy",@@ -2126,6 +2127,7 @@ dependencies = ["error-stack 0.4.1","euclid","hyperswitch_masking",+ "rust_decimal","serde","serde_json","smithy",diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.tomlindex 4227d1a8e5..21748b709f 100644--- a/crates/api_models/Cargo.toml+++ b/crates/api_models/Cargo.toml@@ -28,6 +28,7 @@ actix-web = { version = "4.11.0", optional = true }csv = "1.3"error-stack = "0.4.1"mime = "0.3.17"+rust_decimal = "1.37"reqwest = { version = "0.11.27", optional = true }serde = { version = "1.0.219", features = ["derive"] }serde_json = "1.0.140"diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex b4728b05e2..f5b44cbfb0 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -18,6 +18,10 @@ use common_utils::{};use error_stack::ResultExt;use hyperswitch_masking::PeekInterface;+use rust_decimal::{+ prelude::{FromPrimitive, ToPrimitive},+ Decimal,+};use serde::de;use utoipa::ToSchema;@@ -2632,11 +2636,30 @@ impl PaymentMethodListInstallmentPlan {.map(|&count| {let interest = data.interest_rate- .apply_and_ceil_result(order_amount)+ .calculate_emi_interest(order_amount, count).change_context(errors::ParsingError::UnknownError).attach_printable("Failed to apply installment interest rate")?;let total_with_interest = net_amount + interest;- let per_installment = total_with_interest / count;++ let total_decimal = Decimal::from_i64(total_with_interest.get_amount_as_i64())+ .ok_or(errors::ParsingError::UnknownError)+ .map_err(error_stack::Report::from)+ .attach_printable("Failed to convert total amount to decimal")?;++ let count_decimal = Decimal::from_u8(u8::from(count))+ .ok_or(errors::ParsingError::UnknownError)+ .map_err(error_stack::Report::from)+ .attach_printable("Failed to convert count to decimal")?;++ // - ceil() ensures merchant always receives at least the calculated interest+ let per_installment = MinorUnit::new(+ (total_decimal / count_decimal)+ .ceil()+ .to_i64()+ .ok_or(errors::ParsingError::UnknownError)+ .map_err(error_stack::Report::from)+ .attach_printable("Failed to convert per installment to i64")?,+ );let amount_per_installment = per_installment.to_major_unit_as_f64(currency).change_context(errors::ParsingError::UnknownError)diff --git a/crates/common_types/Cargo.toml b/crates/common_types/Cargo.tomlindex 3b4b28e901..d0ee8887c5 100644--- a/crates/common_types/Cargo.toml+++ b/crates/common_types/Cargo.toml@@ -20,6 +20,7 @@ utoipa = { version = "4.2.3", features = ["preserve_order", "preserve_path_ordertime = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }error-stack = "0.4.1"cpf_cnpj = "0.3"+rust_decimal = { version = "1.37", features = ["maths"] }common_enums = { version = "0.1.0", path = "../common_enums" }common_utils = { version = "0.1.0", path = "../common_utils"}diff --git a/crates/common_types/src/consts.rs b/crates/common_types/src/consts.rsindex 320ab704a7..027cd94d70 100644--- a/crates/common_types/src/consts.rs+++ b/crates/common_types/src/consts.rs@@ -1,5 +1,8 @@//! Constants that are used in the domain level.+/// Base value for converting percentage to decimal (e.g., 12% → 0.12)+pub const PERCENTAGE_BASE: f64 = 100.0;+/// API version#[cfg(feature = "v1")]pub const API_VERSION: common_enums::ApiVersion = common_enums::ApiVersion::V1;diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rsindex df35c59106..938a1ea89d 100644--- a/crates/common_types/src/payments.rs+++ b/crates/common_types/src/payments.rs@@ -19,12 +19,19 @@ use euclid::frontend::{dir::{DirKeyKind, EuclidDirFilter},};use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};+use rust_decimal::{+ prelude::{FromPrimitive, ToPrimitive},+ Decimal, MathematicalOps,+};use serde::{Deserialize, Serialize};use smithy::SmithyModel;use time::PrimitiveDateTime;use utoipa::ToSchema;-use crate::domain::{AdyenSplitData, PostCaptureVoidData, XenditSplitSubMerchantData};+use crate::{+ consts::PERCENTAGE_BASE,+ domain::{AdyenSplitData, PostCaptureVoidData, XenditSplitSubMerchantData},+};#[derive(Serialize,Deserialize,@@ -1311,35 +1318,49 @@ impl TryFrom<Vec<NonZeroU8>> for InstallmentCounts {pub struct InstallmentInterestRate(f64);impl InstallmentInterestRate {- /// apply the interest rate to amount and ceil the result- pub fn apply_and_ceil_result(+ /// Calculate the total EMI interest for a given principal and number of installments+ pub fn calculate_emi_interest(&self,amount: MinorUnit,+ number_of_installments: NonZeroU8,) -> errors::CustomResult<MinorUnit, errors::InstallmentInterestRateError> {- let max_amount = i64::MAX / 10000;- let amount = amount.get_amount_as_i64();- if amount > max_amount {- // value gets rounded off after i64::MAX/10000- Err(error_stack::report!(- errors::InstallmentInterestRateError::UnableToApplyInterestRate- ))- .attach_printable(format!(- "Cannot calculate interest rate for amount greater than {max_amount}",- ))+ let amount_decimal = Decimal::from_i64(amount.get_amount_as_i64())+ .ok_or(errors::InstallmentInterestRateError::UnableToApplyInterestRate)+ .map_err(Report::from)+ .attach_printable("Failed to convert amount to decimal")?;++ let rate_decimal = Decimal::from_f64(self.0 / PERCENTAGE_BASE)+ .ok_or(errors::InstallmentInterestRateError::UnableToApplyInterestRate)+ .map_err(Report::from)+ .attach_printable("Failed to convert interest rate to decimal")?;++ let n_decimal = Decimal::from_u8(u8::from(number_of_installments))+ .ok_or(errors::InstallmentInterestRateError::UnableToApplyInterestRate)+ .map_err(Report::from)+ .attach_printable("Failed to convert number of installments to decimal")?;+ // Formula: Total Interest = (EMI × n) - P+ // where:+ // EMI = (P × r × (1 + r)^n) / ((1 + r)^n - 1)+ // P = principal amount+ // r = interest rate+ // n = number of installments+ let total_interest = if rate_decimal.is_zero() {+ Decimal::ZERO} else {- let amount_f64 = amount- .to_string()- .parse::<f64>()- .change_context(errors::InstallmentInterestRateError::UnableToApplyInterestRate)- .attach_printable("Failed to parse amount as f64")?;- let ceiled = (amount_f64 * (self.0 / 100.0)).ceil();- let result = ceiled- .to_string()- .parse::<i64>()- .change_context(errors::InstallmentInterestRateError::UnableToApplyInterestRate)- .attach_printable("Failed to parse ceiled result as i64")?;- Ok(MinorUnit::new(result))- }+ let one = Decimal::ONE;+ let factor = (one + rate_decimal).powd(n_decimal);+ let emi = (amount_decimal * rate_decimal * factor) / (factor - one);+ emi * n_decimal - amount_decimal+ };+ // - ceil() ensures merchant always receives at least the calculated interest+ let result = total_interest+ .ceil()+ .to_i64()+ .ok_or(errors::InstallmentInterestRateError::UnableToApplyInterestRate)+ .map_err(Report::from)+ .attach_printable("Failed to convert interest result to i64")?;++ Ok(MinorUnit::new(result))}fn is_valid_precision_length(value: &str) -> bool {diff --git a/crates/common_types/tests/payments_test.rs b/crates/common_types/tests/payments_test.rsnew file mode 100644index 0000000000..142253ab9a--- /dev/null+++ b/crates/common_types/tests/payments_test.rs@@ -0,0 +1,40 @@+use std::num::NonZeroU8;++use common_types::payments::InstallmentInterestRate;+use common_utils::types::MinorUnit;++#[test]+fn test_calculate_emi_interest_with_zero_rate() {+ let rate = InstallmentInterestRate::try_from(0.0).unwrap();+ let amount = MinorUnit::new(10000);+ let installments = NonZeroU8::new(12).unwrap();++ let result = rate.calculate_emi_interest(amount, installments).unwrap();+ assert_eq!(result.get_amount_as_i64(), 0);+}++#[test]+fn test_calculate_emi_interest_consistency() {+ let rate = InstallmentInterestRate::try_from(10.0).unwrap();+ let amount = MinorUnit::new(50000);+ let installments = NonZeroU8::new(6).unwrap();++ let result1 = rate.calculate_emi_interest(amount, installments).unwrap();+ let result2 = rate.calculate_emi_interest(amount, installments).unwrap();+ assert_eq!(result1, result2);+}++#[test]+fn test_calculate_emi_interest_known_value() {+ let rate = InstallmentInterestRate::try_from(12.0).unwrap();+ let amount = MinorUnit::new(100000);+ let installments = NonZeroU8::new(12).unwrap();++ let result = rate.calculate_emi_interest(amount, installments).unwrap();+ assert_eq!(result.get_amount_as_i64(), 93725);+}++#[test]+fn test_installment_interest_rate_try_from_negative() {+ assert!(InstallmentInterestRate::try_from(-1.0).is_err());+}diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 60d1d3a7aa..74738f2e49 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -2271,9 +2271,10 @@ wherepub fn calculate_installment_interest(order_amount: MinorUnit,interest_rate: common_types::payments::InstallmentInterestRate,+ number_of_installments: std::num::NonZeroU8,) -> RouterResult<MinorUnit> {interest_rate- .apply_and_ceil_result(order_amount)+ .calculate_emi_interest(order_amount, number_of_installments).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to calculate installment interest")}@@ -2320,6 +2321,7 @@ wherelet total_interest = calculate_installment_interest(payment_data.payment_attempt.net_amount.get_order_amount(),installment_option_data.interest_rate,+ selected_installment.number_of_installments,)?;payment_datadiff --git a/cypress-tests/cypress/e2e/configs/Payment/Adyen.js b/cypress-tests/cypress/e2e/configs/Payment/Adyen.jsindex 24f1eea853..9f3853d77e 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Adyen.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Adyen.js@@ -788,7 +788,7 @@ export const connectorDetails = {status: 200,body: {status: "succeeded",- net_amount: 6300,+ net_amount: 6610,},},},@@ -1054,8 +1054,8 @@ export const connectorDetails = {billing_frequency: "month",interest_rate: 5,amount_details: {- amount_per_installment: 21,- total_amount: 63,+ amount_per_installment: 22.04,+ total_amount: 66.1,},},{@@ -1063,8 +1063,8 @@ export const connectorDetails = {billing_frequency: "month",interest_rate: 5,amount_details: {- amount_per_installment: 10.5,- total_amount: 63,+ amount_per_installment: 11.83,+ total_amount: 70.93,},},{@@ -1072,8 +1072,8 @@ export const connectorDetails = {billing_frequency: "month",interest_rate: 5,amount_details: {- amount_per_installment: 5.25,- total_amount: 63,+ amount_per_installment: 6.77,+ total_amount: 81.24,},},],