Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(revenue_recovery): record transactions without connector accounts on external triggers (#15154)
CHALLA NISHANTH BABUc08fb8bf9e3f
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex 410bf8c767..8bf18ada2f 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -4924,13 +4924,13 @@"Revenue Recovery"],"summary": "Revenue Recovery - Create",- "description": "Record a transaction made outside of Hyperswitch against a billing connector invoice.",+ "description": "Record a transaction made outside of Hyperswitch against an invoice.","operationId": "Create a Revenue Recovery Payment","parameters": [{"name": "X-Profile-Id","in": "header",- "description": "Unique identifier of the business profile under which the invoice is processed. The billing and payment merchant connector accounts in the request must belong to this profile.",+ "description": "Unique identifier of the business profile under which the invoice is processed. Any billing and payment merchant connector accounts in the request must belong to this profile.","required": true,"schema": {"type": "string"@@ -4994,6 +4994,59 @@"transaction_created_at": "2022-09-10T10:11:12Z","transaction_status": "failure"}+ },+ "Record a failed transaction on a profile with external triggers": {+ "value": {+ "amount_details": {+ "currency": "USD",+ "order_amount": 6540+ },+ "billing": {+ "address": {+ "city": "San Francisco",+ "country": "US",+ "first_name": "John",+ "last_name": "Doe",+ "line1": "1467 Harrison Street",+ "state": "California",+ "zip": "94122"+ },+ "email": "[email protected]",+ "phone": {+ "country_code": "+1",+ "number": "9123456789"+ }+ },+ "billing_started_at": "2022-09-10T10:11:12Z",+ "connector": "stripe",+ "connector_customer_id": "cust_12345",+ "connector_transaction_id": "993672945374576J",+ "error": {+ "code": "card_declined",+ "message": "The card was declined.",+ "network_advice_code": "01",+ "network_decline_code": "51",+ "network_error_message": "Retry after some time",+ "reason": "Insufficient funds"+ },+ "merchant_reference_id": "invoice_mbabizu24mvu3mela5njyh",+ "payment_method_data": {+ "payment_method_metadata": {+ "card_exp_month": "01",+ "card_exp_year": "2026",+ "card_extended_bin": "42424242",+ "card_isin": "424242",+ "card_network": "Visa",+ "card_type": "credit",+ "last4": "4242"+ },+ "primary_processor_payment_method_token": "token_1234"+ },+ "payment_method_sub_type": "credit",+ "payment_method_type": "card",+ "transaction_created_at": "2022-09-10T10:11:12Z",+ "transaction_status": "failure"+ }}}}@@ -5017,7 +5070,7 @@}},"400": {- "description": "Missing or invalid mandatory fields",+ "description": "Missing or invalid mandatory fields, or the invoice takes no more transactions","content": {"application/json": {"schema": {@@ -25950,8 +26003,6 @@"type": "object","required": ["total_retry_count",- "billing_connector_id",- "active_attempt_payment_connector_id","billing_connector_payment_details","payment_method_type","payment_method_subtype",@@ -25976,13 +26027,15 @@},"billing_connector_id": {"type": "string",- "description": "Billing Connector Id to update the invoices",- "example": "mca_1234567890"+ "description": "Billing Connector Id to update the invoices. Absent when the transaction is recorded without merchant connector accounts.",+ "example": "mca_1234567890",+ "nullable": true},"active_attempt_payment_connector_id": {"type": "string",- "description": "Payment Connector Id to retry the payments",- "example": "mca_1234567890"+ "description": "Payment Connector Id to retry the payments. Absent when the transaction is recorded without merchant connector accounts.",+ "example": "mca_1234567890",+ "nullable": true},"billing_connector_payment_details": {"$ref": "#/components/schemas/BillingConnectorPaymentDetails"@@ -31806,13 +31859,20 @@}}},+ "RecoveryConnector": {+ "type": "string",+ "description": "Payment processor on which the reported transaction was made. Any other value is refused, as\nthe standardised error code of a transaction is looked up by its processor.",+ "enum": [+ "adyen",+ "stripe",+ "paypal"+ ]+ },"RecoveryPaymentsCreate": {"type": "object","required": ["amount_details","merchant_reference_id",- "billing_merchant_connector_id",- "payment_merchant_connector_id","transaction_status","payment_method_type","payment_method_sub_type",@@ -31843,13 +31903,23 @@},"billing_merchant_connector_id": {"type": "string",- "description": "Unique identifier assigned by Hyperswitch for the custom billing connector account. The account must belong to the profile passed in the `X-Profile-Id` header.",- "example": "mca_1234567890"+ "description": "Unique identifier assigned by Hyperswitch for the custom billing connector account. The account must belong to the profile passed in the `X-Profile-Id` header. Required when the `revenue_recovery_trigger_model` of the profile is `internal_triggers`, and ignored when it is `external_triggers`.",+ "example": "mca_1234567890",+ "nullable": true},"payment_merchant_connector_id": {"type": "string",- "description": "Unique identifier assigned by Hyperswitch for the payment connector account, such as Stripe, on which the transaction was processed. The account must belong to the profile passed in the `X-Profile-Id` header.",- "example": "mca_1234567890"+ "description": "Unique identifier assigned by Hyperswitch for the payment connector account, such as Stripe, on which the transaction was processed. The account must belong to the profile passed in the `X-Profile-Id` header. Required when the `revenue_recovery_trigger_model` of the profile is `internal_triggers`, and ignored when it is `external_triggers`.",+ "example": "mca_1234567890",+ "nullable": true+ },+ "connector": {+ "allOf": [+ {+ "$ref": "#/components/schemas/RecoveryConnector"+ }+ ],+ "nullable": true},"transaction_status": {"$ref": "#/components/schemas/RecoveryTransactionStatus"diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 858911bc8a..29c8b8a95d 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -14818,12 +14818,12 @@ pub struct PaymentRevenueRecoveryMetadata {pub total_retry_count: u16,/// Flag for the payment connector's callpub payment_connector_transmission: Option<PaymentConnectorTransmission>,- /// Billing Connector Id to update the invoices- #[schema(value_type = String, example = "mca_1234567890")]- pub billing_connector_id: id_type::MerchantConnectorAccountId,- /// Payment Connector Id to retry the payments- #[schema(value_type = String, example = "mca_1234567890")]- pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId,+ /// Billing Connector Id to update the invoices. Absent when the transaction is recorded without merchant connector accounts.+ #[schema(value_type = Option<String>, example = "mca_1234567890")]+ pub billing_connector_id: Option<id_type::MerchantConnectorAccountId>,+ /// Payment Connector Id to retry the payments. Absent when the transaction is recorded without merchant connector accounts.+ #[schema(value_type = Option<String>, example = "mca_1234567890")]+ pub active_attempt_payment_connector_id: Option<id_type::MerchantConnectorAccountId>,/// Billing Connector Payment Details#[schema(value_type = BillingConnectorPaymentDetails)]pub billing_connector_payment_details: BillingConnectorPaymentDetails,@@ -14905,17 +14905,17 @@ impl PaymentRevenueRecoveryMetadata {) {self.payment_connector_transmission = Some(payment_connector_transmission);}- pub fn get_payment_token_for_api_request(&self) -> mandates::ProcessorPaymentToken {- mandates::ProcessorPaymentToken {- processor_payment_token: self- .billing_connector_payment_details- .payment_processor_token- .clone(),- merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()),- }- }- pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId {- self.active_attempt_payment_connector_id.clone()++ /// The connector accounts the invoice is recorded against. An invoice on external triggers has+ /// none.+ pub fn get_connector_accounts(+ &self,+ ) -> Option<common_payments_types::RecoveryConnectorAccounts> {+ Some(common_payments_types::RecoveryConnectorAccounts {+ billing_connector_id: self.billing_connector_id.clone()?,+ payment_connector_id: self.active_attempt_payment_connector_id.clone()?,+ connector: self.connector,+ })}pub fn get_connector_customer_id(&self) -> String {@@ -14974,17 +14974,9 @@ pub struct PaymentsAttemptRecordRequest {#[schema(value_type = PaymentMethod, example = "bank_transfer")]pub payment_method_type: api_enums::PaymentMethod,- /// The name of the payment connector through which the payment attempt was made.- #[schema(value_type = Option<Connector>, example = "stripe")]- pub connector: Option<common_enums::connector_enums::Connector>,-- /// Billing connector id to update the invoices.- #[schema(value_type = String, example = "mca_1234567890")]- pub billing_connector_id: id_type::MerchantConnectorAccountId,-- /// Billing connector id to update the invoices.- #[schema(value_type = String, example = "mca_1234567890")]- pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,+ /// What is known about the connector of the transaction, which decides how it is recorded.+ #[schema(value_type = Object)]+ pub connector_details: common_payments_types::RecoveryConnectorDetails,/// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided#[schema(value_type = PaymentMethodType, example = "apple_pay")]@@ -15060,13 +15052,17 @@ pub struct RecoveryPaymentsCreate {/// Error details of a failed transaction.pub error: Option<ErrorDetails>,- /// Unique identifier assigned by Hyperswitch for the custom billing connector account. The account must belong to the profile passed in the `X-Profile-Id` header.- #[schema(value_type = String, example = "mca_1234567890")]- pub billing_merchant_connector_id: id_type::MerchantConnectorAccountId,+ /// Unique identifier assigned by Hyperswitch for the custom billing connector account. The account must belong to the profile passed in the `X-Profile-Id` header. Required when the `revenue_recovery_trigger_model` of the profile is `internal_triggers`, and ignored when it is `external_triggers`.+ #[schema(value_type = Option<String>, example = "mca_1234567890")]+ pub billing_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,++ /// Unique identifier assigned by Hyperswitch for the payment connector account, such as Stripe, on which the transaction was processed. The account must belong to the profile passed in the `X-Profile-Id` header. Required when the `revenue_recovery_trigger_model` of the profile is `internal_triggers`, and ignored when it is `external_triggers`.+ #[schema(value_type = Option<String>, example = "mca_1234567890")]+ pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,- /// Unique identifier assigned by Hyperswitch for the payment connector account, such as Stripe, on which the transaction was processed. The account must belong to the profile passed in the `X-Profile-Id` header.- #[schema(value_type = String, example = "mca_1234567890")]- pub payment_merchant_connector_id: id_type::MerchantConnectorAccountId,+ /// Payment processor on which the transaction was processed. Required when the `revenue_recovery_trigger_model` of the profile is `external_triggers`, and ignored when it is `internal_triggers`, where the processor comes from `payment_merchant_connector_id`.+ #[schema(value_type = Option<RecoveryConnector>, example = "stripe")]+ pub connector: Option<common_payments_types::RecoveryConnector>,/// Status of the transaction reported.#[schema(value_type = RecoveryTransactionStatus, example = "failure")]diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rsindex db36d4b787..785c3374cd 100644--- a/crates/common_types/src/payments.rs+++ b/crates/common_types/src/payments.rs@@ -1019,6 +1019,89 @@ impl From<RecoveryTransactionStatus> for common_enums::AttemptStatus {}}+/// Payment processor on which the reported transaction was made. Any other value is refused, as+/// the standardised error code of a transaction is looked up by its processor.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum RecoveryConnector {+ /// Adyen.+ Adyen,+ /// Stripe.+ Stripe,+ /// PayPal.+ Paypal,+}++impl From<RecoveryConnector> for common_enums::connector_enums::Connector {+ fn from(connector: RecoveryConnector) -> Self {+ match connector {+ RecoveryConnector::Adyen => Self::Adyen,+ RecoveryConnector::Stripe => Self::Stripe,+ RecoveryConnector::Paypal => Self::Paypal,+ }+ }+}++/// The connector accounts a recovery transaction is recorded against.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct RecoveryConnectorAccounts {+ /// Billing connector account the invoice belongs to.+ pub billing_connector_id: common_utils::id_type::MerchantConnectorAccountId,+ /// Payment connector account the transaction ran on and the retries run through.+ pub payment_connector_id: common_utils::id_type::MerchantConnectorAccountId,+ /// The payment connector of that account.+ pub connector: common_enums::connector_enums::Connector,+}++/// What is known about the connector of a recovery transaction, which decides how it is recorded.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum RecoveryConnectorDetails {+ /// Recorded against connector accounts, so Hyperswitch can sync the transaction with the+ /// connector and retry through it.+ ConnectorAccounts(RecoveryConnectorAccounts),+ /// Reported by the merchant without any connector account, so what was reported is final.+ ReportedByMerchant {+ /// The processor that was reported.+ connector: common_enums::connector_enums::Connector,+ },+}++impl RecoveryConnectorDetails {+ /// Whether the transaction is recorded against connector accounts.+ pub fn has_connector_accounts(&self) -> bool {+ matches!(self, Self::ConnectorAccounts(_))+ }++ /// The billing connector account, when the transaction is recorded against one.+ pub fn get_billing_connector_id(+ &self,+ ) -> Option<&common_utils::id_type::MerchantConnectorAccountId> {+ match self {+ Self::ConnectorAccounts(accounts) => Some(&accounts.billing_connector_id),+ Self::ReportedByMerchant { .. } => None,+ }+ }++ /// The payment connector account, when the transaction is recorded against one.+ pub fn get_payment_connector_id(+ &self,+ ) -> Option<&common_utils::id_type::MerchantConnectorAccountId> {+ match self {+ Self::ConnectorAccounts(accounts) => Some(&accounts.payment_connector_id),+ Self::ReportedByMerchant { .. } => None,+ }+ }++ /// The payment connector of the transaction.+ pub fn get_connector(&self) -> common_enums::connector_enums::Connector {+ match self {+ Self::ConnectorAccounts(accounts) => accounts.connector,+ Self::ReportedByMerchant { connector } => *connector,+ }+ }+}+/// 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.rsindex c621c985b6..fc66aaf223 100644--- a/crates/diesel_models/src/types.rs+++ b/crates/diesel_models/src/types.rs@@ -292,7 +292,7 @@ impl FeatureMetadata {) -> Option<id_type::MerchantConnectorAccountId> {self.payment_revenue_recovery_metadata.as_ref()- .map(|recovery_metadata| recovery_metadata.billing_connector_id.clone())+ .and_then(|recovery_metadata| recovery_metadata.billing_connector_id.clone())}// TODO: Check search_tags for relevant payment method type@@ -498,10 +498,12 @@ pub struct PaymentRevenueRecoveryMetadata {pub total_retry_count: u16,/// Flag for the payment connector's callpub payment_connector_transmission: PaymentConnectorTransmission,- /// Billing Connector Id to update the invoices- pub billing_connector_id: id_type::MerchantConnectorAccountId,- /// Payment Connector Id to retry the payments- pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId,+ /// Billing Connector Id to update the invoices. Absent when the transaction is recorded+ /// without merchant connector accounts.+ pub billing_connector_id: Option<id_type::MerchantConnectorAccountId>,+ /// Payment Connector Id to retry the payments. Absent when the transaction is recorded+ /// without merchant connector accounts.+ pub active_attempt_payment_connector_id: Option<id_type::MerchantConnectorAccountId>,/// Billing Connector Payment Detailspub billing_connector_payment_details: BillingConnectorPaymentDetails,///Payment Method Typediff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rsindex b13ed113bc..731b918418 100644--- a/crates/hyperswitch_domain_models/src/payments.rs+++ b/crates/hyperswitch_domain_models/src/payments.rs@@ -1344,10 +1344,14 @@ impl PaymentIntent {)})?;- let connector_account_reference_id = billing_connector_account- .get_account_reference_id_using_payment_merchant_connector_account_id(- revenue_recovery_metadata.active_attempt_payment_connector_id,- )+ let connector_account_reference_id = revenue_recovery_metadata+ .active_attempt_payment_connector_id+ .and_then(|payment_merchant_connector_account_id| {+ billing_connector_account+ .get_account_reference_id_using_payment_merchant_connector_account_id(+ payment_merchant_connector_account_id,+ )+ }).ok_or_else(|| {error_stack::report!(errors::api_error_response::ApiErrorResponse::GenericNotFoundError {@@ -1638,7 +1642,7 @@ where#[cfg(feature = "v2")]#[derive(Clone)]pub struct RevenueRecoveryData {- pub billing_connector_id: id_type::MerchantConnectorAccountId,+ pub connector_details: common_types::payments::RecoveryConnectorDetails,pub processor_payment_method_token: String,pub connector_customer_id: String,pub retry_count: Option<u16>,@@ -1659,7 +1663,7 @@ where) -> CustomResult<Option<FeatureMetadata>, errors::api_error_response::ApiErrorResponse> {let payment_intent_feature_metadata = self.payment_intent.get_feature_metadata();let revenue_recovery = self.payment_intent.get_revenue_recovery_metadata();- let payment_attempt_connector = self.payment_attempt.connector.clone();+ let connector_details = &self.revenue_recovery_data.connector_details;let feature_metadata_first_pg_error_code = revenue_recovery.as_ref()@@ -1714,8 +1718,8 @@ where),);- let payment_revenue_recovery_metadata = match payment_attempt_connector {- Some(connector) => Some(diesel_models::types::PaymentRevenueRecoveryMetadata {+ let payment_revenue_recovery_metadata =+ Some(diesel_models::types::PaymentRevenueRecoveryMetadata {// Update retry count by one.total_retry_count: revenue_recovery.as_ref().map_or(self.revenue_recovery_data.retry_count.unwrap_or(1),@@ -1724,10 +1728,10 @@ where// Since this is an external system call, marking this payment_connector_transmission to ConnectorCallSucceeded.payment_connector_transmission:common_enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,- billing_connector_id: self.revenue_recovery_data.billing_connector_id.clone(),- active_attempt_payment_connector_id: self- .payment_attempt- .get_attempt_merchant_connector_account_id()?,+ billing_connector_id: connector_details.get_billing_connector_id().cloned(),+ active_attempt_payment_connector_id: connector_details+ .get_payment_connector_id()+ .cloned(),billing_connector_payment_details:diesel_models::types::BillingConnectorPaymentDetails {payment_processor_token: self@@ -1748,10 +1752,7 @@ whereerrors::api_error_response::ApiErrorResponse::InternalServerError,).attach_printable("Failed to construct revenue recovery metadata")?,- connector: connector.parse().map_err(|err| {- router_env::logger::error!(?err, "Failed to parse connector string to enum");- errors::api_error_response::ApiErrorResponse::InternalServerError- })?,+ connector: connector_details.get_connector(),// Both billing times belong to the invoice rather than to an individual attempt,// so the value recorded first is retained and later webhooks only seed it when it// is still unset.@@ -1770,10 +1771,7 @@ whererevenue_recovery_ab_routing: revenue_recovery.as_ref().and_then(|data| data.revenue_recovery_ab_routing),- }),- None => Err(errors::api_error_response::ApiErrorResponse::InternalServerError)- .attach_printable("Connector not found in payment attempt")?,- };+ });Ok(Some(FeatureMetadata {multi_currency_processing: payment_intent_feature_metadata.as_ref()diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rsindex e789752eb7..5680732e38 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs@@ -1301,7 +1301,7 @@ impl PaymentAttempt {.connector_transaction_id.as_ref().map(|txn_id| txn_id.get_id().clone());- let connector = request.connector.map(|connector| connector.to_string());+ let connector = Some(request.connector_details.get_connector().to_string());let connector_request_reference_id = payment_intent.merchant_reference_id.as_ref()@@ -1330,7 +1330,10 @@ impl PaymentAttempt {updated_by: storage_scheme.to_string(),redirection_data: None,encoded_data: None,- merchant_connector_id: request.payment_merchant_connector_id.clone(),+ merchant_connector_id: request+ .connector_details+ .get_payment_connector_id()+ .cloned(),external_three_ds_authentication_attempted: None,external_threeds_authentication_type: None,authentication_connector: None,diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex e98a3578f5..471d828449 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -1029,6 +1029,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::CustomRecoveryPaymentMethodData,api_models::payments::AdditionalCardInfo,common_types::payments::RecoveryTransactionStatus,+ common_types::payments::RecoveryConnector,api_models::enums::RevenueRecoveryAlgorithmType,api_models::enums::RevenueRecoveryTriggerModel,api_models::enums::RevenueRecoveryABAlgorithm,diff --git a/crates/openapi/src/routes/revenue_recovery.rs b/crates/openapi/src/routes/revenue_recovery.rsindex 1980956548..05304b9c9b 100644--- a/crates/openapi/src/routes/revenue_recovery.rs+++ b/crates/openapi/src/routes/revenue_recovery.rs@@ -24,14 +24,14 @@ pub async fn revenue_recovery_pt_retrieve_api() {}#[cfg(feature = "v2")]/// Revenue Recovery - Create///-/// Record a transaction made outside of Hyperswitch against a billing connector invoice.+/// Record a transaction made outside of Hyperswitch against an invoice.#[utoipa::path(post,path = "/v2/recovery",params(("X-Profile-Id" = String, Header,- description = "Unique identifier of the business profile under which the invoice is processed. The billing and payment merchant connector accounts in the request must belong to this profile.",+ description = "Unique identifier of the business profile under which the invoice is processed. Any billing and payment merchant connector accounts in the request must belong to this profile.",example = "pro_abcdefghijklmnop"),),@@ -90,6 +90,61 @@ pub async fn revenue_recovery_pt_retrieve_api() {}}))),+ (+ "Record a failed transaction on a profile with external triggers" = (+ value = json!({+ "amount_details": {+ "order_amount": 6540,+ "currency": "USD"+ },+ "merchant_reference_id": "invoice_mbabizu24mvu3mela5njyh",+ "connector": "stripe",+ "transaction_status": "failure",+ "payment_method_type": "card",+ "payment_method_sub_type": "credit",+ "connector_customer_id": "cust_12345",+ "connector_transaction_id": "993672945374576J",+ "transaction_created_at": "2022-09-10T10:11:12Z",+ "billing_started_at": "2022-09-10T10:11:12Z",+ "billing": {+ "address": {+ "line1": "1467 Harrison Street",+ "city": "San Francisco",+ "state": "California",+ "zip": "94122",+ "country": "US",+ "first_name": "John",+ "last_name": "Doe"+ },+ "phone": {+ "number": "9123456789",+ "country_code": "+1"+ },+ "email": "[email protected]"+ },+ "error": {+ "code": "card_declined",+ "message": "The card was declined.",+ "reason": "Insufficient funds",+ "network_advice_code": "01",+ "network_decline_code": "51",+ "network_error_message": "Retry after some time"+ },+ "payment_method_data": {+ "primary_processor_payment_method_token": "token_1234",+ "payment_method_metadata": {+ "card_network": "Visa",+ "card_type": "credit",+ "last4": "4242",+ "card_isin": "424242",+ "card_extended_bin": "42424242",+ "card_exp_month": "01",+ "card_exp_year": "2026"+ }+ },+ })+ )+ ),),),responses(@@ -103,7 +158,7 @@ pub async fn revenue_recovery_pt_retrieve_api() {}"merchant_reference_id": "invoice_mbabizu24mvu3mela5njyh"})),- (status = 400, description = "Missing or invalid mandatory fields", body = GenericErrorResponseOpenApi),+ (status = 400, description = "Missing or invalid mandatory fields, or the invoice takes no more transactions", body = GenericErrorResponseOpenApi),(status = 404, description = "Resource missing"),(status = 500, description = "Internal server error"),),diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex c3ff40042b..4451eccf2e 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -4497,7 +4497,11 @@ pub async fn record_attempt_core(merchant_connector_details: None,};- let payment_status_data = (req.triggered_by == common_enums::TriggeredBy::Internal)+ // A transaction recorded without connector accounts has no connector to be synced with.+ let should_skip_connector_sync = req.triggered_by == common_enums::TriggeredBy::Internal+ || !req.connector_details.has_connector_accounts();++ let payment_status_data = should_skip_connector_sync.then(|| default_payment_status_data.clone()).async_unwrap_or_else(|| async {match Box::pin(proxy_for_payments_operation_core::<diff --git a/crates/router/src/core/payments/operations/payment_attempt_record.rs b/crates/router/src/core/payments/operations/payment_attempt_record.rsindex 1d3f919800..f3e71164ad 100644--- a/crates/router/src/core/payments/operations/payment_attempt_record.rs+++ b/crates/router/src/core/payments/operations/payment_attempt_record.rs@@ -197,7 +197,7 @@ impl<F: Send + Clone + Sync>.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Could not insert payment attempt")?;let revenue_recovery_data = hyperswitch_domain_models::payments::RevenueRecoveryData {- billing_connector_id: request.billing_connector_id.clone(),+ connector_details: request.connector_details.clone(),processor_payment_method_token: request.processor_payment_method_token.clone(),connector_customer_id: request.connector_customer_id.clone(),retry_count: request.retry_count,diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rsindex de6629cbe5..b79db20b20 100644--- a/crates/router/src/core/refunds_v2.rs+++ b/crates/router/src/core/refunds_v2.rs@@ -78,6 +78,29 @@ pub async fn refund_create_core(},)?;+ payment_attempt = db+ .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id(+ platform.get_processor().get_key_store(),+ &req.payment_id,+ platform.get_processor().get_storage_scheme(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?;++ tracing::Span::current().record("global_refund_id", global_refund_id.get_string_repr());++ // A transaction the merchant reported has no connector account to refund it through. Refused+ // here, as a refund saved at this point would stay pending for good.+ utils::when(+ payment_attempt.merchant_connector_id.is_none()+ && !state.conf.merchant_id_auth.merchant_id_auth_enabled,+ || {+ Err(report!(errors::ApiErrorResponse::RefundNotPossible {+ connector: payment_attempt.connector.clone().unwrap_or_default(),+ }))+ },+ )?;+let captured_amount = payment_intent.amount_captured.ok_or(errors::ApiErrorResponse::InternalServerError)@@ -94,17 +117,6 @@ pub async fn refund_create_core(.attach_printable("amount less than or equal to zero"))})?;- payment_attempt = db- .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id(- platform.get_processor().get_key_store(),- &req.payment_id,- platform.get_processor().get_storage_scheme(),- )- .await- .to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?;-- tracing::Span::current().record("global_refund_id", global_refund_id.get_string_repr());-let merchant_connector_details = req.merchant_connector_details.clone();Box::pin(validate_and_create_refund(diff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rsindex 611aa46124..b0bd70c0f6 100644--- a/crates/router/src/core/revenue_recovery.rs+++ b/crates/router/src/core/revenue_recovery.rs@@ -1,8 +1,10 @@pub mod api;pub mod card_selection;+mod external_triggers;pub mod retry_stats;pub mod schedule;pub mod transformers;+mod trigger_model;pub mod types;use std::marker::PhantomData;diff --git a/crates/router/src/core/revenue_recovery/api.rs b/crates/router/src/core/revenue_recovery/api.rsindex 3f9ced27a7..2eee8842a6 100644--- a/crates/router/src/core/revenue_recovery/api.rs+++ b/crates/router/src/core/revenue_recovery/api.rs@@ -1,9 +1,11 @@use actix_web::{web, Responder};use api_models::{payments as payments_api, payments as api_payments};+use common_types::payments::{RecoveryConnectorAccounts, RecoveryConnectorDetails};use common_utils::id_type;use error_stack::{report, FutureExt, ResultExt};use hyperswitch_domain_models::{payments as payments_domain, platform::Platform};+use super::{external_triggers, trigger_model::RecoveryTrigger};use crate::{core::{errors::{self, RouterResult},@@ -83,6 +85,17 @@ pub async fn call_psync_api(Ok(payment_data)}+/// The connector accounts that the retries of an invoice run through. Retries run only under+/// internal triggers, where every transaction is recorded against them.+fn get_connector_accounts_for_retry(+ revenue_recovery_metadata: &payments_api::PaymentRevenueRecoveryMetadata,+) -> RouterResult<RecoveryConnectorAccounts> {+ revenue_recovery_metadata+ .get_connector_accounts()+ .ok_or_else(|| report!(errors::ApiErrorResponse::InternalServerError))+ .attach_printable("Connector accounts not found in revenue recovery metadata")+}+pub async fn call_proxy_api(state: &SessionState,payment_intent: &payments_domain::PaymentIntent,@@ -91,9 +104,10 @@ pub async fn call_proxy_api(payment_processor_token: &str,) -> RouterResult<payments_domain::PaymentConfirmData<api_types::Authorize>> {let operation = payments::operations::proxy_payments_intent::PaymentProxyIntent;+ let connector_accounts = get_connector_accounts_for_retry(revenue_recovery)?;let recurring_details = api_models::mandates::ProcessorPaymentToken {processor_payment_token: payment_processor_token.to_string(),- merchant_connector_id: Some(revenue_recovery.get_merchant_connector_id_for_api_request()),+ merchant_connector_id: Some(connector_accounts.payment_connector_id.clone()),};let req = payments_api::ProxyPaymentsRequest {return_url: None,@@ -101,8 +115,8 @@ pub async fn call_proxy_api(recurring_details,shipping: None,browser_info: None,- connector: revenue_recovery.connector.to_string(),- merchant_connector_id: revenue_recovery.get_merchant_connector_id_for_api_request(),+ connector: connector_accounts.connector.to_string(),+ merchant_connector_id: connector_accounts.payment_connector_id,};logger::info!("Call made to payments proxy api , with the request body {:?}",@@ -206,16 +220,12 @@ pub async fn record_internal_attempt_api(message: "get_revenue_recovery_attempt was not constructed".to_string(),})?;+ let connector_accounts = get_connector_accounts_for_retry(revenue_recovery_metadata)?;+let request_payload = revenue_recovery_attempt_data.create_payment_record_request(state,- &revenue_recovery_payment_data.billing_mca.id,- Some(- revenue_recovery_metadata- .active_attempt_payment_connector_id- .clone(),- ),- Some(revenue_recovery_metadata.connector),+ &RecoveryConnectorDetails::ConnectorAccounts(connector_accounts),common_enums::TriggeredBy::Internal,).await@@ -299,108 +309,117 @@ pub async fn custom_revenue_recovery_core(request: api_models::payments::RecoveryPaymentsCreate,) -> RouterResponse<payments_api::RecoveryPaymentsResponse> {validate_recovery_amounts(&request)?;- let store = state.store.as_ref();- let payment_merchant_connector_account_id = request.payment_merchant_connector_id.to_owned();- let profile_id = profile.get_id();- // Find the payment & billing merchant connector id at the top level to avoid multiple DB calls.- let payment_merchant_connector_account = store- .find_merchant_connector_account_by_id(- &payment_merchant_connector_account_id,- platform.get_processor().get_key_store(),- )- .await- .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {- id: payment_merchant_connector_account_id- .clone()- .get_string_repr()- .to_string(),- })?;+ validate_customer_information(&request)?;++ let updated_recovery_intent = match RecoveryTrigger::from_profile_settings(+ profile.revenue_recovery_trigger_model,+ profile.revenue_recovery_config.as_ref(),+ &request,+ )? {+ RecoveryTrigger::Internal {+ billing_merchant_connector_id,+ payment_merchant_connector_id,+ } => {+ Box::pin(record_transaction_and_schedule_retries(+ &state,+ &req_state,+ &platform,+ &profile,+ &request,+ &billing_merchant_connector_id,+ &payment_merchant_connector_id,+ ))+ .await?+ }+ RecoveryTrigger::External {+ connector,+ retry_config,+ } => {+ Box::pin(external_triggers::record_reported_transaction(+ &state,+ &req_state,+ &platform,+ &profile,+ &request,+ connector,+ retry_config,+ ))+ .await?+ }+ };++ 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,+ ))+}++/// Finds a connector account of the profile.+async fn find_connector_account_of_profile(+ state: &SessionState,+ platform: &Platform,+ profile: &domain::Profile,+ merchant_connector_id: &id_type::MerchantConnectorAccountId,+) -> RouterResult<domain::MerchantConnectorAccount> {+ let not_found = || errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: merchant_connector_id.get_string_repr().to_string(),+ };- utils::when(- &payment_merchant_connector_account.profile_id != profile_id,- || {- Err(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {- id: payment_merchant_connector_account_id- .clone()- .get_string_repr()- .to_string(),- })- },- )?;- let billing_connector_account = store+ let connector_account = state+ .store.find_merchant_connector_account_by_id(- &request.billing_merchant_connector_id.clone(),+ merchant_connector_id,platform.get_processor().get_key_store(),).await- .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {- id: request- .billing_merchant_connector_id- .clone()- .get_string_repr()- .to_string(),- })?;- utils::when(&billing_connector_account.profile_id != profile_id, || {- Err(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {- id: request- .billing_merchant_connector_id- .clone()- .get_string_repr()- .to_string(),- })+ .to_not_found_response(not_found())?;++ utils::when(&connector_account.profile_id != profile.get_id(), || {+ Err(not_found())})?;- validate_customer_information(&request)?;+ Ok(connector_account)+}++/// Records the transaction against the connector accounts and schedules its retries.+async fn record_transaction_and_schedule_retries(+ state: &SessionState,+ req_state: &ReqState,+ platform: &Platform,+ profile: &domain::Profile,+ request: &api_models::payments::RecoveryPaymentsCreate,+ billing_merchant_connector_id: &id_type::MerchantConnectorAccountId,+ payment_merchant_connector_id: &id_type::MerchantConnectorAccountId,+) -> RouterResult<hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent> {+ let payment_connector_account =+ find_connector_account_of_profile(state, platform, profile, payment_merchant_connector_id)+ .await?;+ let billing_connector_account =+ find_connector_account_of_profile(state, platform, profile, billing_merchant_connector_id)+ .await?;let recovery_intent =- recovery_incoming::RevenueRecoveryInvoice::get_or_create_custom_recovery_intent(- request.clone(),- &state,- &req_state,- &platform,- &profile,- )- .await- .change_context(errors::ApiErrorResponse::GenericNotFoundError {- message: format!(- "Failed to load recovery intent for merchant reference id : {:?}",- request.merchant_reference_id.to_owned()- )- .to_string(),- })?;+ get_or_create_invoice(state, req_state, platform, profile, request).await?;- let (revenue_recovery_attempt_data, updated_recovery_intent) = Box::pin(- recovery_incoming::RevenueRecoveryAttempt::load_recovery_attempt_from_api(- request.clone(),- &state,- &req_state,- &platform,- &profile,- recovery_intent.clone(),- payment_merchant_connector_account,- ),- )- .await- .map_err(|error| {- let api_error = match error.current_context() {- errors::RevenueRecoveryError::PaymentAttemptAlreadyRecorded => {- errors::ApiErrorResponse::GenericDuplicateError {- message: format!(- "The transaction {} is already recorded against the invoice {}",- request.connector_transaction_id,- request.merchant_reference_id.get_string_repr()- ),- }- }- _ => errors::ApiErrorResponse::GenericNotFoundError {- message: format!(- "Failed to load recovery attempt for merchant reference id : {:?}",- request.merchant_reference_id.to_owned()- ),- },- };- error.change_context(api_error)- })?;+ let (revenue_recovery_attempt_data, updated_recovery_intent) = Box::pin(record_transaction(+ state,+ req_state,+ platform,+ profile,+ request,+ &recovery_intent,+ &RecoveryConnectorDetails::ConnectorAccounts(RecoveryConnectorAccounts {+ billing_connector_id: billing_connector_account.get_id(),+ payment_connector_id: payment_connector_account.get_id(),+ connector: payment_connector_account.get_connector_name(),+ }),+ ))+ .await?;let intent_retry_count = updated_recovery_intent.feature_metadata@@ -432,9 +451,9 @@ pub async fn custom_revenue_recovery_core(recovery_action.handle_action(- &state,- &profile,- &platform,+ state,+ profile,+ platform,&billing_connector_account,mca_retry_threshold,intent_retry_count,@@ -448,15 +467,79 @@ pub async fn custom_revenue_recovery_core(message: "Unexpected response from recovery core".to_string(),})?;- 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(updated_recovery_intent)+}- Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(- response,- ))+/// Finds or creates the invoice of the transaction.+pub(super) async fn get_or_create_invoice(+ state: &SessionState,+ req_state: &ReqState,+ platform: &Platform,+ profile: &domain::Profile,+ request: &api_models::payments::RecoveryPaymentsCreate,+) -> RouterResult<hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent> {+ recovery_incoming::RevenueRecoveryInvoice::get_or_create_custom_recovery_intent(+ request.clone(),+ state,+ req_state,+ platform,+ profile,+ )+ .await+ .change_context(errors::ApiErrorResponse::GenericNotFoundError {+ message: format!(+ "Failed to load recovery intent for merchant reference id : {:?}",+ request.merchant_reference_id.to_owned()+ )+ .to_string(),+ })+}++/// Records the transaction against the invoice.+pub(super) async fn record_transaction(+ state: &SessionState,+ req_state: &ReqState,+ platform: &Platform,+ profile: &domain::Profile,+ request: &api_models::payments::RecoveryPaymentsCreate,+ recovery_intent: &hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent,+ connector_details: &RecoveryConnectorDetails,+) -> RouterResult<(+ hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt,+ hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent,+)> {+ Box::pin(+ recovery_incoming::RevenueRecoveryAttempt::load_recovery_attempt_from_api(+ request,+ state,+ req_state,+ platform,+ profile,+ recovery_intent,+ connector_details,+ ),+ )+ .await+ .map_err(|error| {+ let api_error = match error.current_context() {+ errors::RevenueRecoveryError::PaymentAttemptAlreadyRecorded => {+ errors::ApiErrorResponse::GenericDuplicateError {+ message: format!(+ "The transaction {} is already recorded against the invoice {}",+ request.connector_transaction_id,+ request.merchant_reference_id.get_string_repr()+ ),+ }+ }+ _ => errors::ApiErrorResponse::GenericNotFoundError {+ message: format!(+ "Failed to load recovery attempt for merchant reference id : {:?}",+ request.merchant_reference_id.to_owned()+ ),+ },+ };+ error.change_context(api_error)+ })}/// Cancel the revenue recovery workflow of the invoice identified by `merchant_reference_id`diff --git a/crates/router/src/core/revenue_recovery/external_triggers.rs b/crates/router/src/core/revenue_recovery/external_triggers.rsnew file mode 100644index 0000000000..bd83895e0b--- /dev/null+++ b/crates/router/src/core/revenue_recovery/external_triggers.rs@@ -0,0 +1,65 @@+use api_models::payments::RecoveryPaymentsCreate;+use common_types::payments::{RecoveryConnector, RecoveryConnectorDetails};+use diesel_models::business_profile::RevenueRecoveryConfig;+use error_stack::report;+use hyperswitch_domain_models::{platform::Platform, revenue_recovery::RecoveryPaymentIntent};++use super::api;+use crate::{+ core::{+ errors::{self, RouterResult},+ payments::operations::{+ payment_attempt_record::PaymentAttemptRecord, ValidateStatusForOperation,+ },+ },+ routes::{app::ReqState, SessionState},+ types::domain,+};++/// 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(+ state: &SessionState,+ req_state: &ReqState,+ platform: &Platform,+ profile: &domain::Profile,+ request: &RecoveryPaymentsCreate,+ connector: RecoveryConnector,+ retry_config: &RevenueRecoveryConfig,+) -> RouterResult<RecoveryPaymentIntent> {+ // A value sent in the request takes priority over the one on the profile.+ let request = &RecoveryPaymentsCreate {+ enable_partial_authorization: request+ .enable_partial_authorization+ .or(Some(retry_config.enable_partial_authorization.into())),+ ..request.clone()+ };++ let invoice = api::get_or_create_invoice(state, req_state, platform, profile, request).await?;++ PaymentAttemptRecord+ .validate_status_for_operation(invoice.status)+ .map_err(|_| {+ report!(errors::ApiErrorResponse::PreconditionFailed {+ message: format!(+ "The invoice is `{}` and takes no more transactions",+ invoice.status+ ),+ })+ })?;++ let (_, updated_invoice) = Box::pin(api::record_transaction(+ state,+ req_state,+ platform,+ profile,+ request,+ &invoice,+ &RecoveryConnectorDetails::ReportedByMerchant {+ connector: connector.into(),+ },+ ))+ .await?;++ Ok(updated_invoice)+}diff --git a/crates/router/src/core/revenue_recovery/transformers.rs b/crates/router/src/core/revenue_recovery/transformers.rsindex d27469dbcd..e96f4d8be8 100644--- a/crates/router/src/core/revenue_recovery/transformers.rs+++ b/crates/router/src/core/revenue_recovery/transformers.rs@@ -95,10 +95,8 @@ impl ForeignFrom<&api_models::payments::RecoveryPaymentsCreate>.peek().to_string(),connector_customer_id: data.connector_customer_id.peek().to_string(),- connector_account_reference_id: data- .payment_merchant_connector_id- .get_string_repr()- .to_string(),+ // Only the billing connector webhooks look up an account through this reference.+ connector_account_reference_id: String::new(),transaction_created_at: Some(data.transaction_created_at),status: data.transaction_status.into(),payment_method_type: data.payment_method_type,diff --git a/crates/router/src/core/revenue_recovery/trigger_model.rs b/crates/router/src/core/revenue_recovery/trigger_model.rsnew file mode 100644index 0000000000..9a7ca0a351--- /dev/null+++ b/crates/router/src/core/revenue_recovery/trigger_model.rs@@ -0,0 +1,68 @@+use api_models::payments::RecoveryPaymentsCreate;+use common_types::payments::RecoveryConnector;+use common_utils::id_type;+use diesel_models::business_profile::RevenueRecoveryConfig;+use error_stack::report;++use crate::{+ core::errors::{self, RouterResult},+ utils::OptionExt,+};++/// What a recovery API request needs under the trigger model of the profile, worked out at the very+/// start of the API. The model comes from the profile alone. The fields of the request are only+/// checked against it, and from here on each model has exactly what it needs.+#[derive(Debug)]+pub(super) enum RecoveryTrigger<'a> {+ /// Hyperswitch triggers the retries through these connector accounts.+ Internal {+ billing_merchant_connector_id: id_type::MerchantConnectorAccountId,+ payment_merchant_connector_id: id_type::MerchantConnectorAccountId,+ },+ /// The merchant triggers the retries on this processor, within these limits.+ External {+ connector: RecoveryConnector,+ retry_config: &'a RevenueRecoveryConfig,+ },+}++impl<'a> RecoveryTrigger<'a> {+ pub(super) fn from_profile_settings(+ trigger_model: common_enums::RevenueRecoveryTriggerModel,+ retry_config: Option<&'a RevenueRecoveryConfig>,+ request: &RecoveryPaymentsCreate,+ ) -> RouterResult<Self> {+ match trigger_model {+ common_enums::RevenueRecoveryTriggerModel::InternalTriggers => {+ // Any `connector` in the request is ignored, as the processor comes from the payment+ // connector account.+ Ok(Self::Internal {+ billing_merchant_connector_id: request+ .billing_merchant_connector_id+ .clone()+ .get_required_value("billing_merchant_connector_id")?,+ payment_merchant_connector_id: request+ .payment_merchant_connector_id+ .clone()+ .get_required_value("payment_merchant_connector_id")?,+ })+ }+ common_enums::RevenueRecoveryTriggerModel::ExternalTriggers => {+ // Any connector account IDs in the request are ignored, as this model doesn't use them.+ let connector = request.connector.get_required_value("connector")?;++ // Profiles are refused without it, this holds for one saved before that check.+ let retry_config = retry_config.ok_or_else(|| {+ report!(errors::ApiErrorResponse::PreconditionFailed {+ message: "The `revenue_recovery_config` of the profile is required when its `revenue_recovery_trigger_model` is `external_triggers`".to_owned(),+ })+ })?;++ Ok(Self::External {+ connector,+ retry_config,+ })+ }+ }+ }+}diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rsindex 41cf8970b4..aba45a3cbe 100644--- a/crates/router/src/core/webhooks/recovery_incoming.rs+++ b/crates/router/src/core/webhooks/recovery_incoming.rs@@ -466,13 +466,13 @@ impl RevenueRecoveryInvoice {impl RevenueRecoveryAttempt {pub async fn load_recovery_attempt_from_api(- data: api_models::payments::RecoveryPaymentsCreate,+ data: &api_models::payments::RecoveryPaymentsCreate,state: &SessionState,req_state: &ReqState,platform: &domain::Platform,profile: &domain::Profile,- payment_intent: revenue_recovery::RecoveryPaymentIntent,- payment_merchant_connector_account: domain::MerchantConnectorAccount,+ payment_intent: &revenue_recovery::RecoveryPaymentIntent,+ connector_details: &common_types::payments::RecoveryConnectorDetails,) -> CustomResult<(revenue_recovery::RecoveryPaymentAttempt,@@ -481,12 +481,12 @@ impl RevenueRecoveryAttempt {errors::RevenueRecoveryError,> {let recovery_attempt = Self(revenue_recovery::RevenueRecoveryAttemptData::foreign_from(- &data,+ data,));// A transaction can be reported only once for an invoice, so one that is already// recorded is rejected instead of being recorded again.let existing_attempt = recovery_attempt- .get_payment_attempt(state, req_state, platform, profile, &payment_intent)+ .get_payment_attempt(state, req_state, platform, profile, payment_intent).await?;if existing_attempt.is_some() {return Err(report!(@@ -499,9 +499,8 @@ impl RevenueRecoveryAttempt {req_state,platform,profile,- &payment_intent,- &data.billing_merchant_connector_id,- Some(payment_merchant_connector_account),+ payment_intent,+ connector_details,).await}@@ -707,8 +706,7 @@ impl RevenueRecoveryAttempt {platform: &domain::Platform,profile: &domain::Profile,payment_intent: &revenue_recovery::RecoveryPaymentIntent,- billing_connector_account_id: &id_type::MerchantConnectorAccountId,- payment_connector_account: Option<domain::MerchantConnectorAccount>,+ connector_details: &common_types::payments::RecoveryConnectorDetails,) -> CustomResult<(revenue_recovery::RecoveryPaymentAttempt,@@ -716,16 +714,10 @@ impl RevenueRecoveryAttempt {),errors::RevenueRecoveryError,> {- let payment_connector_id = payment_connector_account.as_ref().map(|account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount| account.id.clone());- let payment_connector_name = payment_connector_account- .as_ref()- .map(|account| account.connector_name);let request_payload: api_payments::PaymentsAttemptRecordRequest = self.create_payment_record_request(state,- billing_connector_account_id,- payment_connector_id,- payment_connector_name,+ connector_details,common_enums::TriggeredBy::External,).await?;@@ -744,9 +736,7 @@ impl RevenueRecoveryAttempt {Ok(services::ApplicationResponse::JsonWithHeaders((attempt_response, _))) => {let standardised_error_code = retry_stats::events::resolve_standardised_error_code(state,- payment_connector_name- .as_ref()- .map(|connector| connector.to_string()),+ Some(connector_details.get_connector().to_string()),attempt_response.error_details.as_ref()@@ -816,15 +806,24 @@ impl RevenueRecoveryAttempt {let response = (recovery_attempt, updated_recovery_intent);- self.store_payment_processor_tokens_in_redis(state, &response.0, payment_connector_name)+ if let Err(error) = self+ .store_payment_processor_tokens_in_redis(+ state,+ &response.0,+ connector_details.get_connector(),+ ).await- .map_err(|e| {- router_env::logger::error!(- "Failed to store payment processor tokens in Redis: {:?}",- e- );- errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed- })?;+ {+ router_env::logger::error!(+ "Failed to store payment processor tokens in Redis: {:?}",+ error+ );+ // A transaction the merchant reports is recorded by now, and reporting it again would+ // be refused as a duplicate, so they still get an answer.+ if connector_details.has_connector_accounts() {+ return Err(errors::RevenueRecoveryError::RevenueRecoveryRedisInsertFailed.into());+ }+ }Ok(response)}@@ -832,9 +831,7 @@ impl RevenueRecoveryAttempt {pub async fn create_payment_record_request(&self,state: &SessionState,- billing_merchant_connector_account_id: &id_type::MerchantConnectorAccountId,- payment_merchant_connector_account_id: Option<id_type::MerchantConnectorAccountId>,- payment_connector: Option<common_enums::connector_enums::Connector>,+ connector_details: &common_types::payments::RecoveryConnectorDetails,triggered_by: common_enums::TriggeredBy,) -> CustomResult<api_payments::PaymentsAttemptRecordRequest, errors::RevenueRecoveryError>{@@ -880,15 +877,13 @@ impl RevenueRecoveryAttempt {status: revenue_recovery_attempt_data.status,billing: None,shipping: None,- connector: payment_connector,- payment_merchant_connector_id: payment_merchant_connector_account_id,+ connector_details: connector_details.clone(),error,description: None,connector_transaction_id: revenue_recovery_attempt_data.connector_transaction_id.clone(),payment_method_type: revenue_recovery_attempt_data.payment_method_type,- billing_connector_id: billing_merchant_connector_account_id.clone(),payment_method_subtype: revenue_recovery_attempt_data.payment_method_sub_type,payment_method_data: Some(payment_method_data),metadata: None,@@ -992,8 +987,15 @@ impl RevenueRecoveryAttempt {platform,business_profile,payment_intent,- &billing_connector_account.get_id(),- Some(payment_merchant_connector_account),+ &common_types::payments::RecoveryConnectorDetails::ConnectorAccounts(+ common_types::payments::RecoveryConnectorAccounts {+ billing_connector_id: billing_connector_account.get_id(),+ payment_connector_id: payment_merchant_connector_account+ .get_id(),+ connector: payment_merchant_connector_account+ .get_connector_name(),+ },+ ),).await})@@ -1012,16 +1014,12 @@ impl RevenueRecoveryAttempt {&self,state: &SessionState,recovery_attempt: &revenue_recovery::RecoveryPaymentAttempt,- payment_connector_name: Option<common_enums::connector_enums::Connector>,+ payment_connector: common_enums::connector_enums::Connector,) -> CustomResult<(), errors::RevenueRecoveryError> {let revenue_recovery_attempt_data = &self.0;let error_code = revenue_recovery_attempt_data.error_code.clone();let error_message = revenue_recovery_attempt_data.error_message.clone();- let connector_name = payment_connector_name- .ok_or(errors::RevenueRecoveryError::TransactionWebhookProcessingFailed)- .attach_printable("unable to derive payment connector")?- .to_string();// The recorded attempt is synced with the payment connector, so prefer the decline code// it carries and fall back to the one the caller sent.@@ -1032,7 +1030,7 @@ impl RevenueRecoveryAttempt {let gsm_record = helpers::get_gsm_record(state,- connector_name,+ payment_connector.to_string(),REVENUE_RECOVERY,consts::DEFAULT_SUBFLOW_STR,error_code.clone(),