Skip to content

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

feat(revenue_recovery): count every recorded transaction in the cluster data (#15163)

CHALLA NISHANTH BABUf2e123ad6fb0
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 4b35217aa7..35f82fed84 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -16250,14 +16250,6 @@
"next_retry"
],
"properties": {
- "last_failure_code": {
- "allOf": [
- {
- "$ref": "#/components/schemas/StandardisedCode"
- }
- ],
- "nullable": true
- },
"consumed_ladder_rungs": {
"type": "integer",
"format": "int32",
@@ -26283,6 +26275,14 @@
}
],
"nullable": true
+ },
+ "last_failure_code": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/StandardisedCode"
+ }
+ ],
+ "nullable": true
}
}
},
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 0986290b15..0553c83ae1 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -14455,6 +14455,10 @@ pub struct PaymentRevenueRecoveryMetadata {
#[schema(value_type = Option<ExternalTriggerState>)]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub external_trigger_state: Option<common_payments_types::ExternalTriggerState>,
+ /// Standardised error code of the last failed transaction of the invoice. The result of the next transaction is counted against it in the cluster data.
+ #[schema(value_type = Option<StandardisedCode>)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub last_failure_code: Option<common_enums::StandardisedCode>,
}
#[cfg(feature = "v2")]
@@ -14627,6 +14631,10 @@ pub struct PaymentsAttemptRecordRequest {
#[schema(example = "Chase")]
/// Card Issuer
pub card_issuer: Option<String>,
+
+ /// Standardised error code of the attempt, when it failed.
+ #[schema(value_type = Option<StandardisedCode>)]
+ pub standardised_error_code: Option<common_enums::StandardisedCode>,
}
// Serialize is required because the api event requires Serialize to be implemented
diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rs
index 58b1206ef9..7a2847e49c 100644
--- a/crates/common_types/src/payments.rs
+++ b/crates/common_types/src/payments.rs
@@ -1188,10 +1188,6 @@ impl RecoveryNextRetry {
/// job holds it between the merchant's reports.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub struct ExternalTriggerState {
- /// Standardised error code of the last failed transaction. The result of the next retry is
- /// counted against it in the cluster data.
- #[schema(value_type = Option<StandardisedCode>)]
- pub last_failure_code: Option<common_enums::StandardisedCode>,
/// Positions of the static retry ladder the invoice has used.
pub consumed_ladder_rungs: u32,
/// Retries made with the card of the invoice since it was first hard declined. Absent while it
diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs
index 0ea7f0cee6..2f6b525758 100644
--- a/crates/diesel_models/src/types.rs
+++ b/crates/diesel_models/src/types.rs
@@ -531,6 +531,10 @@ pub struct PaymentRevenueRecoveryMetadata {
/// data for every other invoice.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub external_trigger_state: Option<common_types::payments::ExternalTriggerState>,
+ /// Standardised error code of the last failed transaction of the invoice. The result of the
+ /// next transaction is counted against it in the cluster data.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub last_failure_code: Option<common_enums::StandardisedCode>,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index 3192572e4f..15a6ec1279 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -966,6 +966,7 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven
invoice_billing_started_at_time: from.invoice_billing_started_at_time,
revenue_recovery_ab_routing: from.revenue_recovery_ab_routing,
external_trigger_state: from.external_trigger_state,
+ last_failure_code: from.last_failure_code,
}
}
@@ -993,6 +994,7 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven
invoice_billing_started_at_time: self.invoice_billing_started_at_time,
revenue_recovery_ab_routing: self.revenue_recovery_ab_routing,
external_trigger_state: self.external_trigger_state,
+ last_failure_code: self.last_failure_code,
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 24573542f0..60a6d4ed68 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -1663,6 +1663,7 @@ pub struct RevenueRecoveryData {
pub triggered_by: storage_enums::enums::TriggeredBy,
pub card_network: Option<common_enums::CardNetwork>,
pub card_issuer: Option<String>,
+ pub standardised_error_code: Option<common_enums::StandardisedCode>,
}
/// A closed invoice has no next retry, whatever was last stored for it. Cancelling an invoice does
@@ -1807,6 +1808,7 @@ where
external_trigger_state: revenue_recovery
.as_ref()
.and_then(|data| data.external_trigger_state.clone()),
+ last_failure_code: self.revenue_recovery_data.standardised_error_code,
});
Ok(Some(FeatureMetadata {
multi_currency_processing: payment_intent_feature_metadata
diff --git a/crates/router/src/core/payments/operations/payment_attempt_record.rs b/crates/router/src/core/payments/operations/payment_attempt_record.rs
index 8df3075d82..d035ee2c15 100644
--- a/crates/router/src/core/payments/operations/payment_attempt_record.rs
+++ b/crates/router/src/core/payments/operations/payment_attempt_record.rs
@@ -206,6 +206,7 @@ impl<F: Send + Clone + Sync>
triggered_by: request.triggered_by,
card_network: request.card_network.clone(),
card_issuer: request.card_issuer.clone(),
+ standardised_error_code: request.standardised_error_code,
};
let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
payment_intent
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index e70cdfb5b5..aab0ace47c 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -8381,6 +8381,7 @@ impl ForeignFrom<&diesel_models::types::FeatureMetadata> for api_models::payment
external_trigger_state: payment_revenue_recovery_metadata
.external_trigger_state
.clone(),
+ last_failure_code: payment_revenue_recovery_metadata.last_failure_code,
}
});
let apple_pay_details = feature_metadata
diff --git a/crates/router/src/core/revenue_recovery/external_triggers.rs b/crates/router/src/core/revenue_recovery/external_triggers.rs
index eb906d1a36..d508ed54ff 100644
--- a/crates/router/src/core/revenue_recovery/external_triggers.rs
+++ b/crates/router/src/core/revenue_recovery/external_triggers.rs
@@ -18,7 +18,6 @@ use super::{
api,
card_selection::{self, CardAvailability, CardSelection},
get_recovery_grace_window_end, is_retry_budget_exhausted,
- retry_stats::RetryOutcomeEvent,
schedule::StaticLadderProgress,
};
use crate::{
@@ -121,9 +120,9 @@ pub(super) async fn record_transaction_and_get_next_retry(
result
}
-/// Records the transaction, keeps the cluster data up to date and decides the next retry. A
-/// transaction made on session or with the customer present is only recorded: it is not a retry, so
-/// the cluster data and what the invoice last told the merchant stay as they were.
+/// Records the transaction and decides the next retry. A transaction made on session or with the
+/// customer present is only recorded: it is not a retry, so what the invoice last told the merchant
+/// stays as it was.
///
/// Once the transaction is recorded the merchant must get an answer, because reporting it again is
/// refused as a duplicate. So the steps after recording log their failures rather than fail the
@@ -197,15 +196,6 @@ async fn handle_merchant_report(
.unwrap_or(common_enums::FutureUsage::OffSession)
.is_off_session();
- if let Some((failure_code, success)) =
- get_retry_outcome(previous_trigger_state.as_ref(), request.transaction_status)
- .filter(|_| is_merchant_initiated)
- {
- RetryOutcomeEvent::from_retry_outcome(recovery_attempt.created_at, failure_code, success)
- .record(state)
- .await;
- }
-
reset_card_history_after_a_charge(state, request).await;
let payment_intent = state
@@ -274,7 +264,6 @@ async fn handle_merchant_report(
.await;
let trigger_state = ExternalTriggerState {
- last_failure_code,
consumed_ladder_rungs: decision
.next_ladder_progress
.unwrap_or(ladder_progress)
@@ -588,8 +577,8 @@ fn get_retries_after_hard_decline(
}
}
-/// The standardised error code the next retry is counted against: that of this transaction when it
-/// failed. A partial charge leaves none, as it does for the retries Hyperswitch makes.
+/// The standardised error code the next retry time is worked out from: that of this transaction,
+/// if it failed.
fn get_last_failure_code(
transaction_status: RecoveryTransactionStatus,
recovery_attempt: &RecoveryPaymentAttempt,
@@ -600,24 +589,6 @@ fn get_last_failure_code(
}
}
-/// The result to count in the cluster data, as the error code the retry was made after and whether
-/// it succeeded. Only a retry that was scheduled is counted, which leaves out the first transaction
-/// of an invoice and the merchant's own retries before recovery starts, and partial charges are not
-/// counted, as they are not for the retries Hyperswitch makes.
-fn get_retry_outcome(
- previous_trigger_state: Option<&ExternalTriggerState>,
- transaction_status: RecoveryTransactionStatus,
-) -> Option<(Option<common_enums::StandardisedCode>, bool)> {
- let trigger_state = previous_trigger_state
- .filter(|trigger_state| trigger_state.next_retry.schedule_time.is_some())?;
-
- match transaction_status {
- RecoveryTransactionStatus::Failure => Some((trigger_state.last_failure_code, false)),
- RecoveryTransactionStatus::Charged => Some((trigger_state.last_failure_code, true)),
- RecoveryTransactionStatus::PartialCharged => None,
- }
-}
-
/// Why no retry should follow this transaction, before any retry time is worked out.
fn get_no_retry_reason(
invoice_status: common_enums::IntentStatus,
diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs
index 6a17cd04a6..cc2bf6d23d 100644
--- a/crates/router/src/core/webhooks/recovery_incoming.rs
+++ b/crates/router/src/core/webhooks/recovery_incoming.rs
@@ -820,6 +820,24 @@ impl RevenueRecoveryAttempt {
}
}?;
+ if recovery_attempt.attempt_status.is_terminal_status() {
+ retry_stats::RetryOutcomeEvent::from_retry_outcome(
+ recovery_attempt.created_at,
+ payment_intent
+ .feature_metadata
+ .as_ref()
+ .and_then(|feature_metadata| feature_metadata.revenue_recovery.as_ref())
+ .and_then(|recovery_metadata| recovery_metadata.last_failure_code),
+ matches!(
+ recovery_attempt.attempt_status,
+ common_enums::AttemptStatus::Charged
+ | common_enums::AttemptStatus::PartialCharged
+ ),
+ )
+ .record(state)
+ .await;
+ }
+
let response = (recovery_attempt, updated_recovery_intent);
if let Err(error) = self
@@ -892,6 +910,24 @@ impl RevenueRecoveryAttempt {
let error =
Option::<api_payments::RecordAttemptErrorDetails>::from(revenue_recovery_attempt_data);
+
+ let standardised_error_code = match revenue_recovery_attempt_data.status {
+ common_enums::AttemptStatus::Charged | common_enums::AttemptStatus::PartialCharged => {
+ None
+ }
+ _ => {
+ retry_stats::events::resolve_standardised_error_code(
+ state,
+ Some(connector_details.get_connector().to_string()),
+ revenue_recovery_attempt_data.error_code.clone(),
+ revenue_recovery_attempt_data.error_message.clone(),
+ revenue_recovery_attempt_data.network_decline_code.clone(),
+ revenue_recovery_attempt_data.card_info.card_network.clone(),
+ )
+ .await
+ }
+ };
+
Ok(api_payments::PaymentsAttemptRecordRequest {
amount_details,
status: revenue_recovery_attempt_data.status,
@@ -920,6 +956,7 @@ impl RevenueRecoveryAttempt {
triggered_by,
card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),
card_issuer,
+ standardised_error_code,
})
}