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): add external trigger model with next retry schedule (#15113)

CHALLA NISHANTH BABUe92bbafd4001
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index f3727b8ee8..eedef30d60 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -16242,6 +16242,40 @@
}
}
},
+ "ExternalTriggerState": {
+ "type": "object",
+ "description": "The recovery state kept on an invoice whose retries the merchant triggers, since no scheduled\njob holds it between the merchant's reports.",
+ "required": [
+ "consumed_ladder_rungs",
+ "next_retry"
+ ],
+ "properties": {
+ "last_failure_code": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/StandardisedCode"
+ }
+ ],
+ "nullable": true
+ },
+ "consumed_ladder_rungs": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Positions of the static retry ladder the invoice has used.",
+ "minimum": 0
+ },
+ "retries_after_hard_decline": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Retries made with the card of the invoice since it was first hard declined. Absent while it\nhas not been.",
+ "nullable": true,
+ "minimum": 0
+ },
+ "next_retry": {
+ "$ref": "#/components/schemas/RecoveryNextRetry"
+ }
+ }
+ },
"ExternalVaultConnectorDetails": {
"type": "object",
"properties": {
@@ -26225,6 +26259,14 @@
}
],
"nullable": true
+ },
+ "external_trigger_state": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ExternalTriggerState"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -32059,6 +32101,48 @@
"paypal"
]
},
+ "RecoveryNextRetry": {
+ "type": "object",
+ "description": "When the merchant should trigger the next retry of an invoice: at `schedule_time`, or not at all\nwhen that is `null`, for the given `reason`.",
+ "required": [
+ "retry_count"
+ ],
+ "properties": {
+ "retry_count": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Number of the next retry, counted the way the `max_retry_count` of the profile counts them:\nthe first retry after the original payment is 1.",
+ "minimum": 0
+ },
+ "schedule_time": {
+ "type": "string",
+ "description": "The time to trigger the retry at, then report its result through the recovery API. `null`\nwhen no retry is scheduled.",
+ "example": "2022-09-10T10:11:12.000Z",
+ "nullable": true
+ },
+ "reason": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/RecoveryNoRetryReason"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
+ "RecoveryNoRetryReason": {
+ "type": "string",
+ "description": "Why no retry is scheduled for an invoice whose retries the merchant triggers.",
+ "enum": [
+ "recovered",
+ "retries_exhausted",
+ "grace_period_exceeded",
+ "hard_decline",
+ "monitoring",
+ "cancelled",
+ "below_retry_threshold"
+ ]
+ },
"RecoveryPaymentsCreate": {
"type": "object",
"required": [
@@ -32238,6 +32322,14 @@
"nullable": true,
"maxLength": 30,
"minLength": 30
+ },
+ "next_retry": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/RecoveryNextRetry"
+ }
+ ],
+ "nullable": true
}
}
},
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index c5acefff54..5f20e489f7 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -814,6 +814,11 @@ pub struct RevenueRecoveryGetIntentResponse {
#[schema(value_type = RecoveryStatus, example = "scheduled")]
pub status: common_enums::RecoveryStatus,
+ /// When to trigger the next retry of the invoice. Sent when the merchant triggers its retries and has reported a transaction made off session with the customer absent.
+ #[schema(value_type = Option<RecoveryNextRetry>)]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub next_retry: Option<common_payments_types::RecoveryNextRetry>,
+
/// The amount details for the payment
pub amount_details: AmountDetailsResponse,
@@ -2410,6 +2415,11 @@ pub struct RecoveryPaymentsResponse {
example = "invoice_mbabizu24mvu3mela5njyh"
)]
pub merchant_reference_id: Option<id_type::PaymentReferenceId>,
+
+ /// When to trigger the next retry of the invoice. Sent when the `revenue_recovery_trigger_model` of the profile is `external_triggers` and the transaction was made off session with the customer absent. Any other transaction is only recorded.
+ #[schema(value_type = Option<RecoveryNextRetry>)]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub next_retry: Option<common_payments_types::RecoveryNextRetry>,
}
#[cfg(feature = "v2")]
@@ -14433,6 +14443,10 @@ pub struct PaymentRevenueRecoveryMetadata {
#[schema(value_type = Option<RevenueRecoveryABAlgorithm>, example = "adaptive_retry")]
#[serde(default)]
pub revenue_recovery_ab_routing: Option<common_enums::RevenueRecoveryABAlgorithm>,
+ /// Recovery state of an invoice whose retries the merchant triggers.
+ #[schema(value_type = Option<ExternalTriggerState>)]
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub external_trigger_state: Option<common_payments_types::ExternalTriggerState>,
}
#[cfg(feature = "v2")]
diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rs
index 8bdf91050a..58b1206ef9 100644
--- a/crates/common_types/src/payments.rs
+++ b/crates/common_types/src/payments.rs
@@ -1126,6 +1126,82 @@ impl RecoveryConnectorDetails {
}
}
+/// Why no retry is scheduled for an invoice whose retries the merchant triggers.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum RecoveryNoRetryReason {
+ /// The invoice is charged in full.
+ Recovered,
+ /// The invoice has used every retry it is allowed.
+ RetriesExhausted,
+ /// The grace period of the invoice is over, or would be over by the time of the next retry.
+ GracePeriodExceeded,
+ /// The card was hard declined, and the retries the profile allows after that are used up.
+ HardDecline,
+ /// The retry algorithm of the profile is `monitoring`, so transactions are only recorded.
+ Monitoring,
+ /// The invoice is cancelled.
+ Cancelled,
+ /// The invoice has not reached the `billing_connector_retry_threshold` of the profile. The
+ /// merchant's own retries come first, and recovery starts once they reach it.
+ BelowRetryThreshold,
+}
+
+/// When the merchant should trigger the next retry of an invoice: at `schedule_time`, or not at all
+/// when that is `null`, for the given `reason`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+pub struct RecoveryNextRetry {
+ /// Number of the next retry, counted the way the `max_retry_count` of the profile counts them:
+ /// the first retry after the original payment is 1.
+ pub retry_count: u16,
+ /// The time to trigger the retry at, then report its result through the recovery API. `null`
+ /// when no retry is scheduled.
+ #[schema(value_type = Option<String>, example = "2022-09-10T10:11:12.000Z")]
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub schedule_time: Option<PrimitiveDateTime>,
+ /// Why no retry is scheduled. `null` when one is.
+ #[serde(default)]
+ pub reason: Option<RecoveryNoRetryReason>,
+}
+
+impl RecoveryNextRetry {
+ /// A retry to trigger at `schedule_time`.
+ pub fn scheduled(retry_count: u16, schedule_time: PrimitiveDateTime) -> Self {
+ Self {
+ retry_count,
+ schedule_time: Some(schedule_time),
+ reason: None,
+ }
+ }
+
+ /// No retry, for `reason`.
+ pub fn not_scheduled(retry_count: u16, reason: RecoveryNoRetryReason) -> Self {
+ Self {
+ retry_count,
+ schedule_time: None,
+ reason: Some(reason),
+ }
+ }
+}
+
+/// The recovery state kept on an invoice whose retries the merchant triggers, since no scheduled
+/// 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
+ /// has not been.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub retries_after_hard_decline: Option<u16>,
+ /// What the merchant was last told to do.
+ pub next_retry: RecoveryNextRetry,
+}
+
/// Billing Descriptor information to be sent to the payment gateway
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, ToSchema)]
#[cfg_attr(feature = "diesel", derive(AsExpression, FromSqlRow))]
diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs
index fc66aaf223..0ea7f0cee6 100644
--- a/crates/diesel_models/src/types.rs
+++ b/crates/diesel_models/src/types.rs
@@ -527,6 +527,10 @@ pub struct PaymentRevenueRecoveryMetadata {
/// Revenue Recovery A/B routing: the algorithm this invoice was assigned to.
#[serde(default)]
pub revenue_recovery_ab_routing: Option<common_enums::RevenueRecoveryABAlgorithm>,
+ /// Recovery state of an invoice whose retries the merchant triggers. Left out of the stored
+ /// data for every other invoice.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub external_trigger_state: Option<common_types::payments::ExternalTriggerState>,
}
#[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 a59231bf0f..3192572e4f 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -965,6 +965,7 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven
first_payment_attempt_pg_error_code: from.first_payment_attempt_pg_error_code,
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,
}
}
@@ -991,6 +992,7 @@ impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentReven
first_payment_attempt_pg_error_code: self.first_payment_attempt_pg_error_code,
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,
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 731b918418..24573542f0 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -1305,6 +1305,18 @@ impl PaymentIntent {
.and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone())
}
+ /// When the merchant should trigger the next retry of this invoice. Absent unless the merchant
+ /// triggers its retries.
+ pub fn get_external_trigger_next_retry(
+ &self,
+ ) -> Option<common_types::payments::RecoveryNextRetry> {
+ self.get_revenue_recovery_metadata()
+ .and_then(|recovery_metadata| recovery_metadata.external_trigger_state)
+ .map(|trigger_state| {
+ get_next_retry_for_intent_status(self.status, trigger_state.next_retry)
+ })
+ }
+
/// Retries already made against this invoice, by the billing connector and by recovery
/// together. Zero for an intent that has not entered recovery.
pub fn get_revenue_recovery_retry_count(&self) -> Option<u16> {
@@ -1653,6 +1665,27 @@ pub struct RevenueRecoveryData {
pub card_issuer: Option<String>,
}
+/// A closed invoice has no next retry, whatever was last stored for it. Cancelling an invoice does
+/// not touch its recovery metadata, and the state saved after a report can fail to be written.
+#[cfg(feature = "v2")]
+fn get_next_retry_for_intent_status(
+ intent_status: common_enums::IntentStatus,
+ next_retry: common_types::payments::RecoveryNextRetry,
+) -> common_types::payments::RecoveryNextRetry {
+ use common_types::payments::{RecoveryNextRetry, RecoveryNoRetryReason};
+
+ if intent_status == common_enums::IntentStatus::Succeeded {
+ RecoveryNextRetry::not_scheduled(next_retry.retry_count, RecoveryNoRetryReason::Recovered)
+ } else if matches!(
+ intent_status,
+ common_enums::IntentStatus::Cancelled | common_enums::IntentStatus::CancelledPostCapture
+ ) {
+ RecoveryNextRetry::not_scheduled(next_retry.retry_count, RecoveryNoRetryReason::Cancelled)
+ } else {
+ next_retry
+ }
+}
+
#[cfg(feature = "v2")]
impl<F> PaymentAttemptRecordData<F>
where
@@ -1771,6 +1804,9 @@ where
revenue_recovery_ab_routing: revenue_recovery
.as_ref()
.and_then(|data| data.revenue_recovery_ab_routing),
+ external_trigger_state: revenue_recovery
+ .as_ref()
+ .and_then(|data| data.external_trigger_state.clone()),
});
Ok(Some(FeatureMetadata {
multi_currency_processing: payment_intent_feature_metadata
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index 35c32fa731..1bfd1dfb67 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -492,6 +492,11 @@ pub enum PaymentIntentUpdate {
status: common_enums::IntentStatus,
updated_by: String,
},
+ /// Update the feature metadata alone, leaving the status and everything else as it stands.
+ FeatureMetadataUpdate {
+ feature_metadata: Box<Option<diesel_models::types::FeatureMetadata>>,
+ updated_by: String,
+ },
AttemptGroupUpdate {
active_attempts_group_id: id_type::GlobalAttemptGroupId,
active_attempt_id_type: common_enums::ActiveAttemptIDType,
@@ -1065,6 +1070,58 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal
enable_account_name_verification: None,
settlement_conclusion_applied: None,
}),
+ PaymentIntentUpdate::FeatureMetadataUpdate {
+ feature_metadata,
+ updated_by,
+ } => Ok(Self {
+ status: None,
+ amount_captured: None,
+ active_attempt_id: None,
+ active_attempt_id_type: None,
+ active_attempts_group_id: None,
+ prerouting_algorithm: None,
+ modified_at: common_utils::date_time::now(),
+ amount: None,
+ currency: None,
+ shipping_cost: None,
+ tax_details: None,
+ skip_external_tax_calculation: None,
+ surcharge_applicable: None,
+ surcharge_amount: None,
+ tax_on_surcharge: None,
+ routing_algorithm_id: None,
+ capture_method: None,
+ authentication_type: None,
+ billing_address: None,
+ shipping_address: None,
+ customer_present: None,
+ description: None,
+ return_url: None,
+ setup_future_usage: None,
+ apply_mit_exemption: None,
+ statement_descriptor: None,
+ order_details: None,
+ allowed_payment_method_types: None,
+ metadata: None,
+ connector_metadata: None,
+ feature_metadata: *feature_metadata,
+ payment_link_config: None,
+ request_incremental_authorization: None,
+ session_expiry: None,
+ frm_metadata: None,
+ request_external_three_ds_authentication: None,
+ updated_by,
+ force_3ds_challenge: None,
+ is_iframe_redirection_enabled: None,
+ enable_partial_authorization: None,
+ state_metadata: None,
+ profile_acquirer_id: None,
+ external_surcharge_strategy: None,
+ external_surcharge_applicable: None,
+ enable_avs_check: None,
+ enable_account_name_verification: None,
+ settlement_conclusion_applied: None,
+ }),
PaymentIntentUpdate::AttemptGroupUpdate {
updated_by,
active_attempts_group_id,
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index a12147cbc8..25528c8902 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -1035,6 +1035,9 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::AdditionalCardInfo,
common_types::payments::RecoveryTransactionStatus,
common_types::payments::RecoveryConnector,
+ common_types::payments::RecoveryNextRetry,
+ common_types::payments::RecoveryNoRetryReason,
+ common_types::payments::ExternalTriggerState,
api_models::enums::RevenueRecoveryAlgorithmType,
api_models::enums::RevenueRecoveryTriggerModel,
api_models::enums::RevenueRecoveryABAlgorithm,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index eb64cccd28..f12737cbe7 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -4754,6 +4754,7 @@ pub async fn revenue_recovery_get_intent_core(
execute_workflow.as_ref(),
payment_intent.attempt_count,
max_retry_threshold.try_into().unwrap_or(0),
+ payment_intent.get_external_trigger_next_retry(),
);
// Get card_attached count from Redis
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 909bd15230..aeb59fbc5f 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -2778,6 +2778,7 @@ where
id: payment_intent.id.clone(),
profile_id: payment_intent.profile_id.clone(),
status: recovery_status, // Note: field is named 'status' not 'recovery_status'
+ next_retry: payment_intent.get_external_trigger_next_retry(),
amount_details: api_models::payments::AmountDetailsResponse::foreign_from(
payment_intent.amount_details.clone(),
),
@@ -8375,6 +8376,9 @@ impl ForeignFrom<&diesel_models::types::FeatureMetadata> for api_models::payment
.invoice_billing_started_at_time,
revenue_recovery_ab_routing: payment_revenue_recovery_metadata
.revenue_recovery_ab_routing,
+ external_trigger_state: payment_revenue_recovery_metadata
+ .external_trigger_state
+ .clone(),
}
});
let apple_pay_details = feature_metadata
diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rs
index 2316990fe6..63f1e4a0e4 100644
--- a/crates/router/src/core/revenue_recovery.rs
+++ b/crates/router/src/core/revenue_recovery.rs
@@ -77,7 +77,7 @@ pub async fn assign_and_record_ab_routing(
state: &SessionState,
payment_id: &GlobalPaymentId,
feature_metadata: Option<api_payments::FeatureMetadata>,
- revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
+ merchant_context: pcr::RecoveryMerchantContext<'_>,
dimensions: &crate::core::configs::dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndOrgIdAndProfileId,
) -> common_enums::RevenueRecoveryABAlgorithm {
let assigned_algorithm = dimensions
@@ -109,7 +109,7 @@ pub async fn assign_and_record_ab_routing(
match Box::pin(api::update_payment_intent_api(
state,
payment_id.clone(),
- revenue_recovery_payment_data,
+ merchant_context,
payment_update_req,
))
.await
@@ -298,27 +298,17 @@ pub async fn upsert_calculate_pcr_task(
)
.await
{
- // Boxed so the recovery payment data below lives on the heap rather than in this
- // function's future.
- Box::pin(async {
- let revenue_recovery_payment_data = pcr::RevenueRecoveryPaymentData {
- merchant_account: platform.get_processor().get_account().clone(),
- profile: business_profile.clone(),
- key_store: platform.get_processor().get_key_store().inner().clone(),
- billing_mca: billing_connector_account.clone(),
- retry_algorithm: revenue_recovery_retry,
- psync_data: None,
- };
-
- assign_and_record_ab_routing(
- state,
- payment_id,
- recovery_intent_from_payment_intent.feature_metadata.clone(),
- &revenue_recovery_payment_data,
- &dimensions,
- )
- .await;
- })
+ Box::pin(assign_and_record_ab_routing(
+ state,
+ payment_id,
+ recovery_intent_from_payment_intent.feature_metadata.clone(),
+ pcr::RecoveryMerchantContext {
+ merchant_account: platform.get_processor().get_account(),
+ key_store: platform.get_processor().get_key_store().inner(),
+ profile: business_profile,
+ },
+ &dimensions,
+ ))
.await;
}
}
@@ -1891,7 +1881,7 @@ pub async fn reset_connector_transmission_and_active_attempt_id_before_pushing_t
Box::pin(api::update_payment_intent_api(
state,
payment_intent.id.clone(),
- revenue_recovery_payment_data,
+ revenue_recovery_payment_data.get_merchant_context(),
payment_update_req,
))
.await
@@ -2133,12 +2123,35 @@ fn determine_recovery_status_from_workflows(
}
}
+/// The recovery status of an invoice whose retries the merchant triggers. No job tracks it, so
+/// what the merchant was last told says where it stands.
+fn map_external_trigger_recovery_status(
+ next_retry: common_types::payments::RecoveryNextRetry,
+) -> RecoveryStatus {
+ use common_types::payments::RecoveryNoRetryReason;
+
+ match next_retry.reason {
+ None => RecoveryStatus::Scheduled,
+ Some(reason) => match reason {
+ RecoveryNoRetryReason::Recovered => RecoveryStatus::Recovered,
+ RecoveryNoRetryReason::Monitoring | RecoveryNoRetryReason::BelowRetryThreshold => {
+ RecoveryStatus::Monitoring
+ }
+ RecoveryNoRetryReason::RetriesExhausted
+ | RecoveryNoRetryReason::GracePeriodExceeded
+ | RecoveryNoRetryReason::HardDecline
+ | RecoveryNoRetryReason::Cancelled => RecoveryStatus::Terminated,
+ },
+ }
+}
+
pub fn map_recovery_status(
intent_status: IntentStatus,
calculate_workflow: Option<&ProcessTrackerStorage>,
execute_workflow: Option<&ProcessTrackerStorage>,
attempt_count: i16,
max_retry_threshold: i16,
+ external_trigger_next_retry: Option<common_types::payments::RecoveryNextRetry>,
) -> RecoveryStatus {
let (calculate_business_status, calculate_process_tracker_status) = calculate_workflow
.map(|calculate| {
@@ -2165,12 +2178,10 @@ pub fn map_recovery_status(
calculate_process_tracker_status,
execute_business_status,
execute_process_tracker_status,
- || {
- if attempt_count > max_retry_threshold {
- RecoveryStatus::Terminated
- } else {
- RecoveryStatus::Monitoring
- }
+ || match external_trigger_next_retry {
+ Some(next_retry) => map_external_trigger_recovery_status(next_retry),
+ None if attempt_count > max_retry_threshold => RecoveryStatus::Terminated,
+ None => RecoveryStatus::Monitoring,
},
),
@@ -2218,6 +2229,7 @@ pub fn map_to_recovery_payment_item(
execute_workflow.as_ref(),
payment_intent.attempt_count,
max_retry_threshold,
+ payment_intent.get_external_trigger_next_retry(),
);
RecoveryPaymentsListResponseItem {
@@ -2387,7 +2399,8 @@ mod tests {
(IntentStatus::Failed, 3, "monitoring"),
(IntentStatus::Failed, 4, "terminated"),
] {
- let recovery_status = map_recovery_status(intent_status, None, None, attempt_count, 3);
+ let recovery_status =
+ map_recovery_status(intent_status, None, None, attempt_count, 3, None);
assert_eq!(
serde_json::to_value(recovery_status).ok(),
diff --git a/crates/router/src/core/revenue_recovery/api.rs b/crates/router/src/core/revenue_recovery/api.rs
index 2eee8842a6..bd57ed9d1d 100644
--- a/crates/router/src/core/revenue_recovery/api.rs
+++ b/crates/router/src/core/revenue_recovery/api.rs
@@ -169,16 +169,16 @@ pub async fn call_proxy_api(
pub async fn update_payment_intent_api(
state: &SessionState,
global_payment_id: id_type::GlobalPaymentId,
- revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
+ merchant_context: storage::revenue_recovery::RecoveryMerchantContext<'_>,
update_req: payments_api::PaymentsUpdateIntentRequest,
) -> RouterResult<payments_domain::PaymentIntentData<api_types::PaymentUpdateIntent>> {
// TODO : Use api handler instead of calling payments_intent_operation_core
let operation = payments::operations::PaymentUpdateIntent;
- let platform_from_revenue_recovery_payment_data = Platform::new(
- revenue_recovery_payment_data.merchant_account.clone(),
- revenue_recovery_payment_data.key_store.clone(),
- revenue_recovery_payment_data.merchant_account.clone(),
- revenue_recovery_payment_data.key_store.clone(),
+ let platform_from_merchant_context = Platform::new(
+ merchant_context.merchant_account.clone(),
+ merchant_context.key_store.clone(),
+ merchant_context.merchant_account.clone(),
+ merchant_context.key_store.clone(),
None,
);
let (payment_data, _req, _) = Box::pin(payments::payments_intent_operation_core::<
@@ -189,8 +189,8 @@ pub async fn update_payment_intent_api(
>(
state,
state.get_req_state(),
- platform_from_revenue_recovery_payment_data,
- revenue_recovery_payment_data.profile.clone(),
+ platform_from_merchant_context,
+ merchant_context.profile.clone(),
operation,
update_req,
global_payment_id,
@@ -311,7 +311,7 @@ pub async fn custom_revenue_recovery_core(
validate_recovery_amounts(&request)?;
validate_customer_information(&request)?;
- let updated_recovery_intent = match RecoveryTrigger::from_profile_settings(
+ let (updated_recovery_intent, next_retry) = match RecoveryTrigger::from_profile_settings(
profile.revenue_recovery_trigger_model,
profile.revenue_recovery_config.as_ref(),
&request,
@@ -320,7 +320,7 @@ pub async fn custom_revenue_recovery_core(
billing_merchant_connector_id,
payment_merchant_connector_id,
} => {
- Box::pin(record_transaction_and_schedule_retries(
+ let updated_recovery_intent = Box::pin(record_transaction_and_schedule_retries(
&state,
&req_state,
&platform,
@@ -329,13 +329,14 @@ pub async fn custom_revenue_recovery_core(
&billing_merchant_connector_id,
&payment_merchant_connector_id,
))
- .await?
+ .await?;
+ (updated_recovery_intent, None)
}
RecoveryTrigger::External {
connector,
retry_config,
} => {
- Box::pin(external_triggers::record_reported_transaction(
+ Box::pin(external_triggers::record_transaction_and_get_next_retry(
&state,
&req_state,
&platform,
@@ -348,14 +349,8 @@ pub async fn custom_revenue_recovery_core(
}
};
- let response = api_models::payments::RecoveryPaymentsResponse {
- id: updated_recovery_intent.payment_id.to_owned(),
- intent_status: updated_recovery_intent.status.to_owned(),
- merchant_reference_id: updated_recovery_intent.merchant_reference_id.to_owned(),
- };
-
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
- response,
+ get_recovery_payments_response(&updated_recovery_intent, next_retry),
))
}
@@ -470,6 +465,18 @@ async fn record_transaction_and_schedule_retries(
Ok(updated_recovery_intent)
}
+fn get_recovery_payments_response(
+ recovery_intent: &hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent,
+ next_retry: Option<common_types::payments::RecoveryNextRetry>,
+) -> payments_api::RecoveryPaymentsResponse {
+ payments_api::RecoveryPaymentsResponse {
+ id: recovery_intent.payment_id.to_owned(),
+ intent_status: recovery_intent.status.to_owned(),
+ merchant_reference_id: recovery_intent.merchant_reference_id.to_owned(),
+ next_retry,
+ }
+}
+
/// Finds or creates the invoice of the transaction.
pub(super) async fn get_or_create_invoice(
state: &SessionState,
@@ -578,14 +585,13 @@ pub async fn cancel_revenue_recovery_core(
})
})?;
- let response = api_payments::RecoveryPaymentsResponse {
- id: cancelled_intent.id,
- intent_status: cancelled_intent.status,
- merchant_reference_id: cancelled_intent.merchant_reference_id,
- };
-
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
- response,
+ get_recovery_payments_response(
+ &hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from(
+ &cancelled_intent,
+ ),
+ cancelled_intent.get_external_trigger_next_retry(),
+ ),
))
}
diff --git a/crates/router/src/core/revenue_recovery/external_triggers.rs b/crates/router/src/core/revenue_recovery/external_triggers.rs
index bd83895e0b..eb906d1a36 100644
--- a/crates/router/src/core/revenue_recovery/external_triggers.rs
+++ b/crates/router/src/core/revenue_recovery/external_triggers.rs
@@ -1,24 +1,134 @@
use api_models::payments::RecoveryPaymentsCreate;
-use common_types::payments::{RecoveryConnector, RecoveryConnectorDetails};
+use common_types::payments::{
+ ExternalTriggerState, RecoveryConnector, RecoveryConnectorDetails, RecoveryNextRetry,
+ RecoveryNoRetryReason, RecoveryTransactionStatus,
+};
use diesel_models::business_profile::RevenueRecoveryConfig;
use error_stack::report;
-use hyperswitch_domain_models::{platform::Platform, revenue_recovery::RecoveryPaymentIntent};
+use hyperswitch_domain_models::{
+ payments::{payment_intent::PaymentIntentUpdate, PaymentIntent},
+ platform::Platform,
+ revenue_recovery::{RecoveryPaymentAttempt, RecoveryPaymentIntent},
+};
+use hyperswitch_masking::PeekInterface;
+use router_env::logger;
+use time::{Duration, PrimitiveDateTime};
-use super::api;
+use super::{
+ api,
+ card_selection::{self, CardAvailability, CardSelection},
+ get_recovery_grace_window_end, is_retry_budget_exhausted,
+ retry_stats::RetryOutcomeEvent,
+ schedule::StaticLadderProgress,
+};
use crate::{
core::{
- errors::{self, RouterResult},
+ api_locking::{LockAction, LockingInput},
+ configs::dimension_state::{self, DimensionsWithProcessorMerchantIdAndConnector},
+ errors::{self, RouterResult, StorageErrorExt},
payments::operations::{
payment_attempt_record::PaymentAttemptRecord, ValidateStatusForOperation,
},
},
- routes::{app::ReqState, SessionState},
- types::domain,
+ routes::{app::ReqState, lock_utils, SessionState},
+ types::{
+ domain,
+ storage::{revenue_recovery as pcr, revenue_recovery_redis_operation::RedisTokenManager},
+ },
+ workflows::revenue_recovery::{self as revenue_recovery_workflow, RetryTiming},
};
-/// Records a transaction the merchant reports against the invoice, with no connector account behind
-/// it. Nothing is scheduled for it, as the merchant triggers the retries.
-pub(super) async fn record_reported_transaction(
+/// What the next retry of an invoice is decided from.
+struct NextRetryInputs<'a> {
+ payment_intent: &'a PaymentIntent,
+ dimensions: &'a DimensionsWithProcessorMerchantIdAndConnector,
+ retry_config: &'a RevenueRecoveryConfig,
+ ladder_progress: &'a StaticLadderProgress,
+ retry_count: u16,
+ last_failure_code: Option<common_enums::StandardisedCode>,
+ card_availability: CardAvailability,
+ retries_after_hard_decline: Option<u16>,
+}
+
+/// What the limits of the profile say about the next retry of an invoice.
+#[derive(Clone, Copy, Debug, Default)]
+struct RetryLimitChecks {
+ is_retry_budget_spent: bool,
+ is_grace_window_over: bool,
+ is_hard_decline_limit_reached: bool,
+ is_below_retry_threshold: bool,
+}
+
+/// What is decided about the next retry of an invoice, with the state to keep for the one after.
+struct NextRetryDecision {
+ next_retry: RecoveryNextRetry,
+ next_ladder_progress: Option<StaticLadderProgress>,
+ assigned_ab_algorithm: Option<common_enums::RevenueRecoveryABAlgorithm>,
+}
+
+impl NextRetryDecision {
+ fn not_scheduled(retry_count: u16, reason: RecoveryNoRetryReason) -> Self {
+ Self {
+ next_retry: RecoveryNextRetry::not_scheduled(retry_count, reason),
+ next_ladder_progress: None,
+ assigned_ab_algorithm: None,
+ }
+ }
+}
+
+/// Records a transaction the merchant reports and, when it was made off session with the customer
+/// absent, works out when they should trigger the next retry. The reports of an invoice are handled
+/// one at a time, as each one builds on the state the last one left, and no connector sync is there
+/// to correct a report handled out of turn.
+pub(super) async fn record_transaction_and_get_next_retry(
+ state: &SessionState,
+ req_state: &ReqState,
+ platform: &Platform,
+ profile: &domain::Profile,
+ request: &RecoveryPaymentsCreate,
+ connector: RecoveryConnector,
+ retry_config: &RevenueRecoveryConfig,
+) -> RouterResult<(RecoveryPaymentIntent, Option<RecoveryNextRetry>)> {
+ let invoice_lock = LockAction::Hold {
+ input: LockingInput {
+ unique_locking_key: request.merchant_reference_id.get_string_repr().to_owned(),
+ api_identifier: lock_utils::ApiIdentifier::Payments,
+ override_lock_retries: None,
+ },
+ };
+ let merchant_id = platform.get_processor().get_account().get_id().to_owned();
+
+ invoice_lock
+ .clone()
+ .perform_locking_action(state, merchant_id.clone())
+ .await?;
+
+ let result = Box::pin(handle_merchant_report(
+ state,
+ req_state,
+ platform,
+ profile,
+ request,
+ connector,
+ retry_config,
+ ))
+ .await;
+
+ if let Err(error) = invoice_lock.free_lock_action(state, merchant_id).await {
+ logger::error!(?error, "Failed to release the lock of the invoice");
+ }
+
+ 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.
+///
+/// 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
+/// request, apart from reading the invoice back, which fails only if the database just went away.
+async fn handle_merchant_report(
state: &SessionState,
req_state: &ReqState,
platform: &Platform,
@@ -26,7 +136,7 @@ pub(super) async fn record_reported_transaction(
request: &RecoveryPaymentsCreate,
connector: RecoveryConnector,
retry_config: &RevenueRecoveryConfig,
-) -> RouterResult<RecoveryPaymentIntent> {
+) -> RouterResult<(RecoveryPaymentIntent, Option<RecoveryNextRetry>)> {
// A value sent in the request takes priority over the one on the profile.
let request = &RecoveryPaymentsCreate {
enable_partial_authorization: request
@@ -48,7 +158,24 @@ pub(super) async fn record_reported_transaction(
})
})?;
- let (_, updated_invoice) = Box::pin(api::record_transaction(
+ let previous_recovery_metadata = invoice
+ .feature_metadata
+ .as_ref()
+ .and_then(|feature_metadata| feature_metadata.revenue_recovery.as_ref());
+ let is_existing_invoice = previous_recovery_metadata.is_some();
+ let is_same_card = previous_recovery_metadata.is_some_and(|recovery_metadata| {
+ recovery_metadata
+ .billing_connector_payment_details
+ .payment_processor_token
+ == *request
+ .payment_method_data
+ .primary_processor_payment_method_token
+ .peek()
+ });
+ let previous_trigger_state = previous_recovery_metadata
+ .and_then(|recovery_metadata| recovery_metadata.external_trigger_state.clone());
+
+ let (recovery_attempt, _) = Box::pin(api::record_transaction(
state,
req_state,
platform,
@@ -61,5 +188,482 @@ pub(super) async fn record_reported_transaction(
))
.await?;
- Ok(updated_invoice)
+ let is_merchant_initiated = request
+ .customer_present
+ .unwrap_or(common_enums::PresenceOfCustomerDuringPayment::Absent)
+ == common_enums::PresenceOfCustomerDuringPayment::Absent
+ && request
+ .setup_future_usage
+ .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
+ .store
+ .find_payment_intent_by_id(
+ &invoice.payment_id,
+ platform.get_processor().get_key_store(),
+ platform.get_processor().get_storage_scheme(),
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let updated_invoice = RecoveryPaymentIntent::from(&payment_intent);
+
+ if !is_merchant_initiated {
+ return Ok((updated_invoice, None));
+ }
+
+ let dimensions = dimension_state::Dimensions::new()
+ .with_processor_merchant_id(payment_intent.merchant_id.clone().into())
+ .with_connector(common_enums::connector_enums::Connector::Custombilling);
+ let retry_count = payment_intent
+ .get_revenue_recovery_retry_count()
+ .unwrap_or(1);
+ let max_hybrid_cascading_retry_count = dimension_state::Dimensions::new()
+ .with_processor_merchant_id(payment_intent.merchant_id.clone().into())
+ .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id())
+ .with_profile_id(payment_intent.profile_id.clone())
+ .get_recovery_max_hybrid_cascading_retry_count(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await;
+ let ladder_progress = get_ladder_progress(
+ previous_trigger_state.as_ref(),
+ is_existing_invoice,
+ retry_count,
+ max_hybrid_cascading_retry_count,
+ );
+ let last_failure_code = get_last_failure_code(request.transaction_status, &recovery_attempt);
+ let card_availability =
+ get_card_availability(state, request.connector_customer_id.peek(), &payment_intent).await;
+ let retries_after_hard_decline = get_retries_after_hard_decline(
+ previous_trigger_state
+ .as_ref()
+ .and_then(|trigger_state| trigger_state.retries_after_hard_decline),
+ is_same_card,
+ matches!(card_availability, CardAvailability::HardDecline),
+ );
+
+ let decision = Box::pin(decide_next_retry(
+ state,
+ platform,
+ profile,
+ NextRetryInputs {
+ payment_intent: &payment_intent,
+ dimensions: &dimensions,
+ retry_config,
+ ladder_progress: &ladder_progress,
+ retry_count,
+ last_failure_code,
+ card_availability,
+ retries_after_hard_decline,
+ },
+ ))
+ .await;
+
+ let trigger_state = ExternalTriggerState {
+ last_failure_code,
+ consumed_ladder_rungs: decision
+ .next_ladder_progress
+ .unwrap_or(ladder_progress)
+ .consumed_rungs,
+ retries_after_hard_decline,
+ next_retry: decision.next_retry,
+ };
+ save_trigger_state(
+ state,
+ platform,
+ payment_intent,
+ trigger_state,
+ decision.assigned_ab_algorithm,
+ )
+ .await;
+
+ Ok((updated_invoice, Some(decision.next_retry)))
+}
+
+/// A charged card is healthy again, so its retry history starts over, as it does for the retries
+/// Hyperswitch makes.
+async fn reset_card_history_after_a_charge(state: &SessionState, request: &RecoveryPaymentsCreate) {
+ match request.transaction_status {
+ RecoveryTransactionStatus::Failure => {}
+ RecoveryTransactionStatus::Charged | RecoveryTransactionStatus::PartialCharged => {
+ let reset =
+ RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
+ state,
+ request.connector_customer_id.peek(),
+ &None,
+ &None,
+ Some(
+ request
+ .payment_method_data
+ .primary_processor_payment_method_token
+ .peek()
+ .as_str(),
+ ),
+ )
+ .await;
+ if let Err(error) = reset {
+ logger::error!(
+ ?error,
+ "Failed to reset the retry history of a charged card"
+ );
+ }
+ }
+ }
+}
+
+/// Decides the next retry of an invoice: first whatever the limits of the profile rule out, then
+/// its time under the retry algorithm of the profile, then whatever the card allows.
+async fn decide_next_retry(
+ state: &SessionState,
+ platform: &Platform,
+ profile: &domain::Profile,
+ inputs: NextRetryInputs<'_>,
+) -> NextRetryDecision {
+ let NextRetryInputs {
+ payment_intent,
+ dimensions,
+ retry_config,
+ ladder_progress,
+ retry_count,
+ last_failure_code,
+ card_availability,
+ retries_after_hard_decline,
+ } = inputs;
+
+ let retry_algorithm_type = profile
+ .revenue_recovery_retry_algorithm_type
+ .unwrap_or(state.conf.revenue_recovery.retry_algorithm_type);
+ let now = common_utils::date_time::now();
+
+ let grace_window_end =
+ get_recovery_grace_window_end(payment_intent, retry_config.grace_period_days)
+ .inspect_err(|error| {
+ logger::error!(?error, "Cannot bound the invoice by its grace window");
+ })
+ .ok()
+ .filter(|grace_window_end| *grace_window_end > now);
+
+ if let Some(reason) = get_no_retry_reason(
+ payment_intent.status,
+ retry_algorithm_type,
+ RetryLimitChecks {
+ is_retry_budget_spent: is_retry_budget_exhausted(
+ retry_count,
+ retry_config.max_retry_count,
+ ),
+ is_grace_window_over: grace_window_end.is_none(),
+ is_hard_decline_limit_reached: retries_after_hard_decline
+ .is_some_and(|retries| retries >= retry_config.max_hard_decline_retries),
+ is_below_retry_threshold: retry_count < retry_config.billing_connector_retry_threshold,
+ },
+ ) {
+ return NextRetryDecision::not_scheduled(retry_count, reason);
+ }
+ let Some(grace_window_end) = grace_window_end else {
+ return NextRetryDecision::not_scheduled(
+ retry_count,
+ RecoveryNoRetryReason::GracePeriodExceeded,
+ );
+ };
+
+ let retry_timing = Box::pin(revenue_recovery_workflow::get_retry_timing(
+ state,
+ revenue_recovery_workflow::RetryTimingParams {
+ payment_intent,
+ retry_algorithm_type,
+ retry_count: u32::from(retry_count),
+ prev_attempt_error_code: last_failure_code,
+ static_ladder_progress: ladder_progress,
+ remaining_grace_days: u32::try_from((grace_window_end - now).whole_days().max(0))
+ .unwrap_or(0),
+ remaining_budget: u32::from(retry_config.max_retry_count)
+ .saturating_sub(u32::from(retry_count)),
+ provider_merchant_id: platform.get_provider().get_provider_merchant_id(),
+ merchant_context: pcr::RecoveryMerchantContext {
+ merchant_account: platform.get_processor().get_account(),
+ key_store: platform.get_processor().get_key_store().inner(),
+ profile,
+ },
+ },
+ dimensions,
+ ))
+ .await;
+
+ let (retry_time, next_ladder_progress, assigned_ab_algorithm) = match retry_timing {
+ Ok(RetryTiming::At {
+ retry_time,
+ next_static_ladder_progress,
+ assigned_ab_algorithm,
+ }) => (
+ retry_time,
+ next_static_ladder_progress,
+ assigned_ab_algorithm,
+ ),
+ Ok(RetryTiming::Decider) => {
+ match revenue_recovery_workflow::get_schedule_time_to_retry_mit_payments(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ dimensions,
+ u32::from(retry_count),
+ )
+ .await
+ {
+ Some(retry_time) => (retry_time, None, None),
+ None => {
+ return NextRetryDecision::not_scheduled(
+ retry_count,
+ RecoveryNoRetryReason::RetriesExhausted,
+ )
+ }
+ }
+ }
+ Ok(RetryTiming::NoRetries) => {
+ return NextRetryDecision::not_scheduled(retry_count, RecoveryNoRetryReason::Monitoring)
+ }
+ Ok(RetryTiming::LadderExhausted) => {
+ return NextRetryDecision::not_scheduled(
+ retry_count,
+ RecoveryNoRetryReason::RetriesExhausted,
+ )
+ }
+ Err(error) => {
+ logger::error!(
+ ?error,
+ "No time is available for the next retry of the invoice"
+ );
+ return NextRetryDecision::not_scheduled(
+ retry_count,
+ RecoveryNoRetryReason::RetriesExhausted,
+ );
+ }
+ };
+
+ let next_retry = get_next_retry(
+ retry_count,
+ revenue_recovery_workflow::add_random_delay_to_schedule_time(state, retry_time),
+ &card_availability,
+ Duration::seconds(
+ state
+ .conf
+ .revenue_recovery
+ .recovery_timestamp
+ .job_schedule_buffer_time_in_seconds,
+ ),
+ grace_window_end,
+ now,
+ );
+
+ NextRetryDecision {
+ next_retry,
+ next_ladder_progress: next_ladder_progress.filter(|_| next_retry.schedule_time.is_some()),
+ assigned_ab_algorithm,
+ }
+}
+
+/// Where the card of the invoice stands. The merchant picks the card of a retry, so only that card
+/// is considered. A failed lookup does not hold the retry back, the merchant is still given a time.
+async fn get_card_availability(
+ state: &SessionState,
+ connector_customer_id: &str,
+ payment_intent: &PaymentIntent,
+) -> CardAvailability {
+ let invoice_token =
+ revenue_recovery_workflow::get_invoice_payment_processor_token(payment_intent);
+
+ match RedisTokenManager::get_payment_processor_metadata_for_connector_customer(
+ state,
+ connector_customer_id,
+ )
+ .await
+ {
+ Ok(tokens) => card_selection::pick_card_for_retry_time(
+ CardSelection::InvoiceCard,
+ &tokens,
+ invoice_token.as_deref(),
+ ),
+ Err(error) => {
+ logger::error!(?error, "Failed to read the retry history of the card");
+ CardAvailability::NoCard
+ }
+ }
+}
+
+/// Keeps what the next report of the merchant needs on the invoice. Failing here costs the next
+/// retry its cluster and ladder position, not the answer to this report.
+async fn save_trigger_state(
+ state: &SessionState,
+ platform: &Platform,
+ payment_intent: PaymentIntent,
+ trigger_state: ExternalTriggerState,
+ assigned_ab_algorithm: Option<common_enums::RevenueRecoveryABAlgorithm>,
+) {
+ let mut feature_metadata = payment_intent.feature_metadata.clone();
+ if let Some(recovery_metadata) = feature_metadata
+ .as_mut()
+ .and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.as_mut())
+ {
+ recovery_metadata.external_trigger_state = Some(trigger_state);
+ recovery_metadata.revenue_recovery_ab_routing =
+ assigned_ab_algorithm.or(recovery_metadata.revenue_recovery_ab_routing);
+ }
+
+ let storage_scheme = platform.get_processor().get_storage_scheme();
+ let intent_update = PaymentIntentUpdate::FeatureMetadataUpdate {
+ feature_metadata: Box::new(feature_metadata),
+ updated_by: storage_scheme.inner().to_string(),
+ };
+
+ if let Err(error) = state
+ .store
+ .update_payment_intent(
+ payment_intent,
+ intent_update,
+ platform.get_processor().get_key_store(),
+ storage_scheme,
+ )
+ .await
+ {
+ logger::error!(?error, "Failed to save the recovery state of the invoice");
+ }
+}
+
+/// Where the invoice stands on the static ladder: what the last report saved, or else a position
+/// worked out from the retries already made.
+fn get_ladder_progress(
+ previous_trigger_state: Option<&ExternalTriggerState>,
+ is_existing_invoice: bool,
+ retry_count: u16,
+ max_hybrid_cascading_retry_count: u32,
+) -> StaticLadderProgress {
+ match previous_trigger_state {
+ Some(ExternalTriggerState {
+ next_retry:
+ RecoveryNextRetry {
+ reason: Some(RecoveryNoRetryReason::BelowRetryThreshold),
+ ..
+ },
+ ..
+ }) => StaticLadderProgress::seed_for_new_invoice(
+ retry_count,
+ max_hybrid_cascading_retry_count,
+ ),
+ Some(trigger_state) => StaticLadderProgress {
+ consumed_rungs: trigger_state.consumed_ladder_rungs,
+ },
+ None if is_existing_invoice => StaticLadderProgress::seed_for_existing_invoice(
+ retry_count,
+ max_hybrid_cascading_retry_count,
+ ),
+ None => StaticLadderProgress::seed_for_new_invoice(
+ retry_count,
+ max_hybrid_cascading_retry_count,
+ ),
+ }
+}
+
+/// Retries made with the card of the invoice since it was first hard declined. A hard decline is
+/// about the card, so a report on another card starts over.
+fn get_retries_after_hard_decline(
+ previous_retries: Option<u16>,
+ is_same_card: bool,
+ is_hard_declined: bool,
+) -> Option<u16> {
+ match previous_retries.filter(|_| is_same_card) {
+ Some(retries) => Some(retries.saturating_add(1)),
+ None => is_hard_declined.then_some(0),
+ }
+}
+
+/// 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.
+fn get_last_failure_code(
+ transaction_status: RecoveryTransactionStatus,
+ recovery_attempt: &RecoveryPaymentAttempt,
+) -> Option<common_enums::StandardisedCode> {
+ match transaction_status {
+ RecoveryTransactionStatus::Failure => recovery_attempt.standardised_error_code,
+ RecoveryTransactionStatus::Charged | RecoveryTransactionStatus::PartialCharged => None,
+ }
+}
+
+/// 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,
+ retry_algorithm_type: common_enums::RevenueRecoveryAlgorithmType,
+ limit_checks: RetryLimitChecks,
+) -> Option<RecoveryNoRetryReason> {
+ if invoice_status == common_enums::IntentStatus::Succeeded {
+ Some(RecoveryNoRetryReason::Recovered)
+ } else if retry_algorithm_type == common_enums::RevenueRecoveryAlgorithmType::Monitoring {
+ Some(RecoveryNoRetryReason::Monitoring)
+ } else if limit_checks.is_retry_budget_spent {
+ Some(RecoveryNoRetryReason::RetriesExhausted)
+ } else if limit_checks.is_grace_window_over {
+ Some(RecoveryNoRetryReason::GracePeriodExceeded)
+ } else if limit_checks.is_hard_decline_limit_reached {
+ Some(RecoveryNoRetryReason::HardDecline)
+ } else if limit_checks.is_below_retry_threshold {
+ Some(RecoveryNoRetryReason::BelowRetryThreshold)
+ } else {
+ None
+ }
+}
+
+/// The next retry once its time is known, given where the card stands and when the grace window of
+/// the invoice closes.
+fn get_next_retry(
+ retry_count: u16,
+ retry_time: PrimitiveDateTime,
+ card_availability: &CardAvailability,
+ card_wait_buffer: Duration,
+ grace_window_end: PrimitiveDateTime,
+ now: PrimitiveDateTime,
+) -> RecoveryNextRetry {
+ let schedule_time = match card_availability {
+ CardAvailability::Ready { .. }
+ | CardAvailability::NoCard
+ | CardAvailability::HardDecline => retry_time,
+ CardAvailability::WaitHours(wait_hours) => retry_time.max(
+ now.saturating_add(Duration::hours(*wait_hours))
+ .saturating_add(card_wait_buffer),
+ ),
+ };
+
+ if schedule_time >= grace_window_end {
+ RecoveryNextRetry::not_scheduled(retry_count, RecoveryNoRetryReason::GracePeriodExceeded)
+ } else {
+ RecoveryNextRetry::scheduled(retry_count, schedule_time)
+ }
}
diff --git a/crates/router/src/core/revenue_recovery/retry_stats/events.rs b/crates/router/src/core/revenue_recovery/retry_stats/events.rs
index 94108a3b32..463f9620b4 100644
--- a/crates/router/src/core/revenue_recovery/retry_stats/events.rs
+++ b/crates/router/src/core/revenue_recovery/retry_stats/events.rs
@@ -45,6 +45,16 @@ impl RetryOutcomeEvent {
payment_attempt: &PaymentAttempt,
standardised_error_code: Option<StandardisedCode>,
success: bool,
+ ) -> Self {
+ Self::from_retry_outcome(payment_attempt.created_at, standardised_error_code, success)
+ }
+
+ /// Build an event from when a retry ran, the previous attempt's standardised error code and
+ /// whether the retry succeeded. A `None` code maps to the `Unknown` error-code dimension.
+ pub fn from_retry_outcome(
+ created_at: PrimitiveDateTime,
+ standardised_error_code: Option<StandardisedCode>,
+ success: bool,
) -> Self {
let error_code_dim = match standardised_error_code {
Some(code) => Dim::Val(code),
@@ -55,7 +65,7 @@ impl RetryOutcomeEvent {
Dim::Unknown,
Dim::Unknown,
success,
- payment_attempt.created_at,
+ created_at,
)
}
}
diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs
index 80afa29b60..719b6b32aa 100644
--- a/crates/router/src/core/revenue_recovery/types.rs
+++ b/crates/router/src/core/revenue_recovery/types.rs
@@ -891,7 +891,7 @@ impl Action {
Box::pin(revenue_recovery_core::api::update_payment_intent_api(
state,
payment_intent.id.clone(),
- revenue_recovery_payment_data,
+ revenue_recovery_payment_data.get_merchant_context(),
payment_update_req,
))
.await
diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs
index aba45a3cbe..806dfbecc5 100644
--- a/crates/router/src/core/webhooks/recovery_incoming.rs
+++ b/crates/router/src/core/webhooks/recovery_incoming.rs
@@ -75,6 +75,16 @@ pub async fn recovery_incoming_webhook_flow(
))
})?;
+ if business_profile.revenue_recovery_trigger_model
+ == common_enums::RevenueRecoveryTriggerModel::ExternalTriggers
+ {
+ logger::info!(
+ profile_id = ?business_profile.get_id(),
+ "Ignoring the billing connector webhook of a profile whose retries the merchant triggers"
+ );
+ return Ok(webhooks::WebhookResponseTracker::NoEffect);
+ }
+
let connector = api_enums::Connector::from_str(connector_name)
.change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?;
diff --git a/crates/router/src/types/storage/revenue_recovery.rs b/crates/router/src/types/storage/revenue_recovery.rs
index 37bfedfd3f..2aef53f842 100644
--- a/crates/router/src/types/storage/revenue_recovery.rs
+++ b/crates/router/src/types/storage/revenue_recovery.rs
@@ -51,7 +51,24 @@ pub struct RevenueRecoveryPaymentData {
pub retry_algorithm: enums::RevenueRecoveryAlgorithmType,
pub psync_data: Option<PaymentStatusData<types::api::PSync>>,
}
+
+/// The merchant and profile an invoice belongs to.
+#[derive(Clone, Copy)]
+pub struct RecoveryMerchantContext<'a> {
+ pub merchant_account: &'a merchant_account::MerchantAccount,
+ pub key_store: &'a merchant_key_store::MerchantKeyStore,
+ pub profile: &'a business_profile::Profile,
+}
+
impl RevenueRecoveryPaymentData {
+ pub fn get_merchant_context(&self) -> RecoveryMerchantContext<'_> {
+ RecoveryMerchantContext {
+ merchant_account: &self.merchant_account,
+ key_store: &self.key_store,
+ profile: &self.profile,
+ }
+ }
+
pub async fn get_schedule_time_based_on_retry_type(
&self,
state: &SessionState,
diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rs
index a8d64dd8f2..b1e986e3eb 100644
--- a/crates/router/src/workflows/revenue_recovery.rs
+++ b/crates/router/src/workflows/revenue_recovery.rs
@@ -716,11 +716,11 @@ async fn get_retry_time_for_error_code(
async fn get_ab_routed_retry_time(
state: &SessionState,
payment_intent: &PaymentIntent,
- tracking_data: &pcr_storage_types::RevenueRecoveryWorkflowTrackingData,
+ prev_attempt_error_code: Option<common_enums::StandardisedCode>,
remaining_grace_days: u32,
remaining_budget: u32,
// Both needed only to assign an implementation to an invoice that arrives without one
- revenue_recovery_payment_data: &pcr_storage_types::RevenueRecoveryPaymentData,
+ merchant_context: pcr_storage_types::RecoveryMerchantContext<'_>,
ab_dimensions: &crate::core::configs::dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndOrgIdAndProfileId,
) -> (
Option<time::PrimitiveDateTime>,
@@ -755,7 +755,7 @@ async fn get_ab_routed_retry_time(
.feature_metadata
.as_ref()
.map(api_models::payments::FeatureMetadata::foreign_from),
- revenue_recovery_payment_data,
+ merchant_context,
ab_dimensions,
)
.await
@@ -765,7 +765,7 @@ async fn get_ab_routed_retry_time(
let schedule_time = get_retry_time_for_error_code(
state,
assigned_algorithm,
- tracking_data.prev_attempt_error_code,
+ prev_attempt_error_code,
remaining_grace_days,
remaining_budget,
)
@@ -783,82 +783,82 @@ async fn get_ab_routed_retry_time(
/// When a retry runs, as the algorithm decides it. Which card it is made with is decided apart
/// from this, by the card selection.
#[cfg(feature = "v2")]
-enum RetryTiming {
+pub(crate) enum RetryTiming {
/// One time for the invoice, from the cascading ladder or the retry model, with the ladder
- /// position to carry back if a retry is scheduled at it.
+ /// position to carry back if a retry is scheduled at it and the A/B arm the invoice ran.
At {
retry_time: time::PrimitiveDateTime,
next_static_ladder_progress: Option<pcr::schedule::StaticLadderProgress>,
+ assigned_ab_algorithm: Option<common_enums::RevenueRecoveryABAlgorithm>,
},
/// The decider's time, asked of each card the selection admits.
Decider,
+ /// The algorithm does not retry invoices.
+ NoRetries,
+ /// The cascading ladder has no slot left for this invoice.
+ LadderExhausted,
}
+/// What the retry time of an invoice is worked out from, whoever triggers the retry.
#[cfg(feature = "v2")]
-#[allow(clippy::too_many_arguments)]
-pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
- state: &SessionState,
- connector_customer_id: &str,
- payment_intent: &PaymentIntent,
- billing_connector: common_enums::connector_enums::Connector,
- retry_algorithm_type: RevenueRecoveryAlgorithmType,
- retry_count: u32,
- tracking_data: &pcr_storage_types::RevenueRecoveryWorkflowTrackingData,
- static_ladder_progress: &pcr::schedule::StaticLadderProgress,
+pub(crate) struct RetryTimingParams<'a> {
+ pub payment_intent: &'a PaymentIntent,
+ pub retry_algorithm_type: RevenueRecoveryAlgorithmType,
+ pub retry_count: u32,
+ pub prev_attempt_error_code: Option<common_enums::StandardisedCode>,
+ pub static_ladder_progress: &'a pcr::schedule::StaticLadderProgress,
+ pub remaining_grace_days: u32,
+ pub remaining_budget: u32,
// Needed only to resolve the A/B gate
- provider_merchant_id: hyperswitch_domain_models::platform::ProviderMerchantId,
- remaining_grace_days: u32,
- remaining_budget: u32,
+ pub provider_merchant_id: hyperswitch_domain_models::platform::ProviderMerchantId,
// Needed only to assign an implementation to an invoice that arrives without one
- revenue_recovery_payment_data: &pcr_storage_types::RevenueRecoveryPaymentData,
-) -> CustomResult<
- (
- PaymentProcessorTokenResponse,
- Option<pcr::schedule::StaticLadderProgress>,
- ),
- errors::ProcessTrackerError,
-> {
- let dimensions = crate::core::configs::dimension_state::Dimensions::new()
- .with_processor_merchant_id(payment_intent.merchant_id.clone().into())
- .with_connector(billing_connector);
+ pub merchant_context: pcr_storage_types::RecoveryMerchantContext<'a>,
+}
- // The algorithm below decides only when the retry runs. Which card it is made with is settled
- // here by the card switching flag alone, so it is the same whichever algorithm runs.
- let card_selection = CardSelection::from_card_switching_enabled(
- dimensions
- .get_card_switching_enabled(
- state.store.as_ref(),
- state.superposition_service.as_ref(),
- None,
- )
- .await,
- );
+/// When the next retry of an invoice runs, under the retry algorithm.
+#[cfg(feature = "v2")]
+pub(crate) async fn get_retry_timing(
+ state: &SessionState,
+ params: RetryTimingParams<'_>,
+ dimensions: &crate::core::configs::dimension_state::DimensionsWithProcessorMerchantIdAndConnector,
+) -> CustomResult<RetryTiming, errors::ProcessTrackerError> {
+ let RetryTimingParams {
+ payment_intent,
+ retry_algorithm_type,
+ retry_count,
+ prev_attempt_error_code,
+ static_ladder_progress,
+ remaining_grace_days,
+ remaining_budget,
+ provider_merchant_id,
+ merchant_context,
+ } = params;
let retry_timing = match retry_algorithm_type {
RevenueRecoveryAlgorithmType::Monitoring => {
logger::error!("Monitoring type found for Revenue Recovery retry payment");
- return Ok((PaymentProcessorTokenResponse::None, None));
+ RetryTiming::NoRetries
}
RevenueRecoveryAlgorithmType::Cascading => {
let schedule_time = get_schedule_time_to_retry_mit_payments(
state.store.as_ref(),
state.superposition_service.as_ref(),
- &dimensions,
+ dimensions,
retry_count,
)
.await;
- // Distinct from `None` below, which means "no token right now, come back later" and
- // keeps the calculate job alive.
- let Some(time) = schedule_time else {
- logger::info!(retry_count, "Retry ladder exhausted for this invoice");
- return Ok((PaymentProcessorTokenResponse::RetriesExhausted, None));
- };
-
- RetryTiming::At {
- retry_time: time,
- next_static_ladder_progress: None,
+ match schedule_time {
+ Some(time) => RetryTiming::At {
+ retry_time: time,
+ next_static_ladder_progress: None,
+ assigned_ab_algorithm: None,
+ },
+ None => {
+ logger::info!(retry_count, "Retry ladder exhausted for this invoice");
+ RetryTiming::LadderExhausted
+ }
}
}
@@ -899,16 +899,16 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
let (time, algorithm) = get_ab_routed_retry_time(
state,
payment_intent,
- tracking_data,
+ prev_attempt_error_code,
remaining_grace_days,
remaining_budget,
- revenue_recovery_payment_data,
+ merchant_context,
&ab_dimensions,
)
.await;
(time, Some(algorithm))
} else {
- let time = match tracking_data.prev_attempt_error_code {
+ let time = match prev_attempt_error_code {
// Not enrolled in A/B routing, so this runs the baseline pairing.
Some(error_code) => compute_model_retry_time(
state,
@@ -971,7 +971,7 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
get_schedule_time_to_retry_adaptive_payments(
state.store.as_ref(),
state.superposition_service.as_ref(),
- &dimensions,
+ dimensions,
queried_rung,
)
.await
@@ -994,7 +994,7 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
get_schedule_time_to_retry_mit_payments(
state.store.as_ref(),
state.superposition_service.as_ref(),
- &dimensions,
+ dimensions,
retry_count,
)
.await
@@ -1015,7 +1015,7 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
retry_count = retry_count,
queried_rung = queried_rung,
ladder_role = ?ladder_role,
- error_code = ?tracking_data.prev_attempt_error_code,
+ error_code = ?prev_attempt_error_code,
remaining_grace_days = remaining_grace_days,
remaining_budget = remaining_budget,
"No retry time available — every source in play declined and the MIT \
@@ -1046,7 +1046,7 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
static_time = ?static_time,
fallback_time = ?fallback_time,
consumed_rungs = decision.next_progress.consumed_rungs,
- error_code = ?tracking_data.prev_attempt_error_code,
+ error_code = ?prev_attempt_error_code,
remaining_grace_days = remaining_grace_days,
remaining_budget = remaining_budget,
ab_enabled = ab_enabled,
@@ -1057,6 +1057,7 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
RetryTiming::At {
retry_time: decision.schedule_time,
next_static_ladder_progress: Some(decision.next_progress),
+ assigned_ab_algorithm: assigned_algorithm,
}
} else {
RetryTiming::Decider
@@ -1064,12 +1065,81 @@ pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
}
};
+ Ok(retry_timing)
+}
+
+#[cfg(feature = "v2")]
+#[allow(clippy::too_many_arguments)]
+pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
+ state: &SessionState,
+ connector_customer_id: &str,
+ payment_intent: &PaymentIntent,
+ billing_connector: common_enums::connector_enums::Connector,
+ retry_algorithm_type: RevenueRecoveryAlgorithmType,
+ retry_count: u32,
+ tracking_data: &pcr_storage_types::RevenueRecoveryWorkflowTrackingData,
+ static_ladder_progress: &pcr::schedule::StaticLadderProgress,
+ // Needed only to resolve the A/B gate
+ provider_merchant_id: hyperswitch_domain_models::platform::ProviderMerchantId,
+ remaining_grace_days: u32,
+ remaining_budget: u32,
+ // Needed only to assign an implementation to an invoice that arrives without one
+ revenue_recovery_payment_data: &pcr_storage_types::RevenueRecoveryPaymentData,
+) -> CustomResult<
+ (
+ PaymentProcessorTokenResponse,
+ Option<pcr::schedule::StaticLadderProgress>,
+ ),
+ errors::ProcessTrackerError,
+> {
+ let dimensions = crate::core::configs::dimension_state::Dimensions::new()
+ .with_processor_merchant_id(payment_intent.merchant_id.clone().into())
+ .with_connector(billing_connector);
+
+ // The algorithm below decides only when the retry runs. Which card it is made with is settled
+ // here by the card switching flag alone, so it is the same whichever algorithm runs.
+ let card_selection = CardSelection::from_card_switching_enabled(
+ dimensions
+ .get_card_switching_enabled(
+ state.store.as_ref(),
+ state.superposition_service.as_ref(),
+ None,
+ )
+ .await,
+ );
+
+ let retry_timing = Box::pin(get_retry_timing(
+ state,
+ RetryTimingParams {
+ payment_intent,
+ retry_algorithm_type,
+ retry_count,
+ prev_attempt_error_code: tracking_data.prev_attempt_error_code,
+ static_ladder_progress,
+ remaining_grace_days,
+ remaining_budget,
+ provider_merchant_id,
+ merchant_context: revenue_recovery_payment_data.get_merchant_context(),
+ },
+ &dimensions,
+ ))
+ .await?;
+
// Ladder position to write back onto the CALCULATE row. `None` leaves the stored count alone,
// which is the case for every outcome but one — see where it is set.
let (mut payment_processor_token_response, next_static_ladder_progress) = match retry_timing {
+ RetryTiming::NoRetries => return Ok((PaymentProcessorTokenResponse::None, None)),
+
+ // Distinct from `None`, which means "no token right now, come back later" and keeps the
+ // calculate job alive.
+ RetryTiming::LadderExhausted => {
+ return Ok((PaymentProcessorTokenResponse::RetriesExhausted, None))
+ }
+
RetryTiming::At {
retry_time,
next_static_ladder_progress,
+ assigned_ab_algorithm: _,
} => {
let payment_processor_token_response = get_token_availability_for_schedule_time(
state,