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
feat(superposition): add merchant-profile payout amount min max limits (#15179)
Sayak Bhattacharyaf30ddfc0ea67
diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex c2c146c877..c83fba01a3 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -2567,6 +2567,8 @@ client_session_validation_enabled = { value = true, schema = { type = "boolean""webhooks.unverified_webhook_profile_rate_limit" = { value = 0, schema = { maximum = 4294967295, minimum = 0, type = "integer" }, description = "Maximum unverified incoming webhooks per profile per window, 0 disables the profile level", change_reason = "Unverified webhook rate limiting" }"webhooks.unverified_webhook_merchant_connector_account_rate_limit" = { value = 0, schema = { maximum = 4294967295, minimum = 0, type = "integer" }, description = "Maximum unverified incoming webhooks per merchant connector account per window, 0 disables the merchant connector account level", change_reason = "Unverified webhook rate limiting" }"payouts.max_auto_payout_retries" = { value = 0, schema = { maximum = 4294967295, minimum = 0, type = "integer" }, description = "Maximum auto payout retries, differentiated by payout_retry_type dimension (single_connector or multi_connector)", change_reason = "Initial setup" }+"payouts.min_amount" = { value = 0, schema = { maximum = 999999999, minimum = 0, type = "integer" }, description = "Minimum payout amount in the currency's lowest denomination. Override with organization_id, processor_merchant_id, and profile_id to set scoped caps.", change_reason = "Add organization-merchant-profile-configurable payout minimum amount" }+"payouts.max_amount" = { value = 999999999, schema = { maximum = 999999999, minimum = 0, type = "integer" }, description = "Maximum payout amount in the currency's lowest denomination. Override with organization_id, processor_merchant_id, and profile_id to set scoped caps.", change_reason = "Add organization-merchant-profile-configurable payout maximum amount" }"payouts.payout_frm_call" = { value = false, schema = { type = "boolean" }, description = "Whether to call FRM for payouts", change_reason = "Initial setup" }"payouts.rerun_payout_frm_before_auto_retry" = { value = false, schema = { type = "boolean" }, description = "Whether to rerun payout FRM before automatic retries, overridable by the retry connector", change_reason = "Gate payout FRM reruns on automatic retries" }"payouts.payout_blocklist_guard" = { value = false, schema = { type = "boolean" }, description = "Whether to check card payouts against the blocklist and the profile's card blocking rules", change_reason = "Initial setup" }diff --git a/crates/external_services/src/superposition.rs b/crates/external_services/src/superposition.rsindex 3c83fb6a68..89a805bae7 100644--- a/crates/external_services/src/superposition.rs+++ b/crates/external_services/src/superposition.rs@@ -11,7 +11,7 @@ use api_models::superposition_proxy::{};pub use aws_smithy_types::DateTime;use aws_smithy_types::{Document, Number};-use common_utils::{errors::CustomResult, id_type::TargetingKey};+use common_utils::{errors::CustomResult, id_type::TargetingKey, types::MinorUnit};use error_stack::{report, ResultExt};use hyperswitch_masking::ExposeInterface;use serde_json::Map;@@ -660,6 +660,18 @@ impl GetValue<i64> for open_feature::Client {}}+impl GetValue<MinorUnit> for open_feature::Client {+ async fn get_value(+ &self,+ key: &str,+ context: &open_feature::EvaluationContext,+ ) -> Result<MinorUnit, open_feature::EvaluationError> {+ self.get_int_value(key, Some(context), None)+ .await+ .map(MinorUnit::new)+ }+}+impl GetValue<u32> for open_feature::Client {async fn get_value(&self,diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 90580959b0..2bd53014fc 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -518,6 +518,10 @@ pub mod superposition {pub const MAX_AUTO_PAYOUT_RETRIES: &str = "payouts.max_auto_payout_retries";/// Stops payout creation, confirmation, update, cancellation, and fulfillment at OMP scope.pub const PAYOUT_KILL_SWITCH: &str = "payouts.kill_switch";+ /// Minimum allowed payout amount configuration key+ pub const PAYOUT_MIN_AMOUNT: &str = "payouts.min_amount";+ /// Maximum allowed payout amount configuration key+ pub const PAYOUT_MAX_AMOUNT: &str = "payouts.max_amount";/// GSM payout call configuration key (scoped by merchant, profile, and payout retry type)pub const GSM_PAYOUT_CALL: &str = "payouts.gsm_payout_call";/// Disable vault tokenization configuration keydiff --git a/crates/router/src/core/configs.rs b/crates/router/src/core/configs.rsindex e47fbc7c48..4b5e082696 100644--- a/crates/router/src/core/configs.rs+++ b/crates/router/src/core/configs.rs@@ -1,7 +1,7 @@pub mod dimension_config;pub mod dimension_state;pub mod payment_callback;-use common_utils::errors::CustomResult;+use common_utils::{errors::CustomResult, types::MinorUnit};pub use dimension_config::{BlockImplicitCustomerCreation, EnableExtendedCardBin, ImplicitCustomerUpdate,PaymentBlocklistGuard, RequiresCvv, ShouldCallGsm, ShouldEnableMitWithLimitedCardData,@@ -107,6 +107,19 @@ impl ConfigType for i64 {}}+impl ConfigType for MinorUnit {+ fn from_config_str(config_str: &str) -> CustomResult<Self, errors::StorageError> {+ config_str+ .parse::<i64>()+ .map(Self::new)+ .change_context(errors::StorageError::DeserializationFailed)+ }++ fn to_config_string(&self) -> CustomResult<String, errors::StorageError> {+ Ok(self.get_amount_as_i64().to_string())+ }+}+impl ConfigType for u32 {fn from_config_str(config_str: &str) -> CustomResult<Self, errors::StorageError> {config_strdiff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex c1c9b31aed..fba307a39e 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -727,6 +727,30 @@ impl DatabaseBackedConfig for MaxAutoPayoutRetries {}}+config! {+ superposition_key = PAYOUT_MIN_AMOUNT,+ output = common_utils::types::MinorUnit,+ default = common_utils::types::MinorUnit::zero(),+ requires = dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndOrgIdAndProfileId,+ targeting_key = id_type::ProfileId+}++impl DatabaseBackedConfig for PayoutMinAmount {+ const KEY: &'static str = "payout_min_amount";+}++config! {+ superposition_key = PAYOUT_MAX_AMOUNT,+ output = common_utils::types::MinorUnit,+ default = common_utils::types::MinorUnit::new(crate::consts::MAX_ALLOWED_AMOUNT),+ requires = dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndOrgIdAndProfileId,+ targeting_key = id_type::ProfileId+}++impl DatabaseBackedConfig for PayoutMaxAmount {+ const KEY: &'static str = "payout_max_amount";+}+config! {superposition_key = POLL_CONFIG_EXTERNAL_THREE_DS,output = crate::types::PollConfig,diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rsindex 6c2f7f09f9..a9175ae125 100644--- a/crates/router/src/core/payouts/helpers.rs+++ b/crates/router/src/core/payouts/helpers.rs@@ -18,7 +18,10 @@ use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperatiuse hyperswitch_masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy};use router_env::logger;-use super::{validator::PayoutExecutionKindValidation, PayoutData};+use super::{+ validator::{self, PayoutExecutionKindValidation},+ PayoutData,+};#[cfg(feature = "v1")]use crate::core::payments::helpers as payments_helpers;#[cfg(feature = "payouts")]@@ -1453,6 +1456,26 @@ pub async fn update_payouts_and_payout_attempt(}));}+ let profile_id = payout_data.business_profile.get_id();+ let payout_cap_dimensions = dimension_state::Dimensions::new()+ .with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())+ .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())+ .with_organization_id(+ platform+ .get_processor()+ .get_account()+ .get_org_id()+ .to_owned(),+ )+ .with_profile_id(profile_id.clone());+ validator::validate_payout_amount_against_config(+ state,+ &payout_cap_dimensions,+ profile_id,+ req.amount,+ )+ .await?;+// Fetch customer details from request and create new or else use existing customer that was attachedlet customer = get_customer_details_from_request(req);let customer_id = if customer.customer_id.is_some()diff --git a/crates/router/src/core/payouts/proxy.rs b/crates/router/src/core/payouts/proxy.rsindex bc8e2f02bb..0922438de5 100644--- a/crates/router/src/core/payouts/proxy.rs+++ b/crates/router/src/core/payouts/proxy.rs@@ -558,8 +558,20 @@ impl ExternalVaultPayout<'_> {let platform = self.platform;let req = self.normalize_proxy_create_request(req)?;let payout_id = self.validate_proxy_create_identity(&req).await?;- let customer_id = req.get_customer_id().get_required_value("customer_id")?;let processor = platform.get_processor();+ let payout_cap_dimensions = dimension_state::Dimensions::new()+ .with_processor_merchant_id(processor.get_processor_merchant_id())+ .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())+ .with_organization_id(processor.get_account().get_org_id().to_owned())+ .with_profile_id(profile.get_id().clone());+ validator::validate_payout_amount_against_config(+ state,+ &payout_cap_dimensions,+ profile.get_id(),+ req.amount,+ )+ .await?;+ let customer_id = req.get_customer_id().get_required_value("customer_id")?;let use_merchant_reference_id =helpers::should_use_merchant_reference_id_as_customer_id_for_provider(state,@@ -596,9 +608,9 @@ impl ExternalVaultPayout<'_> {let execution_context = self.resolve_external_vault_execution_context(&provider_profile, saved_source).await?;- let dimensions = dimension_state::Dimensions::new()- .with_processor_merchant_id(processor.get_processor_merchant_id())- .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id());+ let dimensions = payout_cap_dimensions+ .without_profile_id()+ .without_organization_id();validate_payout_condition(!core_utils::get_feature_config(state, platform, &dimensions).awaitdiff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rsindex 6aa58ca369..cb8e3bcc04 100644--- a/crates/router/src/core/payouts/validator.rs+++ b/crates/router/src/core/payouts/validator.rs@@ -1,10 +1,12 @@use std::collections::HashSet;use actix_web::http::header;+use api_models::payments::Amount;#[cfg(feature = "olap")]use common_utils::errors::CustomResult;use common_utils::{id_type::{self, GenerateId},+ types::MinorUnit,validation::validate_domain_against_allowed_domains,};use diesel_models::generic_link::PayoutLink;@@ -170,6 +172,30 @@ pub async fn validate_create_request(.attach_printable("invalid merchant_id in request"))})?;+ // Resolve the profile before any customer side effects so the cap applies to the+ // exact merchant/profile context that will own the payout.+ let business_profile = core_utils::get_profile_from_business_details(+ req.business_country,+ req.business_label.as_ref(),+ platform.get_processor(),+ req.profile_id.as_ref(),+ &*state.store,+ )+ .await?;+ let profile_id = business_profile.get_id().to_owned();+ let profile_dimensions = dimensions+ .with_organization_id(+ platform+ .get_processor()+ .get_account()+ .get_org_id()+ .to_owned(),+ )+ .with_profile_id(profile_id.clone());++ validate_payout_amount_against_config(state, &profile_dimensions, &profile_id, req.amount)+ .await?;+// Payout IDlet db: &dyn StorageInterface = &*state.store;let payout_id = match req.payout_id.as_ref() {@@ -319,6 +345,59 @@ pub async fn validate_create_request())}+pub(crate) fn validate_payout_amount(+ amount: Amount,+ min_amount: MinorUnit,+ max_amount: MinorUnit,+) -> RouterResult<()> {+ utils::when(min_amount > max_amount, || {+ Err(report!(errors::ApiErrorResponse::PreconditionFailed {+ message: "payout amount configuration has a minimum greater than its maximum"+ .to_string(),+ }))+ })+ .and_then(|_| {+ let amount = MinorUnit::from(amount);++ utils::when(amount < min_amount || amount > max_amount, || {+ Err(report!(errors::ApiErrorResponse::PreconditionFailed {+ message: format!(+ "payout amount must be between {} and {} in the currency's lowest denomination",+ min_amount.get_amount_as_i64(),+ max_amount.get_amount_as_i64(),+ ),+ }))+ })+ })+}++pub(crate) async fn validate_payout_amount_against_config(+ state: &SessionState,+ dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndOrgIdAndProfileId,+ profile_id: &id_type::ProfileId,+ amount: Option<Amount>,+) -> RouterResult<()> {+ let min_amount = dimensions+ .get_payout_min_amount(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ Some(profile_id),+ )+ .await;+ let max_amount = dimensions+ .get_payout_max_amount(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ Some(profile_id),+ )+ .await;++ amount+ .map(|amount| validate_payout_amount(amount, min_amount, max_amount))+ .transpose()+ .map(|_| ())+}+#[cfg(feature = "v1")]pub async fn get_payout_method_data_generic(state: &SessionState,