Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(revenue_recovery): Add account updater support in revenue recovery flow for worldpayvantiv connector (#10112)

CHALLA NISHANTH BABU66ffd8a26c05
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 6dd9a0afa4..24e8d1e5ff 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -2149,6 +2149,31 @@ impl MandateIds {
Some(MandateReferenceId::NetworkMandateId(_))
)
}
+
+ pub fn get_connector_mandate_id(&self) -> Option<String> {
+ match &self.mandate_reference_id {
+ Some(MandateReferenceId::ConnectorMandateId(data)) => data.connector_mandate_id.clone(),
+ _ => None,
+ }
+ }
+
+ pub fn get_connector_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> {
+ match &self.mandate_reference_id {
+ Some(MandateReferenceId::ConnectorMandateId(data)) => data.mandate_metadata.clone(),
+ _ => None,
+ }
+ }
+
+ pub fn get_updated_mandate_details_of_connector_mandate_id(
+ &self,
+ ) -> Option<UpdatedMandateDetails> {
+ match &self.mandate_reference_id {
+ Some(MandateReferenceId::ConnectorMandateId(data)) => {
+ data.updated_mandate_details.clone()
+ }
+ _ => None,
+ }
+ }
}
#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)]
@@ -2172,6 +2197,48 @@ pub struct ConnectorMandateReferenceId {
update_history: Option<Vec<UpdateHistory>>,
mandate_metadata: Option<pii::SecretSerdeValue>,
connector_mandate_request_reference_id: Option<String>,
+ updated_mandate_details: Option<UpdatedMandateDetails>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)]
+pub struct UpdatedMandateDetails {
+ pub card_network: Option<common_enums::CardNetwork>,
+ pub card_exp_month: Option<Secret<String>>,
+ pub card_exp_year: Option<Secret<String>>,
+ pub card_isin: Option<String>,
+}
+
+impl From<AdditionalCardInfo> for UpdatedMandateDetails {
+ fn from(card_info: AdditionalCardInfo) -> Self {
+ Self {
+ card_network: card_info.card_network,
+ card_exp_month: card_info.card_exp_month,
+ card_exp_year: card_info.card_exp_year,
+ card_isin: card_info.card_isin,
+ }
+ }
+}
+
+impl From<&UpdatedMandateDetails> for AdditionalCardInfo {
+ fn from(card_info: &UpdatedMandateDetails) -> Self {
+ Self {
+ card_network: card_info.card_network.clone(),
+ card_exp_month: card_info.card_exp_month.clone(),
+ card_exp_year: card_info.card_exp_year.clone(),
+ card_isin: card_info.card_isin.clone(),
+ card_issuer: None,
+ card_type: None,
+ card_issuing_country: None,
+ bank_code: None,
+ last4: None,
+ card_extended_bin: None,
+ card_holder_name: None,
+ payment_checks: None,
+ authentication_data: None,
+ is_regulated: None,
+ signature_network: None,
+ }
+ }
}
impl ConnectorMandateReferenceId {
@@ -2181,6 +2248,7 @@ impl ConnectorMandateReferenceId {
update_history: Option<Vec<UpdateHistory>>,
mandate_metadata: Option<pii::SecretSerdeValue>,
connector_mandate_request_reference_id: Option<String>,
+ updated_mandate_details: Option<UpdatedMandateDetails>,
) -> Self {
Self {
connector_mandate_id,
@@ -2188,6 +2256,7 @@ impl ConnectorMandateReferenceId {
update_history,
mandate_metadata,
connector_mandate_request_reference_id,
+ updated_mandate_details,
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs
index d9842dc503..ad73e802a9 100644
--- a/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs
@@ -4118,6 +4118,7 @@ fn build_connector_response(
None,
None,
Some(extend_authorization_response),
+ None,
))
}
diff --git a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
index 29954464fc..f67418da60 100644
--- a/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
@@ -1696,6 +1696,7 @@ impl TryFrom<PaymentsExtendAuthorizationResponseRouterData<PaypalExtendedAuthRes
None,
None,
Some(extend_authorization_response),
+ None,
));
let status = common_enums::AttemptStatus::from(item.response.status.clone());
diff --git a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs
index e2c7a08b06..54cc247c95 100644
--- a/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/stripe/transformers.rs
@@ -2987,6 +2987,7 @@ fn extract_payment_method_connector_response_from_latest_charge(
additional_payment_method_data,
is_overcapture_enabled,
extended_authorization_data,
+ None,
))
} else {
None
diff --git a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
index 525ce70a4a..b99dbef253 100644
--- a/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
@@ -1,5 +1,6 @@
use common_utils::{
ext_traits::Encode,
+ pii,
types::{MinorUnit, StringMajorUnit, StringMinorUnitForConnector},
};
use error_stack::ResultExt;
@@ -29,6 +30,7 @@ use hyperswitch_domain_models::{
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
+use router_env::logger;
use serde::{Deserialize, Serialize};
use crate::{
@@ -121,11 +123,9 @@ pub struct WorldpayvantivMetadataObject {
pub merchant_config_currency: common_enums::Currency,
}
-impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for WorldpayvantivMetadataObject {
+impl TryFrom<&Option<pii::SecretSerdeValue>> for WorldpayvantivMetadataObject {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- meta_data: &Option<common_utils::pii::SecretSerdeValue>,
- ) -> Result<Self, Self::Error> {
+ fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata = connector_utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
@@ -213,7 +213,7 @@ pub struct VantivAddressData {
#[serde(skip_serializing_if = "Option::is_none")]
pub zip: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
- pub email: Option<common_utils::pii::Email>,
+ pub email: Option<pii::Email>,
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<common_enums::CountryAlpha2>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -408,7 +408,7 @@ pub struct WorldpayvantivCardData {
pub card_validation_num: Option<Secret<String>>,
}
-#[derive(Debug, Clone, Serialize)]
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum WorldpayvativCardType {
#[serde(rename = "VI")]
@@ -1302,6 +1302,41 @@ pub struct PaymentResponse {
pub network_transaction_id: Option<Secret<String>>,
pub approved_amount: Option<MinorUnit>,
pub enhanced_auth_response: Option<EnhancedAuthResponse>,
+ pub account_updater: Option<AccountUpdater>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct AccountUpdater {
+ pub original_card_token_info: Option<AccountUpdaterCardTokenInfo>,
+ pub new_card_token_info: Option<AccountUpdaterCardTokenInfo>,
+ pub extended_card_response: ExtendedCardResponse,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct ExtendedCardResponse {
+ pub message: Option<String>,
+ pub code: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct AccountUpdaterCardTokenInfo {
+ pub cnp_token: Secret<String>,
+ pub exp_date: Option<Secret<String>>,
+ #[serde(rename = "type")]
+ pub card_type: Option<WorldpayvativCardType>,
+ pub bin: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct AccountUpdaterCardTokenInfoMetadata {
+ pub exp_date: Option<Secret<String>>,
+ #[serde(rename = "type")]
+ pub card_type: Option<String>,
+ pub bin: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -1877,6 +1912,30 @@ 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)?;
+
+ // 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.
+ let mandate_reference_data = match item.data.request.is_mandate_payment() {
+ true => {
+ if let Some(account_updater) = sale_response.account_updater.as_ref() {
+ account_updater
+ .new_card_token_info
+ .clone()
+ .map(MandateReference::from)
+ } else {
+ sale_response
+ .token_response
+ .clone()
+ .map(MandateReference::from)
+ }
+ }
+ false => sale_response
+ .token_response
+ .clone()
+ .map(MandateReference::from)
+ };
+
+
if connector_utils::is_payment_failure(status) {
let network_decline_code = item
.response
@@ -1894,7 +1953,10 @@ impl<F>
let network_error_message = network_decline_code
.as_ref()
.map(|_| sale_response.message.clone());
+
+
Ok(Self {
+ connector_response: Some(ConnectorResponseData::new(None, None,None, mandate_reference_data.clone())),
status,
response: Err(ErrorResponse {
code: sale_response.response.to_string(),
@@ -1916,8 +1978,13 @@ impl<F>
};
let connector_metadata = Some(report_group.encode_to_value()
.change_context(errors::ConnectorError::ResponseHandlingFailed)?);
- let mandate_reference_data = sale_response.token_response.clone().map(MandateReference::from);
- let connector_response = sale_response.fraud_result.as_ref().map(get_connector_response);
+ let additional_payment_method_connector_response = sale_response.fraud_result.as_ref().map(get_additional_payment_method_connector_response);
+ let connector_response = Some(ConnectorResponseData::new(
+ additional_payment_method_connector_response,
+ None,
+ None,
+ mandate_reference_data.clone(),
+ ));
Ok(Self {
status,
@@ -2168,6 +2235,69 @@ impl From<TokenResponse> for MandateReference {
}
}
+impl From<&AccountUpdaterCardTokenInfo> for api_models::payments::UpdatedMandateDetails {
+ fn from(token_data: &AccountUpdaterCardTokenInfo) -> Self {
+ let card_exp_month = token_data
+ .exp_date
+ .as_ref()
+ .and_then(|exp_date| exp_date.peek().as_str().get(0..2).map(|s| s.to_string()))
+ .map(Secret::new);
+
+ let card_exp_year = token_data
+ .exp_date
+ .as_ref()
+ .and_then(|exp_date| exp_date.peek().as_str().get(2..4).map(|s| s.to_string()))
+ .map(Secret::new);
+
+ Self {
+ card_network: token_data
+ .card_type
+ .clone()
+ .map(common_enums::CardNetwork::from),
+ card_isin: token_data.bin.clone(),
+ card_exp_month,
+ card_exp_year,
+ }
+ }
+}
+
+impl From<WorldpayvativCardType> for common_enums::CardNetwork {
+ fn from(card_type: WorldpayvativCardType) -> Self {
+ match card_type {
+ WorldpayvativCardType::Visa => Self::Visa,
+ WorldpayvativCardType::MasterCard => Self::Mastercard,
+ WorldpayvativCardType::AmericanExpress => Self::AmericanExpress,
+ WorldpayvativCardType::Discover => Self::Discover,
+ WorldpayvativCardType::JCB => Self::JCB,
+ WorldpayvativCardType::DinersClub => Self::DinersClub,
+ WorldpayvativCardType::UnionPay => Self::UnionPay,
+ }
+ }
+}
+
+impl From<AccountUpdaterCardTokenInfo> for MandateReference {
+ fn from(token_data: AccountUpdaterCardTokenInfo) -> Self {
+ let mandate_metadata = api_models::payments::UpdatedMandateDetails::from(&token_data);
+
+ let mandate_metadata_json = serde_json::to_value(&mandate_metadata)
+ .inspect_err(|_| {
+ logger::error!(
+ "Failed to construct Mandate Reference from the UpdatedMandateDetails"
+ )
+ })
+ .ok();
+
+ let mandate_metadata_secret_json = mandate_metadata_json.map(pii::SecretSerdeValue::new);
+
+ Self {
+ connector_mandate_id: Some(token_data.cnp_token.expose()),
+ payment_method_id: None,
+ mandate_metadata: mandate_metadata_secret_json,
+ connector_mandate_request_reference_id: None,
+ }
+ }
+}
+
impl TryFrom<RefundsResponseRouterData<RSync, VantivSyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
@@ -3980,18 +4110,18 @@ fn get_vantiv_card_data(
};
let apple_pay_network = apple_pay_data
- .payment_method
- .network
- .parse::<WorldPayVativApplePayNetwork>()
- .map_err(|_| {
- error_stack::Report::new(errors::ConnectorError::NotSupported {
- message: format!(
- "Invalid Apple Pay network '{}'. Supported networks: Visa,MasterCard,AmEx,Discover,DinersClub,JCB,UnionPay",
- apple_pay_data.payment_method.network
- ),
- connector: "worldpay_vativ"
- })
- })?;
+ .payment_method
+ .network
+ .parse::<WorldPayVativApplePayNetwork>()
+ .map_err(|_| {
+ error_stack::Report::new(errors::ConnectorError::NotSupported {
+ message: format!(
+ "Invalid Apple Pay network '{}'. Supported networks: Visa,MasterCard,AmEx,Discover,DinersClub,JCB,UnionPay",
+ apple_pay_data.payment_method.network
+ ),
+ connector: "worldpay_vativ"
+ })
+ })?;
Ok((
(Some(WorldpayvantivCardData {
@@ -4034,18 +4164,18 @@ fn get_vantiv_card_data(
})?,
};
let google_pay_network = google_pay_data
- .info
- .card_network
- .parse::<WorldPayVativGooglePayNetwork>()
- .map_err(|_| {
- error_stack::Report::new(errors::ConnectorError::NotSupported {
- message: format!(
- "Invalid Google Pay card network '{}'. Supported networks: VISA, MASTERCARD, AMEX, DISCOVER, JCB, UNIONPAY",
- google_pay_data.info.card_network
- ),
- connector: "worldpay_vativ"
- })
- })?;
+ .info
+ .card_network
+ .parse::<WorldPayVativGooglePayNetwork>()
+ .map_err(|_| {
+ error_stack::Report::new(errors::ConnectorError::NotSupported {
+ message: format!(
+ "Invalid Google Pay card network '{}'. Supported networks: VISA, MASTERCARD, AMEX, DISCOVER, JCB, UNIONPAY",
+ google_pay_data.info.card_network
+ ),
+ connector: "worldpay_vativ"
+ })
+ })?;
Ok((
(Some(WorldpayvantivCardData {
@@ -4085,6 +4215,24 @@ fn get_connector_response(payment_response: &FraudResult) -> ConnectorResponseDa
)
}
+fn get_additional_payment_method_connector_response(
+ payment_response: &FraudResult,
+) -> AdditionalPaymentMethodConnectorResponse {
+ let payment_checks = Some(serde_json::json!({
+ "avs_result": payment_response.avs_result,
+ "card_validation_result": payment_response.card_validation_result,
+ "authentication_result": payment_response.authentication_result,
+ "advanced_a_v_s_result": payment_response.advanced_a_v_s_result,
+ }));
+
+ AdditionalPaymentMethodConnectorResponse::Card {
+ authentication_data: None,
+ payment_checks,
+ card_network: None,
+ domestic_network: None,
+ }
+}
+
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename = "chargebackRetrievalResponse", rename_all = "camelCase")]
pub struct ChargebackRetrievalResponse {
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index f4e1955678..621775ea76 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -451,8 +451,8 @@ pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool {
| AttemptStatus::AuthenticationPending
| AttemptStatus::AuthenticationSuccessful
| AttemptStatus::Authorized
- | AttemptStatus::Charged
| AttemptStatus::Authorizing
+ | AttemptStatus::Charged
| AttemptStatus::CodInitiated
| AttemptStatus::Voided
| AttemptStatus::VoidedPostCharge
@@ -461,8 +461,8 @@ pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool {
| AttemptStatus::AutoRefunded
| AttemptStatus::PartialCharged
| AttemptStatus::PartialChargedAndChargeable
- | AttemptStatus::Unresolved
| AttemptStatus::Pending
+ | AttemptStatus::Unresolved
| AttemptStatus::PaymentMethodAwaited
| AttemptStatus::ConfirmationAwaited
| AttemptStatus::DeviceDataCollectionPending
diff --git a/crates/hyperswitch_domain_models/src/revenue_recovery.rs b/crates/hyperswitch_domain_models/src/revenue_recovery.rs
index feb50d2cf3..9f517c1a6b 100644
--- a/crates/hyperswitch_domain_models/src/revenue_recovery.rs
+++ b/crates/hyperswitch_domain_models/src/revenue_recovery.rs
@@ -153,7 +153,7 @@ impl From<&RevenueRecoveryInvoiceData> for api_payments::PaymentsCreateIntentReq
customer_present: Some(common_enums::PresenceOfCustomerDuringPayment::Absent),
description: None,
return_url: None,
- setup_future_usage: None,
+ setup_future_usage: Some(common_enums::FutureUsage::OffSession),
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
index 00ba26df20..3abeb68977 100644
--- a/crates/hyperswitch_domain_models/src/router_data.rs
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -13,7 +13,7 @@ use serde::{Deserialize, Serialize};
use crate::{
address::AddressDetails, network_tokenization::NetworkTokenNumber,
- payment_address::PaymentAddress, payment_method_data, payments,
+ payment_address::PaymentAddress, payment_method_data, payments, router_response_types,
};
#[cfg(feature = "v2")]
use crate::{
@@ -21,7 +21,7 @@ use crate::{
payment_attempt::{ErrorDetails, PaymentAttemptUpdate},
payment_intent::PaymentIntentUpdate,
},
- router_flow_types, router_request_types, router_response_types,
+ router_flow_types, router_request_types,
};
#[derive(Debug, Clone, Serialize)]
@@ -625,6 +625,7 @@ pub struct ConnectorResponseData {
pub additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>,
extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>,
is_overcapture_enabled: Option<primitive_wrappers::OvercaptureEnabledBool>,
+ pub mandate_reference: Option<router_response_types::MandateReference>,
}
impl ConnectorResponseData {
@@ -635,17 +636,20 @@ impl ConnectorResponseData {
additional_payment_method_data: Some(additional_payment_method_data),
extended_authorization_response_data: None,
is_overcapture_enabled: None,
+ mandate_reference: None,
}
}
pub fn new(
additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>,
is_overcapture_enabled: Option<primitive_wrappers::OvercaptureEnabledBool>,
extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>,
+ mandate_reference: Option<router_response_types::MandateReference>,
) -> Self {
Self {
additional_payment_method_data,
extended_authorization_response_data,
is_overcapture_enabled,
+ mandate_reference,
}
}
diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs
index a96373e950..201d773582 100644
--- a/crates/hyperswitch_domain_models/src/router_response_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_response_types.rs
@@ -124,7 +124,7 @@ pub struct TaxCalculationResponseData {
pub order_tax_amount: MinorUnit,
}
-#[derive(Serialize, Debug, Clone)]
+#[derive(Serialize, Debug, Clone, serde::Deserialize)]
pub struct MandateReference {
pub connector_mandate_id: Option<String>,
pub payment_method_id: Option<String>,
@@ -281,6 +281,17 @@ impl PaymentsResponseData {
None
}
}
+
+ pub fn get_mandate_reference(&self) -> Option<MandateReference> {
+ if let Self::TransactionResponse {
+ mandate_reference, ..
+ } = self
+ {
+ mandate_reference.as_ref().clone()
+ } else {
+ None
+ }
+ }
}
#[derive(Debug, Clone, Serialize)]
diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
index ac6a34110a..70e4dc3ff1 100644
--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs
@@ -300,6 +300,7 @@ impl ForeignTryFrom<payments_grpc::ConnectorResponseData> for ConnectorResponseD
additional_payment_method_data,
is_overcapture_enabled,
extended_authorization_response_data,
+ None,
))
}
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index bfc78c9f71..60e9e92212 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -9449,6 +9449,7 @@ where
mandate_reference_record
.connector_mandate_request_reference_id
.clone(),
+ None,
),
))
}
@@ -9520,6 +9521,7 @@ where
None,
mandate_reference_record.mandate_metadata.clone(),
mandate_reference_record.connector_mandate_request_reference_id.clone(),
+ None
)
));
payment_data.set_recurring_mandate_payment_data(
diff --git a/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs b/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs
index 4e4302b1d5..791af3a22d 100644
--- a/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs
+++ b/crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs
@@ -280,6 +280,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ExternalVaultP
None,
None,
None,
+ None,
),
)
}),
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index e2db966f19..9f464b6122 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -744,6 +744,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
None, // update_history
None, // mandate_metadata
None, // connector_mandate_request_reference_id
+ None,
),
),
),
@@ -781,6 +782,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
Some(common_utils::generate_id_with_len(
consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)), // connector_mandate_request_reference_id
+ None,
)),
);
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index a3c1c76751..597a88ba2a 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -418,6 +418,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
None,
None,
connector_id.get_connector_mandate_request_reference_id(),
+ None
)
))
}
@@ -456,6 +457,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
None,
None,
None,
+ None,
),
),
),
@@ -560,6 +562,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
Some(common_utils::generate_id_with_len(
consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)), // connector_mandate_request_reference_id
+ None,
),
));
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 36c775ca9d..ddf93d51c2 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -18,6 +18,9 @@ use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
use hyperswitch_domain_models::payments::{
PaymentConfirmData, PaymentIntentData, PaymentStatusData,
};
+#[cfg(feature = "v2")]
+use masking::PeekInterface;
+use router_derive;
use router_env::{instrument, logger, tracing};
use storage_impl::DataModelExt;
use tracing_futures::Instrument;
@@ -2689,8 +2692,56 @@ impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthor
let attempt_status = updated_payment_attempt.status;
+ let mandate_reference_id = response_router_data
+ .connector_response
+ .as_ref()
+ .and_then(|data| data.mandate_reference.as_ref())
+ .and_then(|mandate_ref| mandate_ref.connector_mandate_id.clone());
+
+ let updated_metadata_details = response_router_data
+ .connector_response
+ .as_ref()
+ .and_then(|data| data.mandate_reference.as_ref())
+ .and_then(|mandate_ref| mandate_ref.mandate_metadata.clone());
+
+ let updated_metadata_info = updated_metadata_details
+ .map(|data| {
+ serde_json::from_value::<api_models::payments::UpdatedMandateDetails>(
+ data.peek().clone(),
+ )
+ })
+ .transpose()
+ .inspect_err(|e| {
+ logger::error!(
+ "Failed to deserialize UpdatedMandateDetails from mandate metadata: {:?}",
+ e
+ );
+ })
+ .ok()
+ .flatten();
+
+ let mandate_data_updated = match updated_metadata_info {
+ Some(data) => Some(api_models::payments::MandateIds {
+ mandate_id: None,
+ mandate_reference_id: Some(
+ api_models::payments::MandateReferenceId::ConnectorMandateId(
+ api_models::payments::ConnectorMandateReferenceId::new(
+ mandate_reference_id,
+ None,
+ None,
+ None,
+ None,
+ Some(data),
+ ),
+ ),
+ ),
+ }),
+ None => payment_data.mandate_data,
+ };
+
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
+ payment_data.mandate_data = mandate_data_updated;
if let Some(payment_method) = &payment_data.payment_method {
match attempt_status {
@@ -3168,6 +3219,7 @@ fn update_connector_mandate_details_for_the_flow<F: Clone>(
None,
mandate_metadata,
connector_mandate_request_reference_id,
+ None,
))
}
} else {
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index f741eb48f1..6cdc93d568 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -339,7 +339,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
connector_id.get_payment_method_id(), // payment_method_id
None, // update_history
connector_id.get_mandate_metadata(), // mandate_metadata
- connector_id.get_connector_mandate_request_reference_id() // connector_mandate_request_reference_id
+ connector_id.get_connector_mandate_request_reference_id(),
+ None // connector_mandate_request_reference_id
)
))
}
diff --git a/crates/router/src/core/payments/operations/proxy_payments_intent.rs b/crates/router/src/core/payments/operations/proxy_payments_intent.rs
index ceae5d850f..58a8dcbaf7 100644
--- a/crates/router/src/core/payments/operations/proxy_payments_intent.rs
+++ b/crates/router/src/core/payments/operations/proxy_payments_intent.rs
@@ -254,6 +254,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ProxyPaymentsR
None,
None,
None,
+ None,
),
),
),
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 100d0e12d2..9d43ba083b 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -382,6 +382,7 @@ where
None,
mandate_metadata,
connector_mandate_request_reference_id,
+ None,
))
}
} else {
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index bdc0f56ad6..95f6722a7e 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -6434,6 +6434,7 @@ impl ForeignFrom<DieselConnectorMandateReferenceId> for ConnectorMandateReferenc
None,
value.mandate_metadata,
value.connector_mandate_request_reference_id,
+ None,
)
}
}
diff --git a/crates/router/src/core/revenue_recovery/types.rs b/crates/router/src/core/revenue_recovery/types.rs
index 5e6713982a..be50394754 100644
--- a/crates/router/src/core/revenue_recovery/types.rs
+++ b/crates/router/src/core/revenue_recovery/types.rs
@@ -9,7 +9,7 @@ use api_models::{
};
use common_utils::{
self,
- ext_traits::{OptionExt, ValueExt},
+ ext_traits::{AsyncExt, OptionExt, ValueExt},
id_type,
};
use diesel_models::{
@@ -430,20 +430,59 @@ impl Action {
);
// handle proxy api's response
match response {
- Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() {
- RevenueRecoveryPaymentsAttemptStatus::Succeeded => {
- let recovery_payment_attempt =
+ Ok(payment_data) => {
+ let account_updater_action = storage::revenue_recovery_redis_operation::RedisTokenManager::handle_account_updater_token_update(
+ state,
+ &connector_customer_id,
+ scheduled_token,
+ payment_data.mandate_data.clone(),
+ &payment_data.payment_attempt.id
+ ).await
+ .inspect_err(|e| {
+ logger::error!(
+ "Failed to handle get valid action: {:?}",
+ e
+ );
+ })
+ .ok();
+
+ let _account_updater_result = account_updater_action
+ .async_map(|action| {
+ let customer_id = connector_customer_id.clone();
+ let payment_attempt_id = payment_data.payment_attempt.id.clone();
+ async move {
+ action
+ .handle_account_updater_action(
+ state,
+ customer_id.as_str(),
+ scheduled_token,
+ &payment_attempt_id,
+ )
+ .await
+ }
+ })
+ .await
+ .transpose()
+ .inspect_err(|e| {
+ logger::error!("Failed to handle account updater action: {:?}", e);
+ })
+ .ok();
+
+ match payment_data.payment_attempt.status.foreign_into() {
+ RevenueRecoveryPaymentsAttemptStatus::Succeeded => {
+ 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,
- );
+ let recovery_payment_tuple =
+ recovery_incoming_flow::RecoveryPaymentTuple::new(
+ &recovery_payment_intent,
+ &recovery_payment_attempt,
+ );
- // publish events to kafka
- if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
+ // publish events to kafka
+ if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(process.retry_count+1)
@@ -455,8 +494,8 @@ impl Action {
);
};
- // 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(
+ // 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,
@@ -465,30 +504,30 @@ impl Action {
)
.await;
- // unlocking the token
- let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
+ // unlocking the token
+ let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
- let event_status = common_enums::EventType::PaymentSucceeded;
-
- let payments_response = payment_data
- .clone()
- .generate_response(
- state,
- None,
- None,
- None,
- &merchant_context,
- profile,
- None,
- )
- .change_context(errors::RecoveryError::PaymentsResponseGenerationFailed)
- .attach_printable("Failed while generating response for payment")?;
-
- RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status(
+ let event_status = common_enums::EventType::PaymentSucceeded;
+
+ let payments_response = payment_data
+ .clone()
+ .generate_response(
+ state,
+ None,
+ None,
+ None,
+ &merchant_context,
+ 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,
@@ -500,23 +539,24 @@ impl Action {
)
.await?;
- Ok(Self::SuccessfulPayment(
- payment_data.payment_attempt.clone(),
- ))
- }
- RevenueRecoveryPaymentsAttemptStatus::Failed => {
- let recovery_payment_attempt =
+ Ok(Self::SuccessfulPayment(
+ payment_data.payment_attempt.clone(),
+ ))
+ }
+ RevenueRecoveryPaymentsAttemptStatus::Failed => {
+ 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,
- );
+ let recovery_payment_tuple =
+ recovery_incoming_flow::RecoveryPaymentTuple::new(
+ &recovery_payment_intent,
+ &recovery_payment_attempt,
+ );
- // publish events to kafka
- if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
+ // publish events to kafka
+ if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(process.retry_count+1)
@@ -528,18 +568,20 @@ impl Action {
);
};
- let error_code = payment_data
- .payment_attempt
- .clone()
- .error
- .map(|error| error.code);
+ let error_code = payment_data
+ .payment_attempt
+ .clone()
+ .error
+ .map(|error| error.code);
- let is_hard_decline =
- revenue_recovery::check_hard_decline(state, &payment_data.payment_attempt)
- .await
- .ok();
+ let is_hard_decline = revenue_recovery::check_hard_decline(
+ state,
+ &payment_data.payment_attempt,
+ )
+ .await
+ .ok();
- let _update_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
+ let _update_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&error_code,
@@ -551,37 +593,38 @@ impl Action {
)
.await;
- // unlocking the token
- let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
+ // unlocking the token
+ let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
- // Reopen calculate workflow on payment failure
- Box::pin(reopen_calculate_workflow_on_payment_failure(
- state,
- process,
- profile,
- merchant_context,
- payment_intent,
- revenue_recovery_payment_data,
- latest_attempt_id,
- ))
- .await?;
-
- // Return terminal failure to finish the current execute workflow
- Ok(Self::TerminalFailure(payment_data.payment_attempt.clone()))
- }
-
- RevenueRecoveryPaymentsAttemptStatus::Processing => {
- Ok(Self::SyncPayment(payment_data.payment_attempt.clone()))
- }
- RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => {
- logger::info!(?action, "Invalid Payment Status For PCR Payment");
- Ok(Self::ManualReviewAction)
+ // Reopen calculate workflow on payment failure
+ Box::pin(reopen_calculate_workflow_on_payment_failure(
+ state,
+ process,
+ profile,
+ merchant_context,
+ payment_intent,
+ revenue_recovery_payment_data,
+ latest_attempt_id,
+ ))
+ .await?;
+
+ // Return terminal failure to finish the current execute workflow
+ Ok(Self::TerminalFailure(payment_data.payment_attempt.clone()))
+ }
+
+ RevenueRecoveryPaymentsAttemptStatus::Processing => {
+ Ok(Self::SyncPayment(payment_data.payment_attempt.clone()))
+ }
+ RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => {
+ logger::info!(?action, "Invalid Payment Status For PCR Payment");
+ Ok(Self::ManualReviewAction)
+ }
}
- },
+ }
Err(err) =>
// check for an active attempt being constructed or not
{
diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rs
index ed49f6f0a4..84af731814 100644
--- a/crates/router/src/core/webhooks/recovery_incoming.rs
+++ b/crates/router/src/core/webhooks/recovery_incoming.rs
@@ -957,6 +957,7 @@ impl RevenueRecoveryAttempt {
last_four_digits: revenue_recovery_attempt_data.card_info.last4.clone(),
card_network: revenue_recovery_attempt_data.card_info.card_network.clone(),
card_type: revenue_recovery_attempt_data.card_info.card_type.clone(),
+ card_isin: revenue_recovery_attempt_data.card_info.card_isin.clone(),
},
is_active: Some(true), // Tokens created from recovery attempts are active by default
account_update_history: None, // No prior account update history exists for freshly ingested tokens
diff --git a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs b/crates/router/src/types/storage/revenue_recovery_redis_operation.rs
index 70aa960d0a..abca6790a9 100644
--- a/crates/router/src/types/storage/revenue_recovery_redis_operation.rs
+++ b/crates/router/src/types/storage/revenue_recovery_redis_operation.rs
@@ -4,7 +4,7 @@ use api_models::revenue_recovery_data_backfill::{self, AccountUpdateHistoryRecor
use common_enums::enums::CardNetwork;
use common_utils::{date_time, errors::CustomResult, id_type};
use error_stack::ResultExt;
-use masking::{ExposeInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use redis_interface::{DelReply, SetnxReply};
use router_env::{instrument, logger, tracing};
use serde::{Deserialize, Serialize};
@@ -26,6 +26,7 @@ pub struct PaymentProcessorTokenDetails {
pub last_four_digits: Option<String>,
pub card_network: Option<CardNetwork>,
pub card_type: Option<String>,
+ pub card_isin: Option<String>,
}
/// Represents the status and retry history of a payment processor token
@@ -51,6 +52,28 @@ pub struct PaymentProcessorTokenStatus {
pub account_update_history: Option<Vec<AccountUpdateHistoryRecord>>,
}
+impl From<&PaymentProcessorTokenDetails> for api_models::payments::AdditionalCardInfo {
+ fn from(data: &PaymentProcessorTokenDetails) -> Self {
+ Self {
+ card_exp_month: data.expiry_month.clone(),
+ card_exp_year: data.expiry_year.clone(),
+ card_issuer: data.card_issuer.clone(),
+ card_network: data.card_network.clone(),
+ card_type: data.card_type.clone(),
+ last4: data.last_four_digits.clone(),
+ card_isin: data.card_isin.clone(),
+ card_issuing_country: None,
+ bank_code: None,
+ card_extended_bin: None,
+ card_holder_name: None,
+ payment_checks: None,
+ authentication_data: None,
+ is_regulated: None,
+ signature_network: None,
+ }
+ }
+}
+
/// Token retry availability information with detailed wait times
#[derive(Debug, Clone)]
pub struct TokenRetryInfo {
@@ -479,7 +502,6 @@ impl RedisTokenManager {
.payment_processor_token_details
.payment_processor_token
.clone();
-
let was_existing = token_map.contains_key(&token_id);
let error_code = token_data.error_code.clone();
@@ -500,6 +522,9 @@ impl RedisTokenManager {
.and_modify(|v| *v += value)
.or_insert(value);
}
+ existing_token.account_update_history = token_data.account_update_history.clone();
+ existing_token.payment_processor_token_details =
+ token_data.payment_processor_token_details.clone();
existing_token
.modified_at
@@ -519,6 +544,9 @@ impl RedisTokenManager {
existing_token.modified_at = Some(last_external_attempt_at);
existing_token.error_code = error_code;
existing_token.is_hard_decline = token_data.is_hard_decline;
+ token_data
+ .is_active
+ .map(|is_active| existing_token.is_active = Some(is_active));
});
})
.or_else(|| {
@@ -1044,7 +1072,10 @@ impl RedisTokenManager {
new_token_info: api_record.new_token_info.clone(),
})
.collect();
- existing_token.account_update_history = Some(converted_history);
+ existing_token
+ .account_update_history
+ .as_mut()
+ .map(|data| data.extend(converted_history));
}
// Update is_active if provided
@@ -1079,4 +1110,235 @@ impl RedisTokenManager {
Ok(token_data)
}
+
+ pub async fn handle_account_updater_token_update(
+ state: &SessionState,
+ customer_id: &str,
+ scheduled_token: &PaymentProcessorTokenStatus,
+ mandate_data: Option<api_models::payments::MandateIds>,
+ payment_attempt_id: &id_type::GlobalAttemptId,
+ ) -> CustomResult<AccountUpdaterAction, errors::StorageError> {
+ match mandate_data {
+ Some(data) => {
+ logger::info!(
+ customer_id = customer_id,
+ "Mandate data provided, proceeding with token update."
+ );
+
+ let old_token_id = scheduled_token
+ .payment_processor_token_details
+ .payment_processor_token
+ .clone();
+
+ let account_updater_action =
+ Self::determine_account_updater_action_based_on_old_token_and_mandate_data(
+ old_token_id.as_str(),
+ data,
+ )?;
+
+ Ok(account_updater_action)
+ }
+ None => {
+ logger::info!(
+ customer_id = customer_id,
+ "Skipping token update. Since we didn't get any updated mandate data"
+ );
+ Ok(AccountUpdaterAction::NoAction)
+ }
+ }
+ }
+
+ fn determine_account_updater_action_based_on_old_token_and_mandate_data(
+ old_token: &str,
+ mandate_data: api_models::payments::MandateIds,
+ ) -> CustomResult<AccountUpdaterAction, errors::StorageError> {
+ let new_token = mandate_data.get_connector_mandate_id();
+ let account_updater_action = match new_token {
+ Some(new_token) => {
+ logger::info!("Found token in mandate data, comparing with old token");
+ let is_token_equal = (new_token == old_token);
+
+ logger::info!(
+ "Old token and new token comparison result: {}",
+ is_token_equal
+ );
+
+ if is_token_equal {
+ logger::info!("Old token and new token are equal. Checking for expiry update");
+ match mandate_data.get_updated_mandate_details_of_connector_mandate_id() {
+ Some(metadata) => {
+ logger::info!("Mandate metadata found for expiry update.");
+ AccountUpdaterAction::ExpiryUpdate(metadata)
+ }
+ None => {
+ logger::info!("No mandate metadata found for expiry update.");
+ AccountUpdaterAction::ExistingToken
+ }
+ }
+ } else {
+ logger::info!("Old token and new token are not equal.");
+ match mandate_data.get_updated_mandate_details_of_connector_mandate_id() {
+ Some(metadata) => {
+ logger::info!("Mandate metadata found for token update.");
+ AccountUpdaterAction::TokenUpdate(new_token, metadata)
+ }
+ None => {
+ logger::warn!("No mandate metadata found for token update. No further action is taken");
+ AccountUpdaterAction::NoAction
+ }
+ }
+ }
+ }
+ None => {
+ logger::warn!("No new token found in mandate data while comparing with old token.");
+ AccountUpdaterAction::NoAction
+ }
+ };
+
+ Ok(account_updater_action)
+ }
+}
+
+pub enum AccountUpdaterAction {
+ TokenUpdate(String, api_models::payments::UpdatedMandateDetails),
+ ExpiryUpdate(api_models::payments::UpdatedMandateDetails),
+ ExistingToken,
+ NoAction,
+}
+
+impl AccountUpdaterAction {
+ pub async fn handle_account_updater_action(
+ &self,
+ state: &SessionState,
+ customer_id: &str,
+ scheduled_token: &PaymentProcessorTokenStatus,
+ attempt_id: &id_type::GlobalAttemptId,
+ ) -> CustomResult<(), errors::StorageError> {
+ match self {
+ Self::TokenUpdate(new_token, updated_mandate_details) => {
+ logger::info!("Handling TokenUpdate action with new token");
+ // Implement token update logic here using additional_card_info if needed
+
+ let mut updated_token = scheduled_token.clone();
+ updated_token.is_active = Some(false);
+ updated_token.modified_at = Some(PrimitiveDateTime::new(
+ OffsetDateTime::now_utc().date(),
+ OffsetDateTime::now_utc().time(),
+ ));
+
+ RedisTokenManager::upsert_payment_processor_token(
+ state,
+ customer_id,
+ updated_token,
+ )
+ .await?;
+
+ logger::info!("Successfully deactivated old token.");
+
+ let new_token = PaymentProcessorTokenStatus {
+ payment_processor_token_details: PaymentProcessorTokenDetails {
+ payment_processor_token: new_token.to_owned(),
+ expiry_month: updated_mandate_details.card_exp_month.clone(),
+ expiry_year: updated_mandate_details.card_exp_year.clone(),
+ card_issuer: None,
+ last_four_digits: None,
+ card_type: None,
+ card_network: updated_mandate_details.card_network.clone(),
+ card_isin: updated_mandate_details.card_isin.clone(),
+ },
+ inserted_by_attempt_id: attempt_id.to_owned(),
+ error_code: None,
+ daily_retry_history: HashMap::new(),
+ scheduled_at: None,
+ is_hard_decline: Some(false),
+ modified_at: Some(PrimitiveDateTime::new(
+ OffsetDateTime::now_utc().date(),
+ OffsetDateTime::now_utc().time(),
+ )),
+ is_active: Some(true),
+ account_update_history: Some(vec![AccountUpdateHistoryRecord {
+ old_token: scheduled_token
+ .payment_processor_token_details
+ .payment_processor_token
+ .clone(),
+ new_token: new_token.to_owned(),
+ updated_at: PrimitiveDateTime::new(
+ OffsetDateTime::now_utc().date(),
+ OffsetDateTime::now_utc().time(),
+ ),
+ old_token_info: Some(api_models::payments::AdditionalCardInfo::from(
+ &scheduled_token.payment_processor_token_details,
+ )),
+ new_token_info: Some(api_models::payments::AdditionalCardInfo::from(
+ updated_mandate_details,
+ )),
+ }]),
+ };
+
+ RedisTokenManager::upsert_payment_processor_token(state, customer_id, new_token)
+ .await?;
+ logger::info!("Successfully updated token with new token information.")
+ }
+ Self::ExpiryUpdate(updated_mandate_details) => {
+ logger::info!("Handling ExpiryUpdate action");
+ // Implement expiry update logic here using additional_card_info
+
+ let mut updated_token = scheduled_token.clone();
+ updated_token.payment_processor_token_details.expiry_month =
+ updated_mandate_details.card_exp_month.clone();
+ updated_token.payment_processor_token_details.expiry_year =
+ updated_mandate_details.card_exp_year.clone();
+ updated_token.payment_processor_token_details.card_network =
+ updated_mandate_details.card_network.clone();
+ updated_token.payment_processor_token_details.card_isin =
+ updated_mandate_details.card_isin.clone();
+ updated_token.modified_at = Some(PrimitiveDateTime::new(
+ OffsetDateTime::now_utc().date(),
+ OffsetDateTime::now_utc().time(),
+ ));
+ updated_token
+ .account_update_history
+ .get_or_insert_with(Vec::new)
+ .push(AccountUpdateHistoryRecord {
+ old_token: scheduled_token
+ .payment_processor_token_details
+ .payment_processor_token
+ .clone(),
+ new_token: updated_token
+ .payment_processor_token_details
+ .payment_processor_token
+ .clone(),
+ updated_at: PrimitiveDateTime::new(
+ OffsetDateTime::now_utc().date(),
+ OffsetDateTime::now_utc().time(),
+ ),
+ old_token_info: Some(api_models::payments::AdditionalCardInfo::from(
+ &scheduled_token.payment_processor_token_details,
+ )),
+ new_token_info: Some(api_models::payments::AdditionalCardInfo::from(
+ &updated_token.payment_processor_token_details,
+ )),
+ });
+
+ RedisTokenManager::upsert_payment_processor_token(
+ state,
+ customer_id,
+ updated_token,
+ )
+ .await?;
+
+ logger::info!("Successfully updated token expiry information.")
+ }
+ Self::ExistingToken => {
+ logger::info!("Handling ExistingToken action - no changes needed");
+ // No action needed for existing token
+ }
+ Self::NoAction => {
+ logger::info!("No action to be taken for NoAction case");
+ // No action needed
+ }
+ };
+
+ Ok(())
+ }
}