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(router): add support to store `signature_network` and `is_regulated` in payment attempts (#8891)
Shankar Singh C15cb47354694
diff --git a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sqlindex 16815e9a33..ffe706cab0 100644--- a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql+++ b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql@@ -45,6 +45,8 @@ CREATE TABLE payment_attempt_queue (`card_network` Nullable(String),`routing_approach` LowCardinality(Nullable(String)),`debit_routing_savings` Nullable(UInt32),+ `signature_network` Nullable(String),+ `is_issuer_regulated` Nullable(Bool),`sign_flag` Int8) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',kafka_topic_list = 'hyperswitch-payment-attempt-events',@@ -100,6 +102,8 @@ CREATE TABLE payment_attempts (`card_network` Nullable(String),`routing_approach` LowCardinality(Nullable(String)),`debit_routing_savings` Nullable(UInt32),+ `signature_network` Nullable(String),+ `is_issuer_regulated` Nullable(Bool),`sign_flag` Int8,INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1,@@ -158,6 +162,8 @@ CREATE MATERIALIZED VIEW payment_attempt_mv TO payment_attempts (`card_network` Nullable(String),`routing_approach` LowCardinality(Nullable(String)),`debit_routing_savings` Nullable(UInt32),+ `signature_network` Nullable(String),+ `is_issuer_regulated` Nullable(Bool),`sign_flag` Int8) ASSELECT@@ -208,6 +214,8 @@ SELECTcard_network,routing_approach,debit_routing_savings,+ signature_network,+ is_issuer_regulated,sign_flagFROMpayment_attempt_queuediff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rsindex 6d7dca22a3..a266e1366a 100644--- a/crates/analytics/src/payments/accumulator.rs+++ b/crates/analytics/src/payments/accumulator.rs@@ -63,6 +63,8 @@ pub struct ProcessedAmountAccumulator {pub struct DebitRoutingAccumulator {pub transaction_count: u64,pub savings_amount: u64,+ pub signature_network: Option<String>,+ pub is_issuer_regulated: Option<bool>,}#[derive(Debug, Default)]@@ -191,7 +193,13 @@ impl PaymentMetricAccumulator for SuccessRateAccumulator {}impl PaymentMetricAccumulator for DebitRoutingAccumulator {- type MetricOutput = (Option<u64>, Option<u64>, Option<u64>);+ type MetricOutput = (+ Option<u64>,+ Option<u64>,+ Option<u64>,+ Option<String>,+ Option<bool>,+ );fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) {if let Some(count) = metrics.count {@@ -200,6 +208,12 @@ impl PaymentMetricAccumulator for DebitRoutingAccumulator {if let Some(total) = metrics.total.as_ref().and_then(ToPrimitive::to_u64) {self.savings_amount += total;}+ if let Some(signature_network) = &metrics.signature_network {+ self.signature_network = Some(signature_network.clone());+ }+ if let Some(is_issuer_regulated) = metrics.is_issuer_regulated {+ self.is_issuer_regulated = Some(is_issuer_regulated);+ }}fn collect(self) -> Self::MetricOutput {@@ -207,6 +221,8 @@ impl PaymentMetricAccumulator for DebitRoutingAccumulator {Some(self.transaction_count),Some(self.savings_amount),Some(0),+ self.signature_network,+ self.is_issuer_regulated,)}}@@ -468,8 +484,13 @@ impl PaymentMetricsAccumulator {) = self.payments_distribution.collect();let (failure_reason_count, failure_reason_count_without_smart_retries) =self.failure_reasons_distribution.collect();- let (debit_routed_transaction_count, debit_routing_savings, debit_routing_savings_in_usd) =- self.debit_routing.collect();+ let (+ debit_routed_transaction_count,+ debit_routing_savings,+ debit_routing_savings_in_usd,+ signature_network,+ is_issuer_regulated,+ ) = self.debit_routing.collect();PaymentMetricsBucketValue {payment_success_rate: self.payment_success_rate.collect(),@@ -497,6 +518,8 @@ impl PaymentMetricsAccumulator {debit_routed_transaction_count,debit_routing_savings,debit_routing_savings_in_usd,+ signature_network,+ is_issuer_regulated,}}}diff --git a/crates/analytics/src/payments/metrics.rs b/crates/analytics/src/payments/metrics.rsindex b19c661322..914eac7116 100644--- a/crates/analytics/src/payments/metrics.rs+++ b/crates/analytics/src/payments/metrics.rs@@ -53,6 +53,8 @@ pub struct PaymentMetricRow {pub total: Option<bigdecimal::BigDecimal>,pub count: Option<i64>,pub routing_approach: Option<DBEnumWrapper<storage_enums::RoutingApproach>>,+ pub signature_network: Option<String>,+ pub is_issuer_regulated: Option<bool>,#[serde(with = "common_utils::custom_serde::iso8601::option")]pub start_bucket: Option<PrimitiveDateTime>,#[serde(with = "common_utils::custom_serde::iso8601::option")]diff --git a/crates/analytics/src/payments/metrics/debit_routing.rs b/crates/analytics/src/payments/metrics/debit_routing.rsindex 2caec813ec..309b2131c6 100644--- a/crates/analytics/src/payments/metrics/debit_routing.rs+++ b/crates/analytics/src/payments/metrics/debit_routing.rs@@ -56,6 +56,14 @@ where}).switch()?;query_builder.add_select_column("currency").switch()?;++ query_builder+ .add_select_column("signature_network")+ .switch()?;+ query_builder+ .add_select_column("is_issuer_regulated")+ .switch()?;+query_builder.add_select_column(Aggregate::Min {field: "created_at",@@ -85,6 +93,16 @@ where.switch()?;}+ query_builder+ .add_group_by_clause("signature_network")+ .attach_printable("Error grouping by signature_network")+ .switch()?;++ query_builder+ .add_group_by_clause("is_issuer_regulated")+ .attach_printable("Error grouping by is_issuer_regulated")+ .switch()?;+query_builder.add_group_by_clause("currency").attach_printable("Error grouping by currency")diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rsindex 10f039fcc7..38746ce595 100644--- a/crates/analytics/src/sqlx.rs+++ b/crates/analytics/src/sqlx.rs@@ -736,6 +736,16 @@ impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow {ColumnNotFound(_) => Ok(Default::default()),e => Err(e),})?;+ let signature_network: Option<String> =+ row.try_get("signature_network").or_else(|e| match e {+ ColumnNotFound(_) => Ok(Default::default()),+ e => Err(e),+ })?;+ let is_issuer_regulated: Option<bool> =+ row.try_get("is_issuer_regulated").or_else(|e| match e {+ ColumnNotFound(_) => Ok(Default::default()),+ e => Err(e),+ })?;let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e {ColumnNotFound(_) => Ok(Default::default()),e => Err(e),@@ -768,6 +778,8 @@ impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow {error_reason,first_attempt,routing_approach,+ signature_network,+ is_issuer_regulated,total,count,start_bucket,diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rsindex 193fdf26cc..7058307993 100644--- a/crates/api_models/src/analytics/payments.rs+++ b/crates/api_models/src/analytics/payments.rs@@ -319,6 +319,8 @@ pub struct PaymentMetricsBucketValue {pub debit_routed_transaction_count: Option<u64>,pub debit_routing_savings: Option<u64>,pub debit_routing_savings_in_usd: Option<u64>,+ pub signature_network: Option<String>,+ pub is_issuer_regulated: Option<bool>,}#[derive(Debug, serde::Serialize)]diff --git a/crates/api_models/src/open_router.rs b/crates/api_models/src/open_router.rsindex 0365d4b6d5..c2e6bc76c0 100644--- a/crates/api_models/src/open_router.rs+++ b/crates/api_models/src/open_router.rs@@ -124,6 +124,13 @@ impl CoBadgedCardNetworks {pub fn get_card_networks(&self) -> Vec<common_enums::CardNetwork> {self.0.iter().map(|info| info.network.clone()).collect()}++ pub fn get_signature_network(&self) -> Option<common_enums::CardNetwork> {+ self.0+ .iter()+ .find(|info| info.network.is_signature_network())+ .map(|info| info.network.clone())+ }}impl From<&DebitRoutingOutput> for payment_methods::CoBadgedCardData {diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rsindex d3a502c877..2e9478dc25 100644--- a/crates/api_models/src/payment_methods.rs+++ b/crates/api_models/src/payment_methods.rs@@ -1229,6 +1229,8 @@ impl From<CardDetailFromLocker> for payments::AdditionalCardInfo {card_holder_name: item.card_holder_name,payment_checks: None,authentication_data: None,+ is_regulated: None,+ signature_network: None,}}}@@ -1252,6 +1254,8 @@ impl From<CardDetailFromLocker> for payments::AdditionalCardInfo {card_holder_name: item.card_holder_name,payment_checks: None,authentication_data: None,+ is_regulated: None,+ signature_network: None,}}}diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 714ad7cb50..d757c6cfb6 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -2970,6 +2970,15 @@ pub struct AdditionalCardInfo {/// Details about the threeds environment./// This is a free form field and the structure varies from processor to processorpub authentication_data: Option<serde_json::Value>,++ /// Indicates if the card issuer is regulated under government-imposed interchange fee caps.+ /// In the United States, this includes debit cards that fall under the Durbin Amendment,+ /// which imposes capped interchange fees.+ pub is_regulated: Option<bool>,++ /// The global signature network under which the card is issued.+ /// This represents the primary global card brand, even if the transaction uses a local network+ pub signature_network: Option<api_enums::CardNetwork>,}#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex a895f0710c..ec8d55ed00 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -2599,7 +2599,7 @@ pub enum DecisionEngineMerchantCategoryCode {}impl CardNetwork {- pub fn is_global_network(&self) -> bool {+ pub fn is_signature_network(&self) -> bool {match self {Self::Interac| Self::Stardiff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rsindex ceff3d161d..a9d4456606 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs@@ -37,6 +37,8 @@ use error_stack::ResultExt;#[cfg(feature = "v2")]use masking::PeekInterface;use masking::Secret;+#[cfg(feature = "v1")]+use router_env::logger;#[cfg(feature = "v2")]use rustc_hash::FxHashMap;#[cfg(feature = "v1")]@@ -1109,6 +1111,19 @@ impl PaymentAttempt {.and_then(|data| data.get_additional_card_info()).and_then(|card_info| card_info.card_network)}++ pub fn get_payment_method_data(&self) -> Option<api_models::payments::AdditionalPaymentData> {+ self.payment_method_data+ .clone()+ .and_then(|data| match data {+ serde_json::Value::Null => None,+ _ => Some(data.parse_value("AdditionalPaymentData")),+ })+ .transpose()+ .map_err(|err| logger::error!("Failed to parse AdditionalPaymentData {err:?}"))+ .ok()+ .flatten()+ }}#[derive(Clone, Debug, Eq, PartialEq)]diff --git a/crates/router/src/core/debit_routing.rs b/crates/router/src/core/debit_routing.rsindex 0aeb2b9777..34eaed4290 100644--- a/crates/router/src/core/debit_routing.rs+++ b/crates/router/src/core/debit_routing.rs@@ -726,7 +726,7 @@ fn find_matching_networks(fee_sorted_debit_networks.iter().filter(|network| merchant_debit_networks.contains(network))- .filter(|network| is_routing_enabled || network.is_global_network())+ .filter(|network| is_routing_enabled || network.is_signature_network()).map(|network| {if network.is_us_local_network() {*has_us_local_network = true;diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 8dd79f95d9..c8320bcc63 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -866,7 +866,7 @@ fn get_card_network_with_us_local_debit_network_override(data.co_badged_card_networks_info.0.iter()- .find(|info| info.network.is_global_network())+ .find(|info| info.network.is_signature_network()).cloned()});info.map(|data| data.network)diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 87f47a9b2b..1523a4b3c2 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -4867,19 +4867,30 @@ pub async fn get_additional_payment_data("Card cobadge check failed due to an invalid card network regex",)?;- let card_network = match (- is_cobadged_based_on_regex,- card_data.co_badged_card_data.is_some(),- ) {- (false, false) => {+ let (card_network, signature_network, is_regulated) = card_data+ .co_badged_card_data+ .as_ref()+ .map(|co_badged_data| {+ logger::debug!("Co-badged card data found");++ (+ card_data.card_network.clone(),+ co_badged_data+ .co_badged_card_networks_info+ .get_signature_network(),+ Some(co_badged_data.is_regulated),+ )+ })+ .or_else(|| {+ is_cobadged_based_on_regex.then(|| {+ logger::debug!("Card network is cobadged (regex-based detection)");+ (card_data.card_network.clone(), None, None)+ })+ })+ .unwrap_or_else(|| {logger::debug!("Card network is not cobadged");- None- }- _ => {- logger::debug!("Card network is cobadged");- card_data.card_network.clone()- }- };+ (None, None, None)+ });let last4 = Some(card_data.card_number.get_last4());if card_data.card_issuer.is_some()@@ -4904,6 +4915,8 @@ pub async fn get_additional_payment_data(// These are filled after calling the processor / connectorpayment_checks: None,authentication_data: None,+ is_regulated,+ signature_network: signature_network.clone(),}),)))} else {@@ -4934,6 +4947,8 @@ pub async fn get_additional_payment_data(// These are filled after calling the processor / connectorpayment_checks: None,authentication_data: None,+ is_regulated,+ signature_network: signature_network.clone(),},))});@@ -4954,6 +4969,8 @@ pub async fn get_additional_payment_data(// These are filled after calling the processor / connectorpayment_checks: None,authentication_data: None,+ is_regulated,+ signature_network: signature_network.clone(),},))})))@@ -5199,6 +5216,8 @@ pub async fn get_additional_payment_data(// These are filled after calling the processor / connectorpayment_checks: None,authentication_data: None,+ is_regulated: None,+ signature_network: None,}),)))} else {@@ -5229,6 +5248,8 @@ pub async fn get_additional_payment_data(// These are filled after calling the processor / connectorpayment_checks: None,authentication_data: None,+ is_regulated: None,+ signature_network: None,},))});@@ -5249,6 +5270,8 @@ pub async fn get_additional_payment_data(// These are filled after calling the processor / connectorpayment_checks: None,authentication_data: None,+ is_regulated: None,+ signature_network: None,},))})))diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rsindex 8a900019b7..0d8dfd8704 100644--- a/crates/router/src/services/kafka/payment_attempt.rs+++ b/crates/router/src/services/kafka/payment_attempt.rs@@ -71,11 +71,16 @@ pub struct KafkaPaymentAttempt<'a> {pub card_discovery: Option<String>,pub routing_approach: Option<storage_enums::RoutingApproach>,pub debit_routing_savings: Option<MinorUnit>,+ pub signature_network: Option<common_enums::CardNetwork>,+ pub is_issuer_regulated: Option<bool>,}#[cfg(feature = "v1")]impl<'a> KafkaPaymentAttempt<'a> {pub fn from_storage(attempt: &'a PaymentAttempt) -> Self {+ let card_payment_method_data = attempt+ .get_payment_method_data()+ .and_then(|data| data.get_additional_card_info());Self {payment_id: &attempt.payment_id,merchant_id: &attempt.merchant_id,@@ -134,6 +139,10 @@ impl<'a> KafkaPaymentAttempt<'a> {.map(|discovery| discovery.to_string()),routing_approach: attempt.routing_approach.clone(),debit_routing_savings: attempt.debit_routing_savings,+ signature_network: card_payment_method_data+ .as_ref()+ .and_then(|data| data.signature_network.clone()),+ is_issuer_regulated: card_payment_method_data.and_then(|data| data.is_regulated),}}}diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rsindex eea3916f80..5f87e017f8 100644--- a/crates/router/src/services/kafka/payment_attempt_event.rs+++ b/crates/router/src/services/kafka/payment_attempt_event.rs@@ -72,11 +72,16 @@ pub struct KafkaPaymentAttemptEvent<'a> {pub card_discovery: Option<String>,pub routing_approach: Option<storage_enums::RoutingApproach>,pub debit_routing_savings: Option<MinorUnit>,+ pub signature_network: Option<common_enums::CardNetwork>,+ pub is_issuer_regulated: Option<bool>,}#[cfg(feature = "v1")]impl<'a> KafkaPaymentAttemptEvent<'a> {pub fn from_storage(attempt: &'a PaymentAttempt) -> Self {+ let card_payment_method_data = attempt+ .get_payment_method_data()+ .and_then(|data| data.get_additional_card_info());Self {payment_id: &attempt.payment_id,merchant_id: &attempt.merchant_id,@@ -135,6 +140,10 @@ impl<'a> KafkaPaymentAttemptEvent<'a> {.map(|discovery| discovery.to_string()),routing_approach: attempt.routing_approach.clone(),debit_routing_savings: attempt.debit_routing_savings,+ signature_network: card_payment_method_data+ .as_ref()+ .and_then(|data| data.signature_network.clone()),+ is_issuer_regulated: card_payment_method_data.and_then(|data| data.is_regulated),}}}