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): Enable multiple retries for partial charged payments (#9818)
chikke srujane7fe4804acd8
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 9a53266c3c..1eb6b6026d 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -207,6 +207,39 @@ impl AttemptStatus {}}+ pub fn is_payment_terminal_failure(self) -> bool {+ match self {+ Self::RouterDeclined+ | Self::Failure+ | Self::Expired+ | Self::VoidFailed+ | Self::CaptureFailed+ | Self::AuthenticationFailed+ | Self::AuthorizationFailed => true,+ Self::Started+ | Self::AuthenticationPending+ | Self::AuthenticationSuccessful+ | Self::Authorized+ | Self::Charged+ | Self::Authorizing+ | Self::CodInitiated+ | Self::Voided+ | Self::VoidedPostCharge+ | Self::VoidInitiated+ | Self::CaptureInitiated+ | Self::AutoRefunded+ | Self::PartialCharged+ | Self::PartiallyAuthorized+ | Self::PartialChargedAndChargeable+ | Self::Unresolved+ | Self::Pending+ | Self::PaymentMethodAwaited+ | Self::ConfirmationAwaited+ | Self::DeviceDataCollectionPending+ | Self::IntegrityFailure => false,+ }+ }+pub fn is_success(self) -> bool {matches!(self, Self::Charged | Self::PartialCharged)}@@ -1886,6 +1919,9 @@ pub enum RecoveryStatus {/// The payment is currently being processed with the payment gateway./// This status is shown during active retry attempts.Processing,+ /// The payment has been partially recovered through retry mechanisms,+ /// and the remaining amount is still being processed by the payment gateway.+ PartiallyCapturedAndProcessing,/// The payment cannot be recovered due to terminal failure conditions./// This includes cases where all retries have been exhausted or the payment has hard decline errors.Terminated,@@ -10100,9 +10136,9 @@ impl From<IntentStatus> for InvoiceStatus {IntentStatus::RequiresCapture| IntentStatus::PartiallyCaptured| IntentStatus::PartiallyCapturedAndCapturable+ | IntentStatus::PartiallyCapturedAndProcessing| IntentStatus::PartiallyAuthorizedAndRequiresCapture| IntentStatus::Processing- | IntentStatus::PartiallyCapturedAndProcessing| IntentStatus::RequiresCustomerAction| IntentStatus::RequiresConfirmation| IntentStatus::RequiresPaymentMethod => Self::PaymentPending,diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rsindex 30c5a7cc7d..f8f6f4ea93 100644--- a/crates/diesel_models/src/payment_intent.rs+++ b/crates/diesel_models/src/payment_intent.rs@@ -405,6 +405,8 @@ pub struct PaymentIntentNew {pub order_date: Option<PrimitiveDateTime>,pub mit_category: Option<storage_enums::MitCategory>,pub tokenization: Option<common_enums::Tokenization>,+ pub active_attempts_group_id: Option<common_utils::id_type::GlobalAttemptGroupId>,+ pub active_attempt_id_type: Option<common_enums::ActiveAttemptIDType>,}#[cfg(feature = "v1")]diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rsindex 84110e13e8..ae601ec268 100644--- a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs@@ -570,20 +570,25 @@ impl<F> TryFrom<ResponseRouterData<F, VantivSyncResponse, PaymentsSyncData, Paym})} else {let required_conversion_type = common_utils::types::StringMajorUnitForConnector;- let minor_amount_captured = item- .response- .payment_detail- .and_then(|details| {- details.amount.map(|amount| {- common_utils::types::AmountConvertor::convert_back(- &required_conversion_type,- amount,- item.data.request.currency,- )- })- })- .transpose()- .change_context(errors::ConnectorError::ResponseHandlingFailed)?;+ let minor_amount_captured: Option<MinorUnit> =+ match connector_utils::is_successful_terminal_status(status) {+ true => item+ .response+ .payment_detail+ .and_then(|details| {+ details.amount.map(|amount| {+ common_utils::types::AmountConvertor::convert_back(+ &required_conversion_type,+ amount,+ item.data.request.currency,+ )+ })+ })+ .transpose()+ .change_context(errors::ConnectorError::ResponseHandlingFailed)?,+ false => None,+ };+Ok(Self {status,response: Ok(PaymentsResponseData::TransactionResponse {@@ -1938,6 +1943,10 @@ impl<F>match (item.response.sale_response.as_ref(), item.response.authorization_response.as_ref()) {(Some(sale_response), None) => {let status = get_attempt_status(WorldpayvantivPaymentFlow::Sale, sale_response.response)?;+ let minor_amount_captured = match connector_utils::is_successful_terminal_status(status) {+ true => sale_response.approved_amount,+ false => None,+ };// While making an authorize flow call to WorldpayVantiv, if Account Updater is enabled then we well get new card token info in response.// We are extracting that new card token info here to be sent back in mandate_id in router_data.@@ -2038,7 +2047,7 @@ impl<F>}),connector_response,amount_captured: sale_response.approved_amount.map(MinorUnit::get_amount_as_i64),- minor_amount_captured: sale_response.approved_amount,+ minor_amount_captured,..item.data})}@@ -2051,6 +2060,10 @@ impl<F>};let status = get_attempt_status(payment_flow_type, auth_response.response)?;+ let minor_amount_captured = match connector_utils::is_successful_terminal_status(status){+ true => auth_response.approved_amount,+ false => None,+ };if connector_utils::is_payment_failure(status) {let network_decline_code = item.response@@ -2128,11 +2141,7 @@ impl<F>} else {None},- minor_amount_captured: if payment_flow_type == WorldpayvantivPaymentFlow::Sale {- auth_response.approved_amount- } else {- None- },+ minor_amount_captured,..item.data})}diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rsindex d9f4b27948..611c5451b9 100644--- a/crates/hyperswitch_connectors/src/utils.rs+++ b/crates/hyperswitch_connectors/src/utils.rs@@ -447,6 +447,39 @@ pub(crate) fn convert_back_amount_to_minor_units<T>(.change_context(errors::ConnectorError::AmountConversionFailed)}+pub(crate) fn is_successful_terminal_status(status: AttemptStatus) -> bool {+ match status {+ AttemptStatus::Charged+ | AttemptStatus::PartialCharged+ | AttemptStatus::PartialChargedAndChargeable => true,+ AttemptStatus::Started+ | AttemptStatus::Authorized+ | AttemptStatus::PartiallyAuthorized+ | AttemptStatus::RouterDeclined+ | AttemptStatus::AuthenticationPending+ | AttemptStatus::AuthenticationSuccessful+ | AttemptStatus::CaptureFailed+ | AttemptStatus::Authorizing+ | AttemptStatus::AuthenticationFailed+ | AttemptStatus::CodInitiated+ | AttemptStatus::Voided+ | AttemptStatus::VoidedPostCharge+ | AttemptStatus::VoidInitiated+ | AttemptStatus::CaptureInitiated+ | AttemptStatus::AutoRefunded+ | AttemptStatus::AuthorizationFailed+ | AttemptStatus::Failure+ | AttemptStatus::Pending+ | AttemptStatus::Unresolved+ | AttemptStatus::PaymentMethodAwaited+ | AttemptStatus::ConfirmationAwaited+ | AttemptStatus::DeviceDataCollectionPending+ | AttemptStatus::IntegrityFailure+ | AttemptStatus::VoidFailed+ | AttemptStatus::Expired => false,+ }+}+pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool {match status {AttemptStatus::AuthenticationFaileddiff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rsindex e6dfc00c59..bbf4aeab88 100644--- a/crates/hyperswitch_domain_models/src/payments.rs+++ b/crates/hyperswitch_domain_models/src/payments.rs@@ -11,6 +11,8 @@ use common_types::{AlwaysRequestExtendedAuthorization, EnableOvercaptureBool, RequestExtendedAuthorizationBool,},};+#[cfg(feature = "v2")]+use common_utils::fp_utils;use common_utils::{self,crypto::Encryptable,@@ -417,6 +419,21 @@ impl AmountDetails {})}+ pub fn get_order_amount_for_recovery_data(+ &self,+ ) -> CustomResult<MinorUnit, errors::api_error_response::ApiErrorResponse> {+ // Validate that amount_captured doesn't exceed order_amount+ let captured_amount = self.amount_captured.unwrap_or(MinorUnit::zero());+ fp_utils::when(captured_amount > self.order_amount, || {+ Err(+ errors::api_error_response::ApiErrorResponse::InvalidRequestData {+ message: "Amount captured cannot exceed the order amount".into(),+ },+ )+ })?;+ Ok(self.order_amount - captured_amount)+ }+pub fn create_split_attempt_amount_details(&self,confirm_intent_request: &api_models::payments::PaymentsConfirmIntentRequest,@@ -721,6 +738,7 @@ impl PaymentIntent {profile: &business_profile::Profile,request: api_models::payments::PaymentsCreateIntentRequest,decrypted_payment_intent: DecryptedPaymentIntent,+ cell_id: id_type::CellId,) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {let request_incremental_authorization =Self::get_request_incremental_authorization_value(&request)?;@@ -740,6 +758,19 @@ impl PaymentIntent {.map(|order_detail| Secret::new(OrderDetailsWithAmount::convert_from(order_detail))).collect()});+ let active_attempt_id_type = request+ .enable_partial_authorization+ .and_then(|enable_partial_authorization| {+ enable_partial_authorization.then_some(common_enums::ActiveAttemptIDType::GroupID)+ })+ .unwrap_or(common_enums::ActiveAttemptIDType::AttemptID);+ let active_attempts_group_id =+ request+ .enable_partial_authorization+ .and_then(|enable_partial_authorization| {+ enable_partial_authorization+ .then_some(id_type::GlobalAttemptGroupId::generate(&cell_id))+ });Ok(Self {id: payment_id.clone(),@@ -758,8 +789,8 @@ impl PaymentIntent {last_synced: None,setup_future_usage: request.setup_future_usage.unwrap_or_default(),active_attempt_id: None,- active_attempt_id_type: common_enums::ActiveAttemptIDType::AttemptID,- active_attempts_group_id: None,+ active_attempt_id_type,+ active_attempts_group_id,order_details,allowed_payment_method_types,connector_metadata: request.connector_metadata,@@ -845,6 +876,12 @@ impl PaymentIntent {self.feature_metadata.clone()}+ pub fn get_recovery_order_amount(+ &self,+ ) -> CustomResult<MinorUnit, errors::api_error_response::ApiErrorResponse> {+ self.amount_details.get_order_amount_for_recovery_data()+ }+pub fn create_revenue_recovery_attempt_data(&self,revenue_recovery_metadata: api_models::payments::PaymentRevenueRecoveryMetadata,@@ -875,8 +912,9 @@ impl PaymentIntent {)})?;+ let amount = self.amount_details.get_order_amount_for_recovery_data()?;Ok(revenue_recovery::RevenueRecoveryAttemptData {- amount: self.amount_details.order_amount,+ amount,currency: self.amount_details.currency,merchant_reference_id,connector_transaction_id: None, // No connector id@@ -946,6 +984,7 @@ impl PaymentIntent {| common_enums::IntentStatus::RequiresCapture| common_enums::IntentStatus::PartiallyCapturedAndCapturable| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture+ | common_enums::IntentStatus::PartiallyCapturedAndProcessing| common_enums::IntentStatus::Conflicted => false,}}diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rsindex 736e5621e1..bdd8b2445e 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs@@ -866,6 +866,8 @@ impl PaymentAttempt {}),};+ let group_id = payment_intent.active_attempts_group_id.clone();+let payment_method_data = request.payment_method_data.as_ref()@@ -898,7 +900,7 @@ impl PaymentAttempt {Ok(Self {payment_id: payment_intent.id.clone(),merchant_id: payment_intent.merchant_id.clone(),- attempts_group_id: None,+ attempts_group_id: group_id.clone(),amount_details: AttemptAmountDetails::from(amount_details),status: request.status,connector,diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rsindex 3c55801d1e..5d5d9b9124 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs@@ -201,6 +201,8 @@ pub struct PaymentIntentUpdateFields {pub force_3ds_challenge: Option<bool>,pub is_iframe_redirection_enabled: Option<bool>,pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,+ pub active_attempt_id_type: Option<common_enums::ActiveAttemptIDType>,+ pub active_attempts_group_id: Option<id_type::GlobalAttemptGroupId>,}#[cfg(feature = "v1")]@@ -377,6 +379,7 @@ pub enum PaymentIntentUpdate {feature_metadata: Box<Option<diesel_models::types::FeatureMetadata>>,updated_by: String,active_attempt_id: Option<id_type::GlobalAttemptId>,+ active_attempts_group_id: Option<id_type::GlobalAttemptGroupId>,},/// UpdateIntentUpdateIntent(Box<PaymentIntentUpdateFields>),@@ -521,7 +524,6 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalactive_attempt_id: None,active_attempt_id_type: None,active_attempts_group_id: None,-prerouting_algorithm: None,modified_at: common_utils::date_time::now(),amount_captured,@@ -568,7 +570,6 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalactive_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,@@ -616,7 +617,6 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalactive_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,@@ -661,7 +661,6 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalactive_attempt_id: None,active_attempt_id_type: None,active_attempts_group_id: None,-modified_at: common_utils::date_time::now(),amount_captured: None,prerouting_algorithm: Some(@@ -740,13 +739,14 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalforce_3ds_challenge,is_iframe_redirection_enabled,enable_partial_authorization,+ active_attempt_id_type,+ active_attempts_group_id,} = *boxed_intent;Ok(Self {status: None,active_attempt_id,- active_attempt_id_type: None,- active_attempts_group_id: None,-+ active_attempt_id_type,+ active_attempts_group_id,prerouting_algorithm: None,modified_at: common_utils::date_time::now(),amount_captured: None,@@ -796,13 +796,13 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalfeature_metadata,updated_by,active_attempt_id,+ active_attempts_group_id,} => Ok(Self {status: Some(status),amount_captured: None,active_attempt_id: Some(active_attempt_id),active_attempt_id_type: None,- active_attempts_group_id: None,-+ active_attempts_group_id,modified_at: common_utils::date_time::now(),amount: None,currency: None,@@ -892,7 +892,6 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalactive_attempt_id: None,active_attempt_id_type: Some(active_attempt_id_type),active_attempts_group_id: Some(active_attempts_group_id),-prerouting_algorithm: None,modified_at: common_utils::date_time::now(),amount: None,@@ -935,7 +934,6 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalactive_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,@@ -2236,6 +2234,8 @@ impl behaviour::Conversion for PaymentIntent {order_date: None,enable_partial_authorization: Some(self.enable_partial_authorization),tokenization: None,+ active_attempt_id_type: Some(self.active_attempt_id_type),+ active_attempts_group_id: self.active_attempts_group_id,})}}diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rsindex 70468c3681..99503093c8 100644--- a/crates/hyperswitch_domain_models/src/router_data.rs+++ b/crates/hyperswitch_domain_models/src/router_data.rs@@ -779,6 +779,19 @@ pub trait TrackerPostUpdateObjects<Flow, FlowRequest, D> {/// Get the amount that has been captured for the paymentfn get_captured_amount(&self, payment_data: &D) -> Option<MinorUnit>;+ /// Get the intent status based on parameters like captured amount and amount capturable+ fn get_intent_status_for_db_update(+ &self,+ payment_data: &D,+ ) -> common_enums::enums::IntentStatus;++ /// Get the intent error response status based on parameters like captured amount and amount capturable+ fn get_intent_error_response_status_for_db_update(+ &self,+ payment_data: &D,+ error: ErrorResponse,+ ) -> common_enums::enums::IntentStatus;+/// Get the attempt status based on parameters like captured amount and amount capturablefn get_attempt_status_for_db_update(&self,@@ -805,6 +818,11 @@ implstorage_scheme: common_enums::MerchantStorageScheme,) -> PaymentIntentUpdate {let amount_captured = self.get_captured_amount(payment_data);+ let intent_amount_captured = payment_data+ .payment_intent+ .amount_captured+ .map(|amount| amount + amount_captured.unwrap_or(MinorUnit::zero()))+ .or(amount_captured);let updated_feature_metadata =payment_data.payment_intent@@ -814,43 +832,38 @@ implif let Some(ref mut payment_revenue_recovery_metadata) =feature_metadata.payment_revenue_recovery_metadata{- payment_revenue_recovery_metadata.payment_connector_transmission = if self- .response- .is_ok()- {- common_enums::PaymentConnectorTransmission::ConnectorCallSucceeded- } else {- common_enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful- };+ payment_revenue_recovery_metadata.payment_connector_transmission = match &self.response {+ Ok(_) => common_enums::enums::PaymentConnectorTransmission::ConnectorCallSucceeded,+ Err(error_response) => match &error_response.status_code {+ 500..=511 => common_enums::enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,+ _ => common_enums::enums::PaymentConnectorTransmission::ConnectorCallSucceeded,+ }+ }}Box::new(feature_metadata)});match self.response {- Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate {- status: common_enums::IntentStatus::from(- self.get_attempt_status_for_db_update(payment_data),- ),- amount_captured,- updated_by: storage_scheme.to_string(),- feature_metadata: updated_feature_metadata,- },- Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate {- status: {- let attempt_status = match error.attempt_status {- // Use the status sent by connector in error_response if it's present- Some(status) => status,- None => match error.status_code {- 500..=511 => common_enums::enums::AttemptStatus::Pending,- _ => common_enums::enums::AttemptStatus::Failure,- },- };- common_enums::IntentStatus::from(attempt_status)- },- amount_captured,- updated_by: storage_scheme.to_string(),- feature_metadata: updated_feature_metadata,- },+ Ok(ref _response) => {+ let status = self.get_intent_status_for_db_update(payment_data);++ PaymentIntentUpdate::ConfirmIntentPostUpdate {+ status,+ amount_captured: intent_amount_captured,+ updated_by: storage_scheme.to_string(),+ feature_metadata: updated_feature_metadata,+ }+ }+ Err(ref error) => {+ let status = self+ .get_intent_error_response_status_for_db_update(payment_data, error.clone());+ PaymentIntentUpdate::ConfirmIntentPostUpdate {+ status,+ amount_captured: intent_amount_captured,+ updated_by: storage_scheme.to_string(),+ feature_metadata: updated_feature_metadata,+ }+ }}}@@ -1001,6 +1014,83 @@ impl}}+ fn get_intent_status_for_db_update(+ &self,+ payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,+ ) -> common_enums::IntentStatus {+ let base_status =+ common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data));++ let amount_captured = self.get_captured_amount(payment_data);+ let intent_amount_captured = payment_data+ .payment_intent+ .amount_captured+ .map(|amount| amount + amount_captured.unwrap_or(MinorUnit::zero()))+ .or(amount_captured);++ let has_captured_amount = intent_amount_captured+ .map(|amt| amt > MinorUnit::zero())+ .unwrap_or(false);++ // If it's a partial authorization flow, we need to adjust the intent status accordingly+ if *payment_data.payment_intent.enable_partial_authorization && has_captured_amount {+ match self.status {+ common_enums::enums::AttemptStatus::Pending => {+ common_enums::IntentStatus::PartiallyCapturedAndProcessing+ }+ status if status.is_payment_terminal_failure() => {+ common_enums::IntentStatus::PartiallyCaptured+ }+ _ => base_status,+ }+ } else {+ base_status+ }+ }++ fn get_intent_error_response_status_for_db_update(+ &self,+ payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,+ error: ErrorResponse,+ ) -> common_enums::enums::IntentStatus {+ // Step 1: Determine attempt_status using existing logic+ let attempt_status = match error.attempt_status {+ // Use the status sent by connector in error_response if it's present+ Some(status) => status,+ None => match error.status_code {+ 500..=511 => common_enums::enums::AttemptStatus::Pending,+ _ => common_enums::enums::AttemptStatus::Failure,+ },+ };+ // Step 2: Check if amount was captured+ let amount_captured = self.get_captured_amount(payment_data);+ let intent_amount_captured = payment_data+ .payment_intent+ .amount_captured+ .map(|amount| amount + amount_captured.unwrap_or(MinorUnit::zero()))+ .or(amount_captured);++ let has_captured_amount = intent_amount_captured+ .map(|amt| amt > MinorUnit::zero())+ .unwrap_or(false);++ // Step 3: Map to intent status based on both attempt_status and amount_captured++ if *payment_data.payment_intent.enable_partial_authorization && has_captured_amount {+ match self.status {+ common_enums::enums::AttemptStatus::Pending => {+ common_enums::IntentStatus::PartiallyCapturedAndProcessing+ }+ status if status.is_payment_terminal_failure() => {+ common_enums::IntentStatus::PartiallyCaptured+ }+ _ => common_enums::IntentStatus::from(attempt_status),+ }+ } else {+ common_enums::IntentStatus::from(attempt_status)+ }+ }+fn get_amount_capturable(&self,payment_data: &payments::PaymentConfirmData<router_flow_types::Authorize>,@@ -1034,7 +1124,8 @@ impl}// Invalid statues for this flow, after doing authorization this state is invalidcommon_enums::IntentStatus::PartiallyCaptured- | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable+ | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,};self.minor_amount_capturable.or(amount_capturable_from_intent_status)@@ -1047,7 +1138,7 @@ impl) -> Option<MinorUnit> {// Based on the status of the response, we can determine the amount that was capturedlet intent_status = common_enums::IntentStatus::from(self.status);- let amount_captured_from_intent_status = match intent_status {+ match intent_status {// If the status is succeeded then we have captured the whole amount// we need not check for `amount_to_capture` here because passing `amount_to_capture` when authorizing is not supportedcommon_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => {@@ -1063,7 +1154,7 @@ implcommon_enums::IntentStatus::RequiresCustomerAction| common_enums::IntentStatus::RequiresMerchantAction| common_enums::IntentStatus::Processing- | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,+ | common_enums::IntentStatus::PartiallyCapturedAndProcessing => Some(MinorUnit::zero()),// Invalid states for this flowcommon_enums::IntentStatus::RequiresPaymentMethod| common_enums::IntentStatus::RequiresConfirmation => None,@@ -1074,11 +1165,10 @@ impl}// Invalid statues for this flowcommon_enums::IntentStatus::PartiallyCaptured- | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,- };- self.minor_amount_captured- .or(amount_captured_from_intent_status)- .or(Some(payment_data.payment_attempt.get_total_amount()))+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable => {+ self.minor_amount_captured+ }+ }}}#[cfg(feature = "v2")]@@ -1102,23 +1192,37 @@ impllet amount_captured = self.get_captured_amount(payment_data);match self.response {Ok(ref _response) => PaymentIntentUpdate::CaptureUpdate {- status: common_enums::IntentStatus::from(- self.get_attempt_status_for_db_update(payment_data),- ),+ status: self.get_intent_status_for_db_update(payment_data),amount_captured,updated_by: storage_scheme.to_string(),},Err(ref error) => PaymentIntentUpdate::CaptureUpdate {- status: error- .attempt_status- .map(common_enums::IntentStatus::from)- .unwrap_or(common_enums::IntentStatus::Failed),+ status: self+ .get_intent_error_response_status_for_db_update(payment_data, error.clone()),amount_captured,updated_by: storage_scheme.to_string(),},}}+ fn get_intent_status_for_db_update(+ &self,+ payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>,+ ) -> common_enums::enums::IntentStatus {+ common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data))+ }++ fn get_intent_error_response_status_for_db_update(+ &self,+ payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>,+ error: ErrorResponse,+ ) -> common_enums::enums::IntentStatus {+ error+ .attempt_status+ .map(common_enums::IntentStatus::from)+ .unwrap_or(common_enums::IntentStatus::Failed)+ }+fn get_payment_attempt_update(&self,payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>,@@ -1257,7 +1361,8 @@ impl}// Invalid statues for this flowcommon_enums::IntentStatus::PartiallyCaptured- | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable+ | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,}}@@ -1300,7 +1405,8 @@ impl| common_enums::IntentStatus::RequiresConfirmation => None,// Invalid statues for this flowcommon_enums::IntentStatus::PartiallyCaptured- | common_enums::IntentStatus::PartiallyCapturedAndCapturable => {+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable+ | common_enums::IntentStatus::PartiallyCapturedAndProcessing => {todo!()}}@@ -1326,29 +1432,105 @@ implstorage_scheme: common_enums::MerchantStorageScheme,) -> PaymentIntentUpdate {let amount_captured = self.get_captured_amount(payment_data);+ let updated_amount_captured_in_db = payment_data+ .payment_intent+ .amount_captured+ .map(|amount| amount + amount_captured.unwrap_or(MinorUnit::zero()))+ .or(amount_captured);+match self.response {- Ok(ref _response) => PaymentIntentUpdate::SyncUpdate {- status: common_enums::IntentStatus::from(- self.get_attempt_status_for_db_update(payment_data),- ),- amount_captured,- updated_by: storage_scheme.to_string(),- },- Err(ref error) => PaymentIntentUpdate::SyncUpdate {- status: {- let attempt_status = match error.attempt_status {- // Use the status sent by connector in error_response if it's present- Some(status) => status,- None => match error.status_code {- 200..=299 => common_enums::enums::AttemptStatus::Failure,- _ => self.status,- },- };- common_enums::IntentStatus::from(attempt_status)- },- amount_captured,- updated_by: storage_scheme.to_string(),+ Ok(ref _response) => {+ let status = self.get_intent_status_for_db_update(payment_data);+ PaymentIntentUpdate::SyncUpdate {+ status,+ amount_captured: updated_amount_captured_in_db,+ updated_by: storage_scheme.to_string(),+ }+ }+ Err(ref error) => {+ let status = self+ .get_intent_error_response_status_for_db_update(payment_data, error.clone());+ PaymentIntentUpdate::SyncUpdate {+ status,+ amount_captured: updated_amount_captured_in_db,+ updated_by: storage_scheme.to_string(),+ }+ }+ }+ }+ fn get_intent_status_for_db_update(+ &self,+ payment_data: &payments::PaymentStatusData<router_flow_types::PSync>,+ ) -> common_enums::IntentStatus {+ // Calculate base status from attempt+ let base_status =+ common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data));++ let amount_captured = self.get_captured_amount(payment_data);+ let intent_amount_captured = payment_data+ .payment_intent+ .amount_captured+ .map(|amount| amount + amount_captured.unwrap_or(MinorUnit::zero()))+ .or(amount_captured);++ let has_captured_amount = intent_amount_captured+ .map(|amt| amt > MinorUnit::zero())+ .unwrap_or(false);++ // If it's a partial authorization flow, we need to adjust the intent status accordingly+ if *payment_data.payment_intent.enable_partial_authorization && has_captured_amount {+ match self.status {+ common_enums::enums::AttemptStatus::Pending => {+ common_enums::IntentStatus::PartiallyCapturedAndProcessing+ }+ status if status.is_payment_terminal_failure() => {+ common_enums::IntentStatus::PartiallyCaptured+ }+ _ => base_status,+ }+ } else {+ base_status+ }+ }++ fn get_intent_error_response_status_for_db_update(+ &self,+ payment_data: &payments::PaymentStatusData<router_flow_types::PSync>,+ error: ErrorResponse,+ ) -> common_enums::enums::IntentStatus {+ // Step 1: Determine attempt_status using existing logic+ let attempt_status = match error.attempt_status {+ // Use the status sent by connector in error_response if it's present+ Some(status) => status,+ None => match error.status_code {+ 200..=299 => common_enums::enums::AttemptStatus::Failure,+ _ => self.status,},+ };++ // Step 2: Check if amount was captured+ let amount_captured = self.get_captured_amount(payment_data);+ let intent_amount_captured = payment_data+ .payment_intent+ .amount_captured+ .map(|amount| amount + amount_captured.unwrap_or(MinorUnit::zero()))+ .or(amount_captured);+ let has_captured_amount = intent_amount_captured+ .map(|amt| amt > MinorUnit::zero())+ .unwrap_or(false);+ // Step 3: Map to intent status based on both attempt_status and amount_captured+ if *payment_data.payment_intent.enable_partial_authorization && has_captured_amount {+ match self.status {+ common_enums::enums::AttemptStatus::Pending => {+ common_enums::IntentStatus::PartiallyCapturedAndProcessing+ }+ status if status.is_payment_terminal_failure() => {+ common_enums::IntentStatus::PartiallyCaptured+ }+ _ => common_enums::IntentStatus::from(attempt_status),+ }+ } else {+ common_enums::IntentStatus::from(attempt_status)}}@@ -1480,7 +1662,7 @@ impl// Based on the status of the response, we can determine the amount capturablelet intent_status = common_enums::IntentStatus::from(self.status);- let amount_capturable_from_intent_status = match intent_status {+ match intent_status {// If the status is already succeeded / failed we cannot capture any more amountcommon_enums::IntentStatus::Succeeded| common_enums::IntentStatus::Failed@@ -1498,15 +1680,11 @@ impl| common_enums::IntentStatus::RequiresConfirmation => None,common_enums::IntentStatus::RequiresCapture| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture- | common_enums::IntentStatus::PartiallyCaptured => {- let total_amount = payment_attempt.amount_details.get_net_amount();- Some(total_amount)- }+ | common_enums::IntentStatus::PartiallyCaptured => self.minor_amount_capturable,// Invalid statues for this flow- common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,- };- self.minor_amount_capturable- .or(amount_capturable_from_intent_status)+ common_enums::IntentStatus::PartiallyCapturedAndCapturable+ | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,+ }}fn get_captured_amount(@@ -1536,14 +1714,13 @@ implcommon_enums::IntentStatus::RequiresCustomerAction| common_enums::IntentStatus::RequiresMerchantAction| common_enums::IntentStatus::Processing- | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,+ | common_enums::IntentStatus::PartiallyCapturedAndProcessing => Some(MinorUnit::zero()),// Invalid states for this flowcommon_enums::IntentStatus::RequiresPaymentMethod| common_enums::IntentStatus::RequiresConfirmation => None,common_enums::IntentStatus::RequiresCapture| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {- let total_amount = payment_attempt.amount_details.get_net_amount();- Some(total_amount)+ Some(MinorUnit::zero())}// Invalid statues for this flowcommon_enums::IntentStatus::PartiallyCaptured@@ -1551,7 +1728,6 @@ impl};self.minor_amount_captured.or(amount_captured_from_intent_status)- .or(Some(payment_data.payment_attempt.get_total_amount()))}}@@ -1576,31 +1752,42 @@ impllet amount_captured = self.get_captured_amount(payment_data);match self.response {Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate {- status: common_enums::IntentStatus::from(- self.get_attempt_status_for_db_update(payment_data),- ),+ status: self.get_intent_status_for_db_update(payment_data),amount_captured,updated_by: storage_scheme.to_string(),feature_metadata: None,},Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate {- status: {- let attempt_status = match error.attempt_status {- // Use the status sent by connector in error_response if it's present- Some(status) => status,- None => match error.status_code {- 500..=511 => common_enums::enums::AttemptStatus::Pending,- _ => common_enums::enums::AttemptStatus::Failure,- },- };- common_enums::IntentStatus::from(attempt_status)- },+ status: self+ .get_intent_error_response_status_for_db_update(payment_data, error.clone()),amount_captured,updated_by: storage_scheme.to_string(),feature_metadata: None,},}}+ fn get_intent_status_for_db_update(+ &self,+ payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>,+ ) -> common_enums::enums::IntentStatus {+ common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data))+ }++ fn get_intent_error_response_status_for_db_update(+ &self,+ payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>,+ error: ErrorResponse,+ ) -> common_enums::enums::IntentStatus {+ let attempt_status = match error.attempt_status {+ // Use the status sent by connector in error_response if it's present+ Some(status) => status,+ None => match error.status_code {+ 500..=511 => common_enums::enums::AttemptStatus::Pending,+ _ => common_enums::enums::AttemptStatus::Failure,+ },+ };+ common_enums::IntentStatus::from(attempt_status)+ }fn get_payment_attempt_update(&self,@@ -1762,7 +1949,8 @@ implSome(total_amount)}common_enums::IntentStatus::PartiallyCaptured- | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable+ | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,}}@@ -1790,7 +1978,8 @@ implcommon_enums::IntentStatus::RequiresCapture| common_enums::IntentStatus::CancelledPostCapture => Some(MinorUnit::zero()),common_enums::IntentStatus::PartiallyCaptured- | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable+ | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,}}}@@ -1816,18 +2005,14 @@ impllet amount_captured = self.get_captured_amount(payment_data);match self.response {Ok(ref _response) => PaymentIntentUpdate::ConfirmIntentPostUpdate {- status: common_enums::IntentStatus::from(- self.get_attempt_status_for_db_update(payment_data),- ),+ status: self.get_intent_status_for_db_update(payment_data),amount_captured,updated_by: storage_scheme.to_string(),feature_metadata: None,},Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate {- status: error- .attempt_status- .map(common_enums::IntentStatus::from)- .unwrap_or(common_enums::IntentStatus::Failed),+ status: self+ .get_intent_error_response_status_for_db_update(payment_data, error.clone()),amount_captured,updated_by: storage_scheme.to_string(),feature_metadata: None,@@ -1835,6 +2020,24 @@ impl}}+ fn get_intent_status_for_db_update(+ &self,+ payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>,+ ) -> common_enums::enums::IntentStatus {+ common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data))+ }++ fn get_intent_error_response_status_for_db_update(+ &self,+ payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>,+ error: ErrorResponse,+ ) -> common_enums::enums::IntentStatus {+ error+ .attempt_status+ .map(common_enums::IntentStatus::from)+ .unwrap_or(common_enums::IntentStatus::Failed)+ }+fn get_payment_attempt_update(&self,payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>,@@ -1994,7 +2197,8 @@ impl}// Invalid statues for this flow, after doing authorization this state is invalidcommon_enums::IntentStatus::PartiallyCaptured- | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable+ | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,}}@@ -2031,7 +2235,8 @@ impl}// Invalid statues for this flowcommon_enums::IntentStatus::PartiallyCaptured- | common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,+ | common_enums::IntentStatus::PartiallyCapturedAndCapturable+ | common_enums::IntentStatus::PartiallyCapturedAndProcessing => None,}}}@@ -2054,13 +2259,29 @@ implpayment_data: &payments::PaymentCancelData<router_flow_types::Void>,storage_scheme: common_enums::MerchantStorageScheme,) -> PaymentIntentUpdate {- let intent_status =- common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data));+ let intent_status = self.get_intent_status_for_db_update(payment_data);PaymentIntentUpdate::VoidUpdate {status: intent_status,updated_by: storage_scheme.to_string(),}}+ fn get_intent_status_for_db_update(+ &self,+ payment_data: &payments::PaymentCancelData<router_flow_types::Void>,+ ) -> common_enums::enums::IntentStatus {+ common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data))+ }++ fn get_intent_error_response_status_for_db_update(+ &self,+ payment_data: &payments::PaymentCancelData<router_flow_types::Void>,+ error: ErrorResponse,+ ) -> common_enums::enums::IntentStatus {+ error+ .attempt_status+ .map(common_enums::IntentStatus::from)+ .unwrap_or(common_enums::IntentStatus::Failed)+ }fn get_payment_attempt_update(&self,diff --git a/crates/router/src/core/payments/operations/payment_attempt_record.rs b/crates/router/src/core/payments/operations/payment_attempt_record.rsindex 971cd6f1d9..51565c62ff 100644--- a/crates/router/src/core/payments/operations/payment_attempt_record.rs+++ b/crates/router/src/core/payments/operations/payment_attempt_record.rs@@ -5,7 +5,7 @@ use async_trait::async_trait;use common_utils::{errors::CustomResult,ext_traits::{AsyncExt, Encode, ValueExt},- types::keymanager::ToEncryptable,+ types::{keymanager::ToEncryptable, MinorUnit},};use error_stack::ResultExt;use hyperswitch_domain_models::payments::PaymentAttemptRecordData;@@ -77,7 +77,8 @@ impl ValidateStatusForOperation for PaymentAttemptRecord {match intent_status {// Payment attempt can be recorded for failed payment as well in revenue recovery flow.common_enums::IntentStatus::RequiresPaymentMethod- | common_enums::IntentStatus::Failed => Ok(()),+ | common_enums::IntentStatus::Failed+ | common_enums::IntentStatus::PartiallyCaptured => Ok(()),common_enums::IntentStatus::Succeeded| common_enums::IntentStatus::Cancelled| common_enums::IntentStatus::CancelledPostCapture@@ -262,14 +263,24 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentAttemptRecordData<F>, PaymentsAttecommon_enums::TriggeredBy::Internal => Some(payment_data.payment_attempt.id.clone()),common_enums::TriggeredBy::External => None,};+ let active_attempts_group_id = payment_data.payment_intent.active_attempts_group_id.clone();+ let amount_captured = payment_data.payment_intent.amount_captured;+ let status = if amount_captured > Some(MinorUnit::new(0))+ && *payment_data.payment_intent.enable_partial_authorization+ {+ common_enums::IntentStatus::PartiallyCapturedAndProcessing+ } else {+ common_enums::IntentStatus::from(payment_data.payment_attempt.status)+ };let payment_intent_update =hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::RecordUpdate{- status: common_enums::IntentStatus::from(payment_data.payment_attempt.status),+ status,feature_metadata: Box::new(feature_metadata),updated_by: storage_scheme.to_string(),- active_attempt_id+ active_attempt_id,+ active_attempts_group_id,};payment_data.payment_intent = statediff --git a/crates/router/src/core/payments/operations/payment_create_intent.rs b/crates/router/src/core/payments/operations/payment_create_intent.rsindex 32dbecc10c..182a4819a4 100644--- a/crates/router/src/core/payments/operations/payment_create_intent.rs+++ b/crates/router/src/core/payments/operations/payment_create_intent.rs@@ -109,6 +109,8 @@ impl<F: Send + Clone + Sync>}let key_manager_state = &state.into();+ let cell_id = state.conf.cell_information.id.clone();+let storage_scheme = platform.get_processor().get_account().storage_scheme;let batch_encrypted_data = domain_types::crypto_operation(@@ -143,6 +145,7 @@ impl<F: Send + Clone + Sync>profile,request.clone(),encrypted_data,+ cell_id,).await?;diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rsindex bbfc923efb..deb69033af 100644--- a/crates/router/src/core/payments/operations/payment_update_intent.rs+++ b/crates/router/src/core/payments/operations/payment_update_intent.rs@@ -61,6 +61,7 @@ impl ValidateStatusForOperation for PaymentUpdateIntent {| common_enums::IntentStatus::RequiresCapture| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture| common_enums::IntentStatus::PartiallyCaptured+ | common_enums::IntentStatus::PartiallyCapturedAndProcessing| common_enums::IntentStatus::RequiresConfirmation| common_enums::IntentStatus::PartiallyCapturedAndCapturable| common_enums::IntentStatus::Expired => {@@ -392,6 +393,8 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsUpdateInforce_3ds_challenge: intent.force_3ds_challenge,is_iframe_redirection_enabled: intent.is_iframe_redirection_enabled,enable_partial_authorization: Some(intent.enable_partial_authorization),+ active_attempts_group_id: intent.active_attempts_group_id,+ active_attempt_id_type: Some(intent.active_attempt_id_type),}));let new_payment_intent = dbdiff --git a/crates/router/src/core/payments/operations/proxy_payments_intent.rs b/crates/router/src/core/payments/operations/proxy_payments_intent.rsindex e1c2849bc0..7566a038b4 100644--- a/crates/router/src/core/payments/operations/proxy_payments_intent.rs+++ b/crates/router/src/core/payments/operations/proxy_payments_intent.rs@@ -42,7 +42,8 @@ impl ValidateStatusForOperation for PaymentProxyIntent {//Failed state is included here so that in PCR, retries can be done for failed payments, otherwise for a failed attempt it was asking for new payment_intentcommon_enums::IntentStatus::RequiresPaymentMethod| common_enums::IntentStatus::Failed- | common_enums::IntentStatus::Processing => Ok(()),+ | common_enums::IntentStatus::Processing+ | common_enums::IntentStatus::PartiallyCapturedAndProcessing => Ok(()),//Failed state is included here so that in PCR, retries can be done for failed payments, otherwise for a failed attempt it was asking for new payment_intentcommon_enums::IntentStatus::RequiresPaymentMethod| common_enums::IntentStatus::Failed => Ok(()),@@ -192,8 +193,9 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ProxyPaymentsRhyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed while encrypting payment intent details")?;+ let active_attempt_id = payment_intent.active_attempt_id.clone();- let payment_attempt = match payment_intent.active_attempt_id.clone() {+ let payment_attempt = match active_attempt_id {Some(ref active_attempt_id) => db.find_payment_attempt_by_id(platform.get_processor().get_key_store(),@@ -395,12 +397,12 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, ProxyPaymentsReque.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Merchant connector id is none when constructing response")?,);-+ let active_attempt_id = payment_data.payment_intent.active_attempt_id.clone();let payment_intent_update =hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntent {status: intent_status,updated_by: storage_scheme.to_string(),- active_attempt_id: Some(payment_data.payment_attempt.id.clone()),+ active_attempt_id,};let authentication_type = payment_datadiff --git a/crates/router/src/core/revenue_recovery.rs b/crates/router/src/core/revenue_recovery.rsindex dbdbcf1b84..2061c162a3 100644--- a/crates/router/src/core/revenue_recovery.rs+++ b/crates/router/src/core/revenue_recovery.rs@@ -262,7 +262,7 @@ pub async fn perform_execute_payment(revenue_recovery_metadata.payment_connector_transmission.unwrap_or_default(),- payment_intent.active_attempt_id.clone(),+ payment_intent.active_attempt_id.as_ref(),revenue_recovery_payment_data,&tracking_data.global_payment_id,)@@ -338,8 +338,7 @@ pub async fn perform_execute_payment(}};}-- types::Decision::Psync(attempt_status, attempt_id) => {+ types::Decision::Psync(intent_status, attempt_id) => {// find if a psync task is already presentlet task = PSYNC_WORKFLOW;let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;@@ -348,11 +347,11 @@ pub async fn perform_execute_payment(match psync_process {Some(_) => {- let pcr_status: types::RevenueRecoveryPaymentsAttemptStatus =- attempt_status.foreign_into();+ let pcr_status: types::RevenueRecoveryPaymentIntentStatus =+ intent_status.foreign_into();pcr_status- .update_pt_status_based_on_attempt_status_for_execute_payment(+ .update_pt_status_based_on_intent_status_for_execute_payment(db,execute_task_process,)@@ -509,8 +508,8 @@ pub async fn perform_payments_sync(.and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone()).get_required_value("Payment Revenue Recovery Metadata")?.convert_back();- let pcr_status: types::RevenueRecoveryPaymentsAttemptStatus =- payment_attempt.status.foreign_into();+ let pcr_status: types::RevenueRecoveryPaymentIntentStatus =+ payment_intent.status.foreign_into();let new_revenue_recovery_payment_data = &pcr::RevenueRecoveryPaymentData {psync_data: Some(psync_data),@@ -703,7 +702,7 @@ pub async fn perform_calculate_workflow(logger::info!(process_id = %process.id,connector_customer_id = %connector_customer_id,- "Hard decline flag is false, rescheduling for scheduled time + 15 mins"+ "Hard decline flag is false, rescheduling after job_schedule_buffer_time_in_seconds");update_calculate_job_schedule_time(@@ -1179,9 +1178,12 @@ pub async fn resume_revenue_recovery_process_tracker(| IntentStatus::PartiallyAuthorizedAndRequiresCapture| IntentStatus::PartiallyCapturedAndProcessing| IntentStatus::Conflicted- | IntentStatus::Expired => Err(report!(errors::ApiErrorResponse::NotSupported {- message: "Invalid Payment Status ".to_owned(),- })),+ | IntentStatus::Expired+ | IntentStatus::PartiallyCapturedAndProcessing => {+ Err(report!(errors::ApiErrorResponse::NotSupported {+ message: "Invalid Payment Status ".to_owned(),+ }))+ }}}pub async fn get_payment_response_using_payment_get_operation(@@ -1231,25 +1233,29 @@ pub async fn reset_connector_transmission_and_active_attempt_id_before_pushing_t.and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone()).get_required_value("Payment Revenue Recovery Metadata")?.convert_back();- match active_payment_attempt_id {- Some(_) => {+ match (active_payment_attempt_id, &payment_intent.status) {+ // No active attempt OR status is PartiallyCaptured - return None+ (None, _) | (Some(_), IntentStatus::PartiallyCaptured) => Ok(None),++ // Has active attempt and status is not PartiallyCaptured - proceed with update+ (Some(_), _) => {// update the connector payment transmission field to Unsuccessful and unset active attempt idrevenue_recovery_metadata.set_payment_transmission_field_for_api_request(enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,);let payment_update_req =- api_payments::PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api(- payment_intent- .feature_metadata- .clone()- .unwrap_or_default()- .convert_back()- .set_payment_revenue_recovery_metadata_using_api(- revenue_recovery_metadata.clone(),- ),- enums::UpdateActiveAttempt::Unset,- );+ api_payments::PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api(+ payment_intent+ .feature_metadata+ .clone()+ .unwrap_or_default()+ .convert_back()+ .set_payment_revenue_recovery_metadata_using_api(+ revenue_recovery_metadata.clone(),+ ),+ enums::UpdateActiveAttempt::Unset,+ );logger::info!("Call made to payments update intent api , with the request body {:?}",payment_update_req@@ -1265,7 +1271,6 @@ pub async fn reset_connector_transmission_and_active_attempt_id_before_pushing_tOk(Some(()))}- None => Ok(None),}}diff --git a/crates/router/src/core/revenue_recovery/transformers.rs b/crates/router/src/core/revenue_recovery/transformers.rsindex 2016d7b5cc..8b09b4a354 100644--- a/crates/router/src/core/revenue_recovery/transformers.rs+++ b/crates/router/src/core/revenue_recovery/transformers.rs@@ -1,45 +1,44 @@-use common_enums::AttemptStatus;+use common_enums::IntentStatus;use masking::PeekInterface;use crate::{- core::revenue_recovery::types::RevenueRecoveryPaymentsAttemptStatus,+ core::revenue_recovery::types::RevenueRecoveryPaymentIntentStatus,types::transformers::ForeignFrom,};-impl ForeignFrom<AttemptStatus> for RevenueRecoveryPaymentsAttemptStatus {- fn foreign_from(s: AttemptStatus) -> Self {- match s {- AttemptStatus::Authorized- | AttemptStatus::Charged- | AttemptStatus::AutoRefunded- | AttemptStatus::PartiallyAuthorized- | AttemptStatus::PartialCharged- | AttemptStatus::PartialChargedAndChargeable => Self::Succeeded,-- AttemptStatus::Started- | AttemptStatus::AuthenticationSuccessful- | AttemptStatus::Authorizing- | AttemptStatus::CodInitiated- | AttemptStatus::VoidInitiated- | AttemptStatus::CaptureInitiated- | AttemptStatus::Pending => Self::Processing,-- AttemptStatus::AuthenticationFailed- | AttemptStatus::AuthorizationFailed- | AttemptStatus::VoidFailed- | AttemptStatus::RouterDeclined- | AttemptStatus::CaptureFailed- | AttemptStatus::Failure => Self::Failed,+impl ForeignFrom<IntentStatus> for RevenueRecoveryPaymentIntentStatus {+ fn foreign_from(status: IntentStatus) -> Self {+ match status {+ IntentStatus::Succeeded => Self::Succeeded,+ IntentStatus::PartiallyCapturedAndProcessing | IntentStatus::Processing => {+ Self::Processing+ }+ IntentStatus::Failed => Self::Failed,+ IntentStatus::PartiallyCaptured | IntentStatus::PartiallyCapturedAndCapturable => {+ Self::PartialCharged+ }+ IntentStatus::Cancelled+ | IntentStatus::CancelledPostCapture+ | IntentStatus::RequiresCustomerAction+ | IntentStatus::RequiresMerchantAction+ | IntentStatus::RequiresPaymentMethod+ | IntentStatus::RequiresConfirmation+ | IntentStatus::RequiresCapture+ | IntentStatus::PartiallyAuthorizedAndRequiresCapture+ | IntentStatus::Conflicted+ | IntentStatus::Expired => Self::InvalidStatus(status.to_string()),+ }+ }+}- AttemptStatus::Voided- | AttemptStatus::VoidedPostCharge- | AttemptStatus::ConfirmationAwaited- | AttemptStatus::PaymentMethodAwaited- | AttemptStatus::AuthenticationPending- | AttemptStatus::DeviceDataCollectionPending- | AttemptStatus::Unresolved- | AttemptStatus::IntegrityFailure- | AttemptStatus::Expired => Self::InvalidStatus(s.to_string()),+impl From<RevenueRecoveryPaymentIntentStatus> for common_enums::EventType {+ fn from(status: RevenueRecoveryPaymentIntentStatus) -> Self {+ match status {+ RevenueRecoveryPaymentIntentStatus::Succeeded => Self::PaymentSucceeded,+ RevenueRecoveryPaymentIntentStatus::PartialCharged => Self::PaymentCaptured,+ RevenueRecoveryPaymentIntentStatus::Processing => Self::PaymentProcessing,+ RevenueRecoveryPaymentIntentStatus::Failed => Self::PaymentFailed,+ RevenueRecoveryPaymentIntentStatus::InvalidStatus(_) => Self::ActionRequired,}}}diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rsindex 242c76d618..31ae2998d1 100644--- a/crates/router/src/core/revenue_recovery/types.rs+++ b/crates/router/src/core/revenue_recovery/types.rs@@ -60,23 +60,24 @@ type RecoveryResult<T> = error_stack::Result<T, errors::RecoveryError>;pub const REVENUE_RECOVERY: &str = "revenue_recovery";/// The status of Passive Churn Payments#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]-pub enum RevenueRecoveryPaymentsAttemptStatus {+pub enum RevenueRecoveryPaymentIntentStatus {Succeeded,Failed,Processing,InvalidStatus(String),+ PartialCharged,// Cancelled,}-impl RevenueRecoveryPaymentsAttemptStatus {- pub(crate) async fn update_pt_status_based_on_attempt_status_for_execute_payment(+impl RevenueRecoveryPaymentIntentStatus {+ pub(crate) async fn update_pt_status_based_on_intent_status_for_execute_payment(&self,db: &dyn StorageInterface,execute_task_process: &storage::ProcessTracker,) -> Result<(), errors::ProcessTrackerError> {- logger::info!("Entering update_pt_status_based_on_attempt_status_for_execute_payment");+ logger::info!("Entering update_pt_status_based_on_intent_status_for_execute_payment");match &self {- Self::Succeeded | Self::Failed | Self::Processing => {+ Self::Succeeded | Self::PartialCharged | Self::Failed | Self::Processing => {// finish the current execute taskdb.finish_process_with_business_status(execute_task_process.clone(),@@ -145,19 +146,18 @@ impl RevenueRecoveryPaymentsAttemptStatus {.as_ref().ok_or(errors::RecoveryError::ValueNotFound).attach_printable("Psync data not found in revenue recovery payment data")?;-- match self {+ let intent_status: Self = psync_response.payment_intent.status.foreign_into();+ let event_status = common_enums::EventType::from(intent_status.clone());+ match intent_status {Self::Succeeded => {// finish psync task as the payment was a successdb.as_scheduler().finish_process_with_business_status(- process_tracker,+ process_tracker.clone(),business_status::PSYNC_WORKFLOW_COMPLETE,).await?;- let event_status = common_enums::EventType::PaymentSucceeded;-// publish events to kafkaif let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(state,@@ -222,6 +222,72 @@ impl RevenueRecoveryPaymentsAttemptStatus {.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed).attach_printable("Failed to update the process tracker")?;}+ Self::PartialCharged => {+ // finish psync task as the payment was a PartialCharged+ db.as_scheduler()+ .finish_process_with_business_status(+ process_tracker.clone(),+ business_status::PSYNC_WORKFLOW_COMPLETE,+ )+ .await?;++ // publish events to kafka+ recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(+ state,+ &recovery_payment_tuple,+ Some(retry_count + 1),+ )+ .await+ .inspect_err(|e| {+ router_env::logger::error!(+ "Failed to publish revenue recovery event to kafka: {:?}",+ e+ );+ })+ .ok();++ // update the status of token in redis+ let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(+ state,+ &connector_customer_id,+ &None,+ &None,+ used_token.as_deref(),+ )+ .await;++ let payments_response = psync_response+ .clone()+ .generate_response(state, None, None, None, &platform, profile, None)+ .change_context(errors::RecoveryError::PaymentsResponseGenerationFailed)+ .attach_printable("Failed while generating response for payment")?;++ Box::pin(reopen_calculate_workflow_on_payment_failure(+ state,+ &process_tracker.clone(),+ profile,+ platform.clone(),+ payment_intent,+ revenue_recovery_payment_data,+ psync_response.payment_attempt.get_id(),+ ))+ .await?;++ RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status(+ state,+ common_enums::EventClass::Payments,+ event_status,+ payment_intent,+ &platform,+ profile,+ recovery_payment_attempt+ .attempt_id+ .get_string_repr()+ .to_string(),+ payments_response+ )+ .await?;+ }Self::Failed => {// finish psync taskdb.as_scheduler()@@ -311,7 +377,7 @@ impl RevenueRecoveryPaymentsAttemptStatus {}pub enum Decision {Execute,- Psync(enums::AttemptStatus, id_type::GlobalAttemptId),+ Psync(enums::IntentStatus, id_type::GlobalAttemptId),InvalidDecision,ReviewForSuccessfulPayment,ReviewForFailedPayment(enums::TriggeredBy),@@ -322,7 +388,7 @@ impl Decision {state: &SessionState,intent_status: enums::IntentStatus,called_connector: enums::PaymentConnectorTransmission,- active_attempt_id: Option<id_type::GlobalAttemptId>,+ active_attempt_id: Option<&id_type::GlobalAttemptId>,revenue_recovery_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,payment_id: &id_type::GlobalPaymentId,) -> RecoveryResult<Self> {@@ -334,6 +400,11 @@ impl Decision {enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,None,) => Self::Execute,+ (+ enums::IntentStatus::PartiallyCaptured,+ enums::PaymentConnectorTransmission::ConnectorCallSucceeded,+ Some(_),+ ) => Self::Execute,(enums::IntentStatus::Processing,enums::PaymentConnectorTransmission::ConnectorCallSucceeded,@@ -350,7 +421,27 @@ impl Decision {.change_context(errors::RecoveryError::PaymentCallFailed).attach_printable("Error while executing the Psync call")?;let payment_attempt = psync_data.payment_attempt;- Self::Psync(payment_attempt.status, payment_attempt.get_id().clone())+ let payment_intent = psync_data.payment_intent;+ Self::Psync(payment_intent.status, payment_attempt.get_id().clone())+ }+ (+ enums::IntentStatus::PartiallyCapturedAndProcessing,+ enums::PaymentConnectorTransmission::ConnectorCallSucceeded,+ Some(_),+ ) => {+ let psync_data = revenue_recovery_core::api::call_psync_api(+ state,+ payment_id,+ revenue_recovery_data,+ true,+ true,+ )+ .await+ .change_context(errors::RecoveryError::PaymentCallFailed)+ .attach_printable("Error while executing the Psync call")?;+ let payment_attempt = psync_data.payment_attempt;+ let payment_intent = psync_data.payment_intent;+ Self::Psync(payment_intent.status, payment_attempt.get_id().clone())}(enums::IntentStatus::Failed,@@ -393,6 +484,7 @@ pub enum Action {RetryPayment(PrimitiveDateTime),TerminalFailure(PaymentAttempt),SuccessfulPayment(PaymentAttempt),+ PartialCharged,ReviewPayment,ManualReviewAction,}@@ -430,6 +522,7 @@ impl Action {hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from(payment_intent,);+ let intent_status = recovery_payment_intent.status;// handle proxy api's responsematch response {Ok(payment_data) => {@@ -469,9 +562,11 @@ impl Action {logger::error!("Failed to handle account updater action: {:?}", e);}).ok();-- match payment_data.payment_attempt.status.foreign_into() {- RevenueRecoveryPaymentsAttemptStatus::Succeeded => {+ let intent_status: RevenueRecoveryPaymentIntentStatus =+ payment_data.payment_intent.status.foreign_into();+ let event_status = common_enums::EventType::from(intent_status.clone());+ match intent_status {+ RevenueRecoveryPaymentIntentStatus::Succeeded => {let recovery_payment_attempt =hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(&payment_data.payment_attempt,@@ -507,14 +602,13 @@ impl Action {.await;// unlocking the token- let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(++ storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(state,- &connector_customer_id,+ &connector_customer_id,&payment_intent.id)- .await;-- let event_status = common_enums::EventType::PaymentSucceeded;+ .await;let payments_response = payment_data.clone()@@ -538,7 +632,48 @@ impl Action {payment_data.payment_attempt.clone(),))}- RevenueRecoveryPaymentsAttemptStatus::Failed => {+ RevenueRecoveryPaymentIntentStatus::PartialCharged => {+ let recovery_payment_attempt =+ hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(+ &payment_data.payment_attempt,+ );++ let recovery_payment_tuple =+ recovery_incoming_flow::RecoveryPaymentTuple::new(+ &recovery_payment_intent,+ &recovery_payment_attempt,+ );++ // update the status of token in redis+ let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(+ state,+ &connector_customer_id,+ &None,+ &None,+ Some(&scheduled_token.payment_processor_token_details.payment_processor_token),+ )+ .await;+ let payments_response = payment_data+ .clone()+ .generate_response(state, None, None, None, &platform, profile, None)+ .change_context(errors::RecoveryError::PaymentsResponseGenerationFailed)+ .attach_printable("Failed while generating response for payment")?;++ RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status(+ state,+ common_enums::EventClass::Payments,+ event_status,+ payment_intent,+ &platform,+ profile,+ payment_data.payment_attempt.id.get_string_repr().to_string(),+ payments_response+ )+ .await?;++ Ok(Self::PartialCharged)+ }+ RevenueRecoveryPaymentIntentStatus::Failed => {let recovery_payment_attempt =hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(&payment_data.payment_attempt,@@ -589,12 +724,12 @@ impl Action {.await;// unlocking the token- let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(- state,- &connector_customer_id,+ storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(+ state,+ &connector_customer_id,&payment_intent.id- )- .await;+ )+ .await;// Reopen calculate workflow on payment failureBox::pin(reopen_calculate_workflow_on_payment_failure(@@ -612,10 +747,10 @@ impl Action {Ok(Self::TerminalFailure(payment_data.payment_attempt.clone()))}- RevenueRecoveryPaymentsAttemptStatus::Processing => {+ RevenueRecoveryPaymentIntentStatus::Processing => {Ok(Self::SyncPayment(payment_data.payment_attempt.clone()))}- RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => {+ RevenueRecoveryPaymentIntentStatus::InvalidStatus(action) => {logger::info!(?action, "Invalid Payment Status For PCR Payment");Ok(Self::ManualReviewAction)}@@ -741,6 +876,17 @@ impl Action {.attach_printable("Failed to update the process tracker")?;Ok(())}+ Self::PartialCharged => {+ db.as_scheduler()+ .finish_process_with_business_status(+ execute_task_process.clone(),+ business_status::EXECUTE_WORKFLOW_COMPLETE,+ )+ .await+ .change_context(errors::RecoveryError::ProcessTrackerFailure)+ .attach_printable("Failed to update the process tracker")?;+ Ok(())+ }Self::ReviewPayment => {// requeue the process tracker in case of error responselet pt_update = storage::ProcessTrackerUpdate::StatusUpdate {@@ -789,8 +935,8 @@ impl Action {let used_token = get_payment_processor_token_id_from_payment_attempt(&payment_attempt);match response {- Ok(_payment_data) => match payment_attempt.status.foreign_into() {- RevenueRecoveryPaymentsAttemptStatus::Succeeded => {+ Ok(_payment_data) => match payment_intent.status.foreign_into() {+ RevenueRecoveryPaymentIntentStatus::Succeeded => {let connector_customer_id = payment_intent.extract_connector_customer_id_from_payment_intent().change_context(errors::RecoveryError::ValueNotFound)@@ -807,16 +953,35 @@ impl Action {.await;// unlocking the token- let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(+ let intent_status = payment_intent.status;+ storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(state,&connector_customer_id,&payment_intent.id+ )+ .await;++ Ok(Self::SuccessfulPayment(payment_attempt))+ }+ RevenueRecoveryPaymentIntentStatus::PartialCharged => {+ let connector_customer_id = payment_intent+ .extract_connector_customer_id_from_payment_intent()+ .change_context(errors::RecoveryError::ValueNotFound)+ .attach_printable("Failed to extract customer ID from payment intent")?;++ // update the status of token in redis+ let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(+ state,+ &connector_customer_id,+ &None,+ &None,+ used_token.as_deref(),).await;- Ok(Self::SuccessfulPayment(payment_attempt))+ Ok(Self::PartialCharged)}- RevenueRecoveryPaymentsAttemptStatus::Failed => {+ RevenueRecoveryPaymentIntentStatus::Failed => {let connector_customer_id = payment_intent.extract_connector_customer_id_from_payment_intent().change_context(errors::RecoveryError::ValueNotFound)@@ -837,12 +1002,12 @@ impl Action {used_token.as_deref(),).await;-+ let intent_status = payment_intent.status;// unlocking the token- let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(- state,- &connector_customer_id,- &payment_intent.id+ storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(+ state,+ &connector_customer_id,+ &payment_intent.id).await;@@ -861,10 +1026,10 @@ impl Action {Ok(Self::TerminalFailure(payment_attempt.clone()))}- RevenueRecoveryPaymentsAttemptStatus::Processing => {+ RevenueRecoveryPaymentIntentStatus::Processing => {Ok(Self::SyncPayment(payment_attempt))}- RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => {+ RevenueRecoveryPaymentIntentStatus::InvalidStatus(action) => {logger::info!(?action, "Invalid Payment Status For PCR PSync Payment");Ok(Self::ManualReviewAction)}@@ -987,6 +1152,19 @@ impl Action {.attach_printable("Failed to update the process tracker")?;Ok(())}+ Self::PartialCharged => {+ // finish the current psync task+ db.as_scheduler()+ .finish_process_with_business_status(+ psync_task_process.clone(),+ business_status::PSYNC_WORKFLOW_COMPLETE,+ )+ .await+ .change_context(errors::RecoveryError::ProcessTrackerFailure)+ .attach_printable("Failed to update the process tracker")?;++ Ok(())+ }Self::ReviewPayment => {// requeue the process tracker task in case of psync api errorlet pt_update = storage::ProcessTrackerUpdate::StatusUpdate {