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(modular): harden compatibility workflows for revert use cases (#12481)

Kashifdf55de90a827
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index bd5baf56da..aa444117b0 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -10523,6 +10523,24 @@ pub enum ConnectorTokenStatus {
Inactive,
}
+impl From<ConnectorMandateStatus> for ConnectorTokenStatus {
+ fn from(status: ConnectorMandateStatus) -> Self {
+ match status {
+ ConnectorMandateStatus::Active => Self::Active,
+ ConnectorMandateStatus::Inactive => Self::Inactive,
+ }
+ }
+}
+
+impl From<ConnectorTokenStatus> for ConnectorMandateStatus {
+ fn from(status: ConnectorTokenStatus) -> Self {
+ match status {
+ ConnectorTokenStatus::Active => Self::Active,
+ ConnectorTokenStatus::Inactive => Self::Inactive,
+ }
+ }
+}
+
#[derive(
Clone,
Copy,
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index e5d2454b7b..d98418d84a 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -79,6 +79,7 @@ pub struct PaymentMethod {
pub payment_method_subtype: Option<String>,
pub network_transaction_link_id: Option<String>,
pub compatibility_updated_at: Option<PrimitiveDateTime>,
+ pub auxiliary_fingerprint_id: Option<String>,
}
#[cfg(feature = "v2")]
@@ -120,8 +121,8 @@ pub struct PaymentMethod {
pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
pub network_transaction_link_id: Option<Secret<String>>,
pub compatibility_updated_at: Option<PrimitiveDateTime>,
- pub external_vault_token_data: Option<Encryption>,
pub auxiliary_fingerprint_id: Option<String>,
+ pub external_vault_token_data: Option<Encryption>,
}
impl PaymentMethod {
@@ -186,6 +187,7 @@ pub struct PaymentMethodNew {
pub network_tokenization_data: Option<Encryption>,
pub id: Option<String>,
pub compatibility_updated_at: Option<PrimitiveDateTime>,
+ pub auxiliary_fingerprint_id: Option<String>,
}
#[cfg(feature = "v2")]
@@ -331,6 +333,9 @@ pub enum PaymentMethodUpdate {
id: String,
payment_method_type_v2: Option<storage_enums::PaymentMethod>,
payment_method_subtype: Option<storage_enums::PaymentMethodType>,
+ connector_mandate_details: Option<serde_json::Value>,
+ locker_fingerprint_id: Option<String>,
+ auxiliary_fingerprint_id: Option<String>,
last_modified_by: Option<String>,
},
// Compatibility-only update used by modular backward-compat PT.
@@ -338,6 +343,7 @@ pub enum PaymentMethodUpdate {
PopulateLegacyCompatFields {
payment_method: Option<storage_enums::PaymentMethod>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
+ connector_mandate_details: Option<serde_json::Value>,
last_modified_by: Option<String>,
},
}
@@ -398,6 +404,7 @@ pub enum PaymentMethodUpdate {
PopulateLegacyCompatFields {
payment_method: Option<storage_enums::PaymentMethod>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
+ connector_mandate_details: Option<CommonMandateReference>,
last_modified_by: Option<String>,
},
}
@@ -458,6 +465,7 @@ pub struct PaymentMethodUpdateInternal {
network_transaction_link_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
+ locker_fingerprint_id: Option<String>,
network_token_requestor_reference_id: Option<String>,
payment_method: Option<storage_enums::PaymentMethod>,
connector_mandate_details: Option<serde_json::Value>,
@@ -474,7 +482,9 @@ pub struct PaymentMethodUpdateInternal {
payment_method_type_v2: Option<storage_enums::PaymentMethod>,
payment_method_subtype: Option<String>,
id: Option<String>,
+ version: Option<common_enums::ApiVersion>,
compatibility_updated_at: Option<PrimitiveDateTime>,
+ auxiliary_fingerprint_id: Option<String>,
}
#[cfg(feature = "v1")]
@@ -493,6 +503,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_transaction_link_id: None,
status: None,
locker_id: None,
+ locker_fingerprint_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
@@ -509,7 +520,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
id: None,
payment_method_type_v2: None,
payment_method_subtype: None,
+ version: None,
compatibility_updated_at: None,
+ auxiliary_fingerprint_id: None,
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
@@ -522,6 +535,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_transaction_link_id: None,
status: None,
locker_id: None,
+ locker_fingerprint_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
@@ -538,7 +552,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
id: None,
payment_method_type_v2: None,
payment_method_subtype: None,
+ version: None,
compatibility_updated_at: None,
+ auxiliary_fingerprint_id: None,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
metadata: None,
@@ -548,6 +564,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_transaction_link_id: None,
status: None,
locker_id: None,
+ locker_fingerprint_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
@@ -564,7 +581,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
id: None,
payment_method_type_v2: None,
payment_method_subtype: None,
+ version: None,
compatibility_updated_at: None,
+ auxiliary_fingerprint_id: None,
},
PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
payment_method_data,
@@ -579,6 +598,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_transaction_link_id: None,
status: None,
locker_id: None,
+ locker_fingerprint_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
@@ -595,7 +615,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
id: None,
payment_method_type_v2: None,
payment_method_subtype: None,
+ version: None,
compatibility_updated_at: None,
+ auxiliary_fingerprint_id: None,
},
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
@@ -610,6 +632,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_transaction_link_id,
status,
locker_id: None,
+ locker_fingerprint_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
@@ -626,7 +649,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
id: None,
payment_method_type_v2: None,
payment_method_subtype: None,
+ version: None,
compatibility_updated_at: None,
+ auxiliary_fingerprint_id: None,
},
PaymentMethodUpdate::NetworkTransactionLinkIdUpdate {
network_transaction_link_id,
@@ -639,6 +664,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_transaction_link_id,
status: None,
locker_id: None,
+ locker_fingerprint_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
@@ -655,7 +681,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
id: None,
payment_method_type_v2: None,
payment_method_subtype: None,
+ version: None,
compatibility_updated_at: None,
+ auxiliary_fingerprint_id: None,
},
PaymentMethodUpdate::StatusUpdate {
status,
@@ -668,6 +696,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_transaction_link_id: None,
status,
locker_id: None,
+ locker_fingerprint_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: None,
@@ -684,7 +713,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
id: None,
payment_method_type_v2: None,
payment_method_subtype: None,
+ version: None,
compatibility_updated_at: None,
+ auxiliary_fingerprint_id: None,
},
PaymentMethodUpdate::AdditionalDataUpdate {
payment_method_data,
@@ -709,6 +740,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_transaction_link_id: None,
status,
locker_id,
+ locker_fingerprint_id: None,
network_token_requestor_reference_id,
payment_method,
connector_mandate_details: connector_mandate_details
@@ -726,7 +758,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
id: None,
payment_method_type_v2: None,
payment_method_subtype: None,
+ version: None,
compatibility_updated_at: None,
+ auxiliary_fingerprint_id: None,
},
PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details,
@@ -737,6 +771,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: None,
status: None,
locker_id: None,
+ locker_fingerprint_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: connector_mandate_details.map(|v| v.expose()),
@@ -755,7 +790,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
id: None,
payment_method_type_v2: None,
payment_method_subtype: None,
+ version: None,
compatibility_updated_at: None,
+ auxiliary_fingerprint_id: None,
},
PaymentMethodUpdate::NetworkTokenDataUpdate {
network_token_requestor_reference_id,
@@ -769,6 +806,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: None,
status: None,
locker_id: None,
+ locker_fingerprint_id: None,
payment_method: None,
connector_mandate_details: None,
updated_by: None,
@@ -787,7 +825,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
id: None,
payment_method_type_v2: None,
payment_method_subtype: None,
+ version: None,
compatibility_updated_at: None,
+ auxiliary_fingerprint_id: None,
},
PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate {
connector_mandate_details,
@@ -804,6 +844,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
payment_method_data: None,
last_used_at: None,
locker_id: None,
+ locker_fingerprint_id: None,
payment_method: None,
updated_by: None,
payment_method_issuer: None,
@@ -818,7 +859,9 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
id: None,
payment_method_type_v2: None,
payment_method_subtype: None,
+ version: None,
compatibility_updated_at: None,
+ auxiliary_fingerprint_id: None,
},
PaymentMethodUpdate::PaymentMethodBatchUpdate {
connector_mandate_details,
@@ -832,6 +875,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: None,
status,
locker_id: None,
+ locker_fingerprint_id: None,
network_token_requestor_reference_id: None,
payment_method: None,
connector_mandate_details: connector_mandate_details
@@ -852,12 +896,17 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
id: None,
payment_method_type_v2: None,
payment_method_subtype: None,
+ version: None,
compatibility_updated_at: None,
+ auxiliary_fingerprint_id: None,
},
PaymentMethodUpdate::PopulateModularCompatFields {
id,
payment_method_type_v2,
payment_method_subtype,
+ connector_mandate_details,
+ locker_fingerprint_id,
+ auxiliary_fingerprint_id,
last_modified_by,
} => {
let now = common_utils::date_time::now();
@@ -870,9 +919,10 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
network_transaction_link_id: None,
status: None,
locker_id: None,
+ locker_fingerprint_id,
network_token_requestor_reference_id: None,
payment_method: None,
- connector_mandate_details: None,
+ connector_mandate_details,
updated_by: None,
payment_method_issuer: None,
payment_method_type: None,
@@ -886,39 +936,49 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
payment_method_type_v2,
payment_method_subtype: payment_method_subtype.map(|x| x.to_string()),
id: Some(id),
+ version: Some(common_enums::ApiVersion::V2),
compatibility_updated_at: Some(now),
+ auxiliary_fingerprint_id,
}
}
PaymentMethodUpdate::PopulateLegacyCompatFields {
payment_method,
payment_method_type,
+ connector_mandate_details,
last_modified_by,
- } => Self {
- metadata: None,
- payment_method_data: None,
- last_used_at: None,
- network_transaction_id: None,
- network_transaction_link_id: None,
- status: None,
- locker_id: None,
- network_token_requestor_reference_id: None,
- payment_method,
- connector_mandate_details: None,
- updated_by: None,
- payment_method_issuer: None,
- payment_method_type,
- last_modified: common_utils::date_time::now(),
- network_token_locker_id: None,
- network_token_payment_method_data: None,
- scheme: None,
- last_modified_by,
- customer_details: None,
- network_tokenization_data: None,
- payment_method_type_v2: None,
- payment_method_subtype: None,
- id: None,
- compatibility_updated_at: None,
- },
+ } => {
+ let now = common_utils::date_time::now();
+
+ Self {
+ metadata: None,
+ payment_method_data: None,
+ last_used_at: None,
+ network_transaction_id: None,
+ network_transaction_link_id: None,
+ status: None,
+ locker_id: None,
+ locker_fingerprint_id: None,
+ network_token_requestor_reference_id: None,
+ payment_method,
+ connector_mandate_details,
+ updated_by: None,
+ payment_method_issuer: None,
+ payment_method_type,
+ last_modified: now,
+ network_token_locker_id: None,
+ network_token_payment_method_data: None,
+ scheme: None,
+ last_modified_by,
+ customer_details: None,
+ network_tokenization_data: None,
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
+ id: None,
+ version: None,
+ compatibility_updated_at: Some(now),
+ auxiliary_fingerprint_id: None,
+ }
+ }
}
}
}
@@ -1154,6 +1214,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
PaymentMethodUpdate::PopulateLegacyCompatFields {
payment_method,
payment_method_type,
+ connector_mandate_details,
last_modified_by,
} => Self {
payment_method_data: None,
@@ -1165,7 +1226,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
payment_method,
payment_method_type,
payment_method_type_v2: None,
- connector_mandate_details: None,
+ connector_mandate_details,
updated_by: None,
payment_method_subtype: None,
last_modified: now,
@@ -1238,6 +1299,7 @@ impl From<&PaymentMethodNew> for PaymentMethod {
payment_method_subtype: None,
id: payment_method_new.id.clone(),
compatibility_updated_at: payment_method_new.compatibility_updated_at,
+ auxiliary_fingerprint_id: payment_method_new.auxiliary_fingerprint_id.clone(),
}
}
}
@@ -1370,15 +1432,10 @@ impl From<PaymentsMandateReference> for PaymentsTokenReference {
.0
.into_iter()
.map(|(mca_id, record)| {
- let token_status = match record.connector_mandate_status {
- Some(common_enums::ConnectorMandateStatus::Active) => {
- common_enums::ConnectorTokenStatus::Active
- }
- Some(common_enums::ConnectorMandateStatus::Inactive) => {
- common_enums::ConnectorTokenStatus::Inactive
- }
- None => common_enums::ConnectorTokenStatus::Inactive,
- };
+ let token_status = record
+ .connector_mandate_status
+ .map(common_enums::ConnectorTokenStatus::from)
+ .unwrap_or(common_enums::ConnectorTokenStatus::Inactive);
let token_record = ConnectorTokenReferenceRecord {
connector_token: record.connector_mandate_id,
@@ -1436,6 +1493,109 @@ impl std::ops::DerefMut for PayoutsMandateReference {
}
}
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
+pub struct ConnectorMandateCompatReference {
+ pub connector_mandate_id: Option<String>,
+ pub connector_token: Option<String>,
+ pub payment_method_type: Option<common_enums::PaymentMethodType>,
+ pub payment_method_subtype: Option<common_enums::PaymentMethodType>,
+ pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>,
+ pub connector_token_status: Option<common_enums::ConnectorTokenStatus>,
+ pub connector_mandate_request_reference_id: Option<String>,
+ pub connector_token_request_reference_id: Option<String>,
+ pub original_payment_authorized_amount: Option<i64>,
+ pub original_payment_authorized_currency: Option<common_enums::Currency>,
+ pub mandate_metadata: Option<pii::SecretSerdeValue>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub connector_customer_id: Option<String>,
+}
+
+impl ConnectorMandateCompatReference {
+ #[cfg(feature = "v1")]
+ fn add_v2_fields(&mut self) {
+ self.connector_token = self.connector_mandate_id.clone();
+ self.payment_method_subtype = self.payment_method_type;
+ self.connector_token_request_reference_id =
+ self.connector_mandate_request_reference_id.clone();
+ self.connector_token_status = self
+ .connector_mandate_status
+ .map(common_enums::ConnectorTokenStatus::from);
+ }
+
+ fn add_v1_fields(&mut self) {
+ self.connector_mandate_id = self.connector_token.clone();
+ self.payment_method_type = self.payment_method_subtype;
+ self.connector_mandate_request_reference_id =
+ self.connector_token_request_reference_id.clone();
+ self.connector_mandate_status = self
+ .connector_token_status
+ .map(common_enums::ConnectorMandateStatus::from);
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct ConnectorMandateCompatDetails {
+ payments:
+ HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorMandateCompatReference>,
+ payouts: Option<PayoutsMandateReference>,
+}
+
+impl TryFrom<serde_json::Value> for ConnectorMandateCompatDetails {
+ type Error = ParsingError;
+
+ fn try_from(mut connector_mandate_details: serde_json::Value) -> Result<Self, Self::Error> {
+ let payment_connector_references =
+ connector_mandate_details
+ .as_object_mut()
+ .ok_or(ParsingError::StructParseFailure(
+ "connector mandate details",
+ ))?;
+ let payouts = payment_connector_references
+ .remove("payouts")
+ .map(serde_json::from_value)
+ .transpose()
+ .map_err(|_| ParsingError::StructParseFailure("payout mandate details"))?;
+ let payments = serde_json::from_value(serde_json::Value::Object(std::mem::take(
+ payment_connector_references,
+ )))
+ .map_err(|_| ParsingError::StructParseFailure("payment mandate details"))?;
+
+ Ok(Self { payments, payouts })
+ }
+}
+
+impl ConnectorMandateCompatDetails {
+ pub fn into_value(self) -> Option<serde_json::Value> {
+ let mut connector_mandate_details_value = serde_json::to_value(self.payments).ok()?;
+
+ if let Some(payouts) = self.payouts {
+ let payouts = serde_json::to_value(payouts).ok()?;
+ connector_mandate_details_value.as_object_mut().map(
+ |payment_connector_references| {
+ payment_connector_references.insert("payouts".to_string(), payouts);
+ },
+ )?;
+ }
+
+ Some(connector_mandate_details_value)
+ }
+
+ #[cfg(feature = "v1")]
+ fn add_v2_fields(mut self) -> Self {
+ self.payments
+ .values_mut()
+ .for_each(ConnectorMandateCompatReference::add_v2_fields);
+ self
+ }
+
+ fn add_v1_fields(mut self) -> Self {
+ self.payments
+ .values_mut()
+ .for_each(ConnectorMandateCompatReference::add_v1_fields);
+ self
+ }
+}
+
#[cfg(feature = "v1")]
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, diesel::AsExpression)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
@@ -1472,6 +1632,17 @@ impl CommonMandateReference {
.transpose()
.change_context(ParsingError::StructParseFailure("payout mandate details"))?;
+ #[cfg(feature = "v2")]
+ {
+ if let Some(updated_payments) =
+ Self::parse_connector_mandate_compat_details(Some(payments.clone()))
+ .map(Self::add_v1_connector_mandate_fields)
+ .and_then(ConnectorMandateCompatDetails::into_value)
+ {
+ payments = updated_payments;
+ }
+ }
+
Ok(payments)
}
@@ -1504,15 +1675,8 @@ impl CommonMandateReference {
.0
.into_iter()
.map(|(mca_id, token_record)| {
- let connector_mandate_status = match token_record.connector_token_status
- {
- common_enums::ConnectorTokenStatus::Active => {
- common_enums::ConnectorMandateStatus::Active
- }
- common_enums::ConnectorTokenStatus::Inactive => {
- common_enums::ConnectorMandateStatus::Inactive
- }
- };
+ let connector_mandate_status =
+ token_record.connector_token_status.into();
(
mca_id,
@@ -1577,6 +1741,33 @@ impl CommonMandateReference {
}
}
+ /// Add V2-compatible connector mandate keys into an existing V1 connector mandate JSON.
+ ///
+ /// This keeps old keys in place and only augments each payment connector entry with
+ /// V2-specific keys when missing.
+ #[cfg(feature = "v1")]
+ pub fn add_v2_connector_mandate_fields(
+ connector_mandate_details: ConnectorMandateCompatDetails,
+ ) -> ConnectorMandateCompatDetails {
+ connector_mandate_details.add_v2_fields()
+ }
+
+ pub fn parse_connector_mandate_compat_details(
+ connector_mandate_details: Option<serde_json::Value>,
+ ) -> Option<ConnectorMandateCompatDetails> {
+ ConnectorMandateCompatDetails::try_from(connector_mandate_details?).ok()
+ }
+
+ /// Add V1-compatible connector mandate keys into an existing V2 connector mandate JSON.
+ ///
+ /// This keeps new keys in place and only augments each payment connector entry with
+ /// V1-specific keys when missing.
+ pub fn add_v1_connector_mandate_fields(
+ connector_mandate_details: ConnectorMandateCompatDetails,
+ ) -> ConnectorMandateCompatDetails {
+ connector_mandate_details.add_v1_fields()
+ }
+
#[cfg(feature = "v2")]
/// Insert a new payment token reference for the given connector_id
pub fn insert_payment_token_reference_record(
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index d2b788f4d5..2c844762ba 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1482,6 +1482,8 @@ diesel::table! {
#[max_length = 255]
network_transaction_link_id -> Nullable<Varchar>,
compatibility_updated_at -> Nullable<Timestamp>,
+ #[max_length = 64]
+ auxiliary_fingerprint_id -> Nullable<Varchar>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index b3d27a2066..b29464cb61 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1422,9 +1422,9 @@ diesel::table! {
#[max_length = 255]
network_transaction_link_id -> Nullable<Varchar>,
compatibility_updated_at -> Nullable<Timestamp>,
- external_vault_token_data -> Nullable<Bytea>,
#[max_length = 64]
auxiliary_fingerprint_id -> Nullable<Varchar>,
+ external_vault_token_data -> Nullable<Bytea>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs
index 3f07b8679d..df8833cfdc 100644
--- a/crates/hyperswitch_domain_models/src/payment_methods.rs
+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs
@@ -1,4 +1,4 @@
-use std::collections::HashMap;
+use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc};
#[cfg(feature = "v2")]
use api_models::payment_methods::PaymentMethodsData;
@@ -506,6 +506,7 @@ impl super::behaviour::Conversion for PaymentMethod {
payment_method_subtype: None,
id: None,
compatibility_updated_at: self.compatibility_updated_at,
+ auxiliary_fingerprint_id: None,
})
}
@@ -744,6 +745,7 @@ impl super::behaviour::Conversion for PaymentMethod {
network_tokenization_data: self.network_tokenization_data.map(|val| val.into()),
id: None,
compatibility_updated_at: self.compatibility_updated_at,
+ auxiliary_fingerprint_id: None,
})
}
}
@@ -1265,6 +1267,7 @@ pub trait PaymentMethodInterface {
key_store: &MerchantKeyStore,
payment_method: PaymentMethod,
storage_scheme: MerchantStorageScheme,
+ compat_action: Option<PaymentMethodCompatAction>,
) -> CustomResult<PaymentMethod, Self::Error>;
async fn update_payment_method(
@@ -1273,6 +1276,7 @@ pub trait PaymentMethodInterface {
payment_method: PaymentMethod,
payment_method_update: StoragePaymentMethodUpdate,
storage_scheme: MerchantStorageScheme,
+ compat_action: Option<PaymentMethodCompatAction>,
) -> CustomResult<PaymentMethod, Self::Error>;
#[cfg(feature = "v2")]
@@ -1298,6 +1302,25 @@ pub trait PaymentMethodInterface {
) -> CustomResult<PaymentMethod, Self::Error>;
}
+type PaymentMethodCompatFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
+type PaymentMethodCompatFn =
+ dyn for<'a> Fn(&'a PaymentMethod) -> PaymentMethodCompatFuture<'a> + Send + Sync;
+
+pub struct PaymentMethodCompatAction(Arc<PaymentMethodCompatFn>);
+
+impl PaymentMethodCompatAction {
+ pub fn new<F>(action: F) -> Self
+ where
+ F: for<'a> Fn(&'a PaymentMethod) -> PaymentMethodCompatFuture<'a> + Send + Sync + 'static,
+ {
+ Self(Arc::new(action))
+ }
+
+ pub async fn execute(&self, payment_method: &PaymentMethod) {
+ self.0(payment_method).await;
+ }
+}
+
#[cfg(feature = "v2")]
pub enum PaymentMethodsSessionUpdateEnum {
GeneralUpdate {
diff --git a/crates/hyperswitch_domain_models/src/vault.rs b/crates/hyperswitch_domain_models/src/vault.rs
index 076a52fb44..5908bd046c 100644
--- a/crates/hyperswitch_domain_models/src/vault.rs
+++ b/crates/hyperswitch_domain_models/src/vault.rs
@@ -289,7 +289,6 @@ impl PaymentMethodVaultingData {
}
}
- #[cfg(feature = "v2")]
pub fn to_auxiliary_fingerprint_data(&self) -> AuxiliaryFingerprintData {
match self {
Self::Card(card) => AuxiliaryFingerprintData::CardNumber(card.card_number.clone()),
diff --git a/crates/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rs
index c3bb4f62a4..f75e5880e2 100644
--- a/crates/payment_methods/src/core/migration/payment_methods.rs
+++ b/crates/payment_methods/src/core/migration/payment_methods.rs
@@ -734,6 +734,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(
compatibility_updated_at: None,
},
provider.get_account().storage_scheme,
+ None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 7fb9cf1e1e..b83fd12c4e 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -59,6 +59,7 @@ use hyperswitch_domain_models::payment_methods::PaymentMethodUpdate as DomainPay
use hyperswitch_domain_models::{
payment_method_data::BankDebitData,
payments::{payment_attempt::PaymentAttempt, PaymentIntent, VaultData},
+ platform::ProviderMerchantId,
router_data_v2::flow_common_types::VaultConnectorFlowData,
router_flow_types::ExternalVaultInsertFlow,
types::VaultRouterData,
@@ -73,6 +74,7 @@ use time::Duration;
#[cfg(feature = "v2")]
use super::payments::tokenization;
use super::{
+ configs::dimension_state,
errors::{RouterResponse, StorageErrorExt},
pm_auth,
};
@@ -80,8 +82,8 @@ use super::{
use crate::{
configs::settings,
core::{
- configs::dimension_state, payment_methods::transformers as pm_transforms,
- payment_methods::utils as payment_method_utils, tokenization as tokenization_core,
+ payment_methods::{transformers as pm_transforms, utils as payment_method_utils},
+ tokenization as tokenization_core,
},
headers,
routes::{self, payment_methods as pm_routes},
@@ -120,6 +122,8 @@ const PAYMENT_METHOD_MODULAR_FORWARD_COMPAT_TAG: &str = "PM_MOD_FORWARD_COMPAT";
const PAYMENT_METHOD_MODULAR_BACKWARD_COMPAT_TASK: &str = "PM_MOD_BACK_COMPAT";
#[cfg(feature = "v2")]
const PAYMENT_METHOD_MODULAR_BACKWARD_COMPAT_TAG: &str = "PM_MOD_BACK_COMPAT";
+const PAYMENT_METHOD_MODULAR_COMPAT_PROCESS_TRACKER_ID_MAX_LENGTH: usize = 126;
+const PAYMENT_METHOD_MODULAR_COMPAT_PROCESS_TRACKER_ID_SUFFIX_LENGTH: usize = 8;
#[cfg(feature = "v2")]
const PAYMENT_METHOD_REDACTED_FINGERPRINT_ID: &str = "FINGERPRINT_ID_REDACTED";
@@ -476,6 +480,103 @@ fn generate_task_id_for_payment_method_status_update_workflow(
format!("{runner}_{task}_{key_id}")
}
+fn generate_task_id_for_payment_method_modular_compat_workflow(
+ key_id: &str,
+ runner: storage::ProcessTrackerRunner,
+ task: &str,
+) -> String {
+ let suffix = common_utils::generate_id_with_len(
+ PAYMENT_METHOD_MODULAR_COMPAT_PROCESS_TRACKER_ID_SUFFIX_LENGTH,
+ );
+ let prefix = format!("{runner}_{task}_");
+ let key_id_len = PAYMENT_METHOD_MODULAR_COMPAT_PROCESS_TRACKER_ID_MAX_LENGTH
+ .saturating_sub(prefix.len() + suffix.len() + 1);
+ let key_id = &key_id[..key_id.len().min(key_id_len)];
+ format!("{prefix}{key_id}_{suffix}")
+}
+
+fn payment_method_compat_modifier(payment_method: &domain::PaymentMethod) -> Option<String> {
+ payment_method
+ .last_modified_by
+ .as_ref()
+ .or(payment_method.created_by.as_ref())
+ .map(ToString::to_string)
+}
+
+#[cfg(feature = "v1")]
+pub async fn payment_method_modular_forward_compat_action(
+ state: &SessionState,
+ merchant_id: &id_type::MerchantId,
+ customer_id: Option<&id_type::CustomerId>,
+) -> Option<domain::PaymentMethodCompatAction> {
+ let dimensions = dimension_state::Dimensions::new()
+ .with_provider_merchant_id(ProviderMerchantId::new(merchant_id.clone()));
+ let should_schedule_modular_forward_compat =
+ utils::get_should_schedule_modular_forward_compat(state, &dimensions, customer_id).await;
+
+ should_schedule_modular_forward_compat.then(|| {
+ let state = state.clone();
+ domain::PaymentMethodCompatAction::new(move |payment_method| {
+ let state = state.clone();
+ Box::pin(async move {
+ let res = add_payment_method_modular_forward_compat_task(
+ &*state.store,
+ payment_method,
+ &payment_method.merchant_id,
+ state.conf.application_source,
+ payment_method_compat_modifier(payment_method),
+ )
+ .await;
+
+ if let Err(err) = res {
+ logger::error!(
+ ?err,
+ payment_method_id=%payment_method.get_id(),
+ merchant_id=%payment_method.merchant_id.get_string_repr(),
+ "Failed to schedule modular forward compatibility PT after payment method DB write"
+ );
+ }
+ })
+ })
+ })
+}
+
+#[cfg(feature = "v2")]
+pub fn payment_method_modular_backward_compat_action(
+ state: &SessionState,
+) -> domain::PaymentMethodCompatAction {
+ let state = state.clone();
+ domain::PaymentMethodCompatAction::new(move |payment_method| {
+ let state = state.clone();
+ Box::pin(async move {
+ backward_compat::trigger_payment_method_modular_backward_compat(
+ &state,
+ payment_method,
+ payment_method_compat_modifier(payment_method),
+ )
+ .await;
+ })
+ })
+}
+
+#[cfg(feature = "v1")]
+pub async fn payment_method_modular_compat_action(
+ state: &SessionState,
+ merchant_id: &id_type::MerchantId,
+ customer_id: Option<&id_type::CustomerId>,
+) -> Option<domain::PaymentMethodCompatAction> {
+ payment_method_modular_forward_compat_action(state, merchant_id, customer_id).await
+}
+
+#[cfg(feature = "v2")]
+pub async fn payment_method_modular_compat_action(
+ state: &SessionState,
+ _merchant_id: &id_type::MerchantId,
+ _customer_id: Option<&id_type::GlobalCustomerId>,
+) -> Option<domain::PaymentMethodCompatAction> {
+ Some(payment_method_modular_backward_compat_action(state))
+}
+
#[cfg(feature = "v1")]
pub async fn add_payment_method_status_update_task(
db: &dyn StorageInterface,
@@ -543,20 +644,18 @@ pub async fn add_payment_method_modular_forward_compat_task(
payment_method: &domain::PaymentMethod,
merchant_id: &id_type::MerchantId,
application_source: common_enums::ApplicationSource,
- initiator: Option<&hyperswitch_domain_models::platform::Initiator>,
+ last_modified_by: Option<String>,
) -> Result<(), ProcessTrackerError> {
let tracking_data = storage::PaymentMethodModularCompatTrackingData {
payment_method_id: payment_method.payment_method_id.clone(),
merchant_id: merchant_id.to_owned(),
- last_modified_by: initiator
- .and_then(|initiator| initiator.to_created_by())
- .map(|last_modified_by| last_modified_by.to_string()),
+ last_modified_by,
};
let runner = storage::ProcessTrackerRunner::PaymentMethodModularForwardCompatWorkflow;
let task = PAYMENT_METHOD_MODULAR_FORWARD_COMPAT_TASK;
let tag = [PAYMENT_METHOD_MODULAR_FORWARD_COMPAT_TAG];
- let process_tracker_id = generate_task_id_for_payment_method_status_update_workflow(
+ let process_tracker_id = generate_task_id_for_payment_method_modular_compat_workflow(
payment_method.payment_method_id.as_str(),
runner,
task,
@@ -597,22 +696,20 @@ pub async fn add_payment_method_modular_backward_compat_task(
payment_method: &domain::PaymentMethod,
merchant_id: &id_type::MerchantId,
application_source: common_enums::ApplicationSource,
- initiator: Option<&hyperswitch_domain_models::platform::Initiator>,
+ last_modified_by: Option<String>,
) -> Result<(), ProcessTrackerError> {
let payment_method_id = payment_method.get_id().get_string_repr().to_owned();
let tracking_data = storage::PaymentMethodModularCompatTrackingData {
payment_method_id: payment_method_id.clone(),
merchant_id: merchant_id.to_owned(),
- last_modified_by: initiator
- .and_then(|initiator| initiator.to_created_by())
- .map(|last_modified_by| last_modified_by.to_string()),
+ last_modified_by,
};
let runner = storage::ProcessTrackerRunner::PaymentMethodModularBackwardCompatWorkflow;
let task = PAYMENT_METHOD_MODULAR_BACKWARD_COMPAT_TASK;
let tag = [PAYMENT_METHOD_MODULAR_BACKWARD_COMPAT_TAG];
- let process_tracker_id = generate_task_id_for_payment_method_status_update_workflow(
+ let process_tracker_id = generate_task_id_for_payment_method_modular_compat_workflow(
&payment_method_id,
runner,
task,
@@ -2207,34 +2304,19 @@ impl LockerOperations for LegacyLocker {
Ok((None, None))
}
Some(pm_transforms::DataDuplicationCheck::MetaDataChanged) => {
- // delete existing record and add newone with updated metadata but same vault_id
-
- self.delete_payment_method_from_locker(
- state,
- platform,
- domain::VaultId::generate(legacy_locker_res.card_reference.clone()),
- &customer_id,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to delete payment method from legacy locker")?;
-
- let legacy_locker_res = add_payment_method_to_legacy_locker(
+ let add_vault_response = update_metadata_changed_payment_method_in_legacy_locker(
state,
platform,
vault_request_data,
existing_locker_id,
&customer_id,
+ legacy_locker_res.card_reference,
)
.await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to add payment method to legacy locker")?;
+ .attach_printable(
+ "Failed to update metadata-changed payment method in legacy locker",
+ )?;
- let add_vault_response = pm_types::AddVaultResponse {
- entity_id: None,
- vault_id: domain::VaultId::generate(legacy_locker_res.card_reference),
- fingerprint_id: None,
- };
logger::info!("Updating only payment method metadata in legacy locker");
Ok((Some(vault_request_data.clone()), Some(add_vault_response)))
}
@@ -2242,6 +2324,45 @@ impl LockerOperations for LegacyLocker {
}
}
}
+
+#[cfg(feature = "v2")]
+pub async fn update_metadata_changed_payment_method_in_legacy_locker(
+ state: &SessionState,
+ platform: &domain::Platform,
+ vault_request_data: &domain::PaymentMethodVaultingData,
+ existing_vault_id: Option<domain::VaultId>,
+ customer_id: &id_type::GlobalCustomerId,
+ metadata_changed_card_reference: String,
+) -> RouterResult<pm_types::AddVaultResponse> {
+ LegacyLocker
+ .delete_payment_method_from_locker(
+ state,
+ platform,
+ domain::VaultId::generate(metadata_changed_card_reference),
+ customer_id,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to delete payment method from legacy locker")?;
+
+ let legacy_locker_res = add_payment_method_to_legacy_locker(
+ state,
+ platform,
+ vault_request_data,
+ existing_vault_id,
+ customer_id,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method to legacy locker")?;
+
+ Ok(pm_types::AddVaultResponse {
+ entity_id: Some(customer_id.get_string_repr().to_owned()),
+ vault_id: domain::VaultId::generate(legacy_locker_res.card_reference),
+ fingerprint_id: None,
+ })
+}
+
#[cfg(feature = "v2")]
impl LockerType {
pub fn from_micro_services_config(
@@ -2339,7 +2460,7 @@ pub async fn create_payment_method_bank_redirect_core(
}
None => {
logger::debug!("Payment method is new, creating a new payment method record");
- create_payment_method_for_confirm(
+ let payment_method = create_payment_method_for_confirm(
state,
customer_id,
payment_method_id,
@@ -2356,7 +2477,9 @@ pub async fn create_payment_method_bank_redirect_core(
platform.get_initiator(),
enums::PaymentMethodStatus::New,
)
- .await?
+ .await?;
+
+ payment_method
}
};
@@ -2642,6 +2765,7 @@ async fn execute_payment_method_create(
payment_method,
pm_update,
platform.get_provider().get_account().storage_scheme,
+ Some(payment_method_modular_backward_compat_action(state)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -2678,15 +2802,6 @@ async fn execute_payment_method_create(
None,
)?;
- Box::pin(
- backward_compat::trigger_payment_method_modular_backward_compat_best_effort(
- state,
- &payment_method,
- platform,
- ),
- )
- .await;
-
Ok((resp, payment_method))
}
Err(e) => {
@@ -2703,6 +2818,8 @@ async fn execute_payment_method_create(
payment_method,
pm_update,
platform.get_provider().get_account().storage_scheme,
+ // Inactivation on failed PM setup should not enqueue compatibility work.
+ None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -2931,6 +3048,7 @@ pub async fn create_payment_method_wallet_core(
existing_pm,
pm_update,
platform.get_provider().get_account().storage_scheme,
+ Some(payment_method_modular_backward_compat_action(state)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3978,6 +4096,7 @@ pub async fn create_payment_method_for_intent(
compatibility_updated_at: None,
},
storage_scheme,
+ Some(payment_method_modular_backward_compat_action(state)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -4136,6 +4255,7 @@ pub async fn create_payment_method_for_confirm(
compatibility_updated_at: None,
},
storage_scheme,
+ Some(payment_method_modular_backward_compat_action(state)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -5765,7 +5885,14 @@ pub async fn update_payment_method_status_internal(
};
let updated_pm = db
- .update_payment_method(key_store, payment_method.clone(), pm_update, storage_scheme)
+ .update_payment_method(
+ key_store,
+ payment_method.clone(),
+ pm_update,
+ storage_scheme,
+ // This internal PM update path is not part of modular compatibility scheduling.
+ None,
+ )
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
@@ -5961,6 +6088,8 @@ pub async fn delete_payment_method_by_record(
payment_method.clone(),
pm_update,
platform.get_provider().get_account().storage_scheme,
+ // Redaction updates should not trigger PM modular compat scheduling.
+ None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -7307,6 +7436,7 @@ impl<'a> pm_types::PaymentMethodUpdateHandler<'a> {
self.payment_method.clone(),
pm_update,
self.platform.get_provider().get_account().storage_scheme,
+ Some(payment_method_modular_backward_compat_action(self.state)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payment_methods/backward_compat.rs b/crates/router/src/core/payment_methods/backward_compat.rs
index 8410c86191..4821629239 100644
--- a/crates/router/src/core/payment_methods/backward_compat.rs
+++ b/crates/router/src/core/payment_methods/backward_compat.rs
@@ -1,5 +1,6 @@
use common_utils::{ext_traits::StringExt, id_type};
use error_stack::ResultExt;
+use hyperswitch_domain_models::platform::ProviderMerchantId;
use super::{add_payment_method_modular_backward_compat_task, utils};
use crate::{
@@ -13,14 +14,12 @@ async fn trigger_payment_method_modular_backward_compat_inline(
state: &SessionState,
payment_method: &domain::PaymentMethod,
merchant_id: &id_type::MerchantId,
- initiator: Option<&hyperswitch_domain_models::platform::Initiator>,
+ last_modified_by: Option<String>,
) -> Result<(), ProcessTrackerError> {
let tracking_data = storage::PaymentMethodModularCompatTrackingData {
payment_method_id: payment_method.get_id().get_string_repr().to_owned(),
merchant_id: merchant_id.to_owned(),
- last_modified_by: initiator
- .and_then(|initiator| initiator.to_created_by())
- .map(|last_modified_by| last_modified_by.to_string()),
+ last_modified_by,
};
Box::pin(
@@ -37,14 +36,14 @@ async fn schedule_payment_method_modular_backward_compat_task_best_effort(
state: &SessionState,
payment_method: &domain::PaymentMethod,
merchant_id: &id_type::MerchantId,
- initiator: Option<&hyperswitch_domain_models::platform::Initiator>,
+ last_modified_by: Option<String>,
) {
let res = add_payment_method_modular_backward_compat_task(
&*state.store,
payment_method,
merchant_id,
state.conf.application_source,
- initiator,
+ last_modified_by,
)
.await
.change_context(router_errors::ApiErrorResponse::InternalServerError)
@@ -68,14 +67,14 @@ async fn schedule_payment_method_modular_backward_compat_task_best_effort(
}
}
-pub(super) async fn trigger_payment_method_modular_backward_compat_best_effort(
+pub(super) async fn trigger_payment_method_modular_backward_compat(
state: &SessionState,
payment_method: &domain::PaymentMethod,
- platform: &domain::Platform,
+ last_modified_by: Option<String>,
) {
- let merchant_id = platform.get_provider().get_account().get_id().to_owned();
+ let merchant_id = &payment_method.merchant_id;
let dimensions = dimension_state::Dimensions::new()
- .with_provider_merchant_id(platform.get_provider().get_provider_merchant_id());
+ .with_provider_merchant_id(ProviderMerchantId::new(merchant_id.clone()));
let should_trigger_backwards_compatibility_inline =
utils::get_should_trigger_backwards_compatibility_inline(state, &dimensions, None).await;
@@ -85,8 +84,8 @@ pub(super) async fn trigger_payment_method_modular_backward_compat_best_effort(
Box::pin(trigger_payment_method_modular_backward_compat_inline(
state,
payment_method,
- &merchant_id,
- platform.get_initiator(),
+ merchant_id,
+ last_modified_by.clone(),
)),
)
.await;
@@ -117,8 +116,8 @@ pub(super) async fn trigger_payment_method_modular_backward_compat_best_effort(
schedule_payment_method_modular_backward_compat_task_best_effort(
state,
payment_method,
- &merchant_id,
- platform.get_initiator(),
+ merchant_id,
+ last_modified_by,
)
.await;
}
@@ -131,8 +130,8 @@ pub(super) async fn trigger_payment_method_modular_backward_compat_best_effort(
schedule_payment_method_modular_backward_compat_task_best_effort(
state,
payment_method,
- &merchant_id,
- platform.get_initiator(),
+ merchant_id,
+ last_modified_by,
)
.await;
} else {
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 4096de6b6e..24a18a2129 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -164,6 +164,13 @@ impl PaymentMethodsController for PmCards<'_> {
let current_time = common_utils::date_time::now();
+ let compat_action = super::payment_method_modular_forward_compat_action(
+ self.state,
+ merchant_id,
+ Some(customer_id),
+ )
+ .await;
+
let response = db
.insert_payment_method(
self.provider.get_key_store(),
@@ -214,50 +221,12 @@ impl PaymentMethodsController for PmCards<'_> {
compatibility_updated_at: None,
},
self.provider.get_account().storage_scheme,
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
- let should_schedule_modular_forward_compat =
- payment_method_utils::get_should_schedule_modular_forward_compat(
- self.state,
- &dimension_state::Dimensions::new()
- .with_provider_merchant_id(self.provider.get_provider_merchant_id()),
- Some(customer_id),
- )
- .await;
-
- if should_schedule_modular_forward_compat {
- let res = super::add_payment_method_modular_forward_compat_task(
- &*self.state.store,
- &response,
- merchant_id,
- self.state.conf.application_source,
- initiator,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to add payment method modular compatibility task in process tracker",
- );
-
- if let Err(err) = res {
- logger::error!(
- ?err,
- payment_method_id=%response.payment_method_id,
- merchant_id=%merchant_id.get_string_repr(),
- "Failed to schedule modular forward compatibility PT; continuing payment method create flow"
- );
- }
- } else {
- logger::debug!(
- payment_method_id=%response.payment_method_id,
- merchant_id=%merchant_id.get_string_repr(),
- "Skipping modular forward compatibility PT scheduling by config"
- );
- }
-
if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {
let _ = self
.set_default_payment_method(
@@ -502,11 +471,19 @@ impl PaymentMethodsController for PmCards<'_> {
"Failed to fetch payment method for existing pm_id: {pm_id:?} in db",
))?;
+ let compat_action = super::payment_method_modular_forward_compat_action(
+ self.state,
+ &existing_pm.merchant_id,
+ existing_pm.customer_id.as_ref(),
+ )
+ .await;
+
db.update_payment_method(
key_store,
existing_pm,
pm_update,
self.provider.get_account().storage_scheme,
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -1397,6 +1374,14 @@ impl PaymentMethodsController for PmCards<'_> {
hyperswitch_domain_models::vault::PaymentMethodVaultingData,
errors::VaultError,
> {
+ let should_trigger_fingerprint_migration =
+ payment_method_utils::get_should_trigger_fingerprint_migration(
+ self.state,
+ Some(customer_id),
+ self.provider.get_provider_merchant_id(),
+ )
+ .await;
+
let payload = if !is_v2_pm {
pm_types::VaultRetrieveRequest {
entity_id: hyperswitch_domain_models::vault::V1VaultEntityId::new(
@@ -1409,13 +1394,12 @@ impl PaymentMethodsController for PmCards<'_> {
.change_context(errors::VaultError::RequestEncodingFailed)
.attach_printable("Failed to encode VaultRetrieveRequest")?
} else {
- pm_types::GenericVaultRetrieveRequest {
- entity_id: customer_id.clone(),
- vault_id: vault_id.clone(),
- }
- .encode_to_vec()
- .change_context(errors::VaultError::RequestEncodingFailed)
- .attach_printable("Failed to encode GenericVaultRetrieveRequest")?
+ encode_v2_pm_vault_retrieve_request(
+ should_trigger_fingerprint_migration,
+ merchant_id.clone(),
+ customer_id,
+ vault_id,
+ )?
};
let resp = vault::call_to_vault::<pm_types::VaultRetrieve>(self.state, payload, None, None)
@@ -1652,6 +1636,7 @@ impl PaymentMethodsController for PmCards<'_> {
let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id: Some(None),
last_modified_by: initiator
+ .as_ref()
.and_then(|initiator| initiator.to_created_by())
.map(|last_modified_by| last_modified_by.to_string()),
};
@@ -1926,11 +1911,19 @@ impl PaymentMethodsController for PmCards<'_> {
.map(|last_modified_by| last_modified_by.to_string()),
};
+ let compat_action = super::payment_method_modular_forward_compat_action(
+ self.state,
+ &existing_pm.merchant_id,
+ existing_pm.customer_id.as_ref(),
+ )
+ .await;
+
db.update_payment_method(
self.provider.get_key_store(),
existing_pm,
pm_update,
self.provider.get_account().storage_scheme,
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -2173,6 +2166,33 @@ pub fn encode_vault_retrieve_request(
}
}
+#[cfg(feature = "v1")]
+#[instrument(skip_all)]
+pub fn encode_v2_pm_vault_retrieve_request(
+ should_trigger_fingerprint_migration: bool,
+ merchant_id: id_type::MerchantId,
+ customer_id: &id_type::CustomerId,
+ vault_id: &domain::VaultId,
+) -> errors::CustomResult<Vec<u8>, errors::VaultError> {
+ if should_trigger_fingerprint_migration {
+ pm_types::VaultRetrieveRequestNew {
+ entity_id: merchant_id,
+ vault_id: vault_id.clone(),
+ }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode VaultRetrieveRequestNew")
+ } else {
+ pm_types::GenericVaultRetrieveRequest {
+ entity_id: customer_id.to_owned(),
+ vault_id: vault_id.clone(),
+ }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode GenericVaultRetrieveRequest")
+ }
+}
+
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub fn encode_vault_retrieve_request(
@@ -2405,11 +2425,19 @@ pub async fn add_payment_method_data(
.map(|last_modified_by| last_modified_by.to_string()),
};
+ let compat_action = super::payment_method_modular_forward_compat_action(
+ &state,
+ &payment_method.merchant_id,
+ payment_method.customer_id.as_ref(),
+ )
+ .await;
+
db.update_payment_method(
provider.get_key_store(),
payment_method,
pm_update,
provider.get_account().storage_scheme,
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -2491,11 +2519,19 @@ pub async fn add_payment_method_data(
network_tokenization_data: None, // setting it to None as write path will be introduced in a later PR
};
+ let compat_action = super::payment_method_modular_forward_compat_action(
+ &state,
+ &payment_method.merchant_id,
+ payment_method.customer_id.as_ref(),
+ )
+ .await;
+
db.update_payment_method(
provider.get_key_store(),
payment_method,
pm_update,
provider.get_account().storage_scheme,
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -2536,6 +2572,8 @@ pub async fn add_payment_method_data(
payment_method,
pm_update,
provider.get_account().storage_scheme,
+ // Inactivation is a legacy cleanup write and does not require compat.
+ None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -2757,6 +2795,7 @@ pub async fn update_customer_payment_method(
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: pm_data_encrypted.map(Into::into),
last_modified_by: initiator
+ .as_ref()
.and_then(|initiator| initiator.to_created_by())
.map(|last_modified_by| last_modified_by.to_string()),
};
@@ -2765,11 +2804,19 @@ pub async fn update_customer_payment_method(
.payment_method_id
.clone_from(&pm.payment_method_id);
+ let compat_action = super::payment_method_modular_forward_compat_action(
+ &state,
+ &pm.merchant_id,
+ pm.customer_id.as_ref(),
+ )
+ .await;
+
db.update_payment_method(
provider.get_key_store(),
pm.clone(),
pm_update,
provider.get_account().storage_scheme,
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -2840,16 +2887,25 @@ pub async fn update_customer_payment_method(
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: Some(pm_data_encrypted.into()),
last_modified_by: initiator
+ .as_ref()
.and_then(|initiator| initiator.to_created_by())
.map(|last_modified_by| last_modified_by.to_string()),
};
+ let compat_action = super::payment_method_modular_forward_compat_action(
+ &state,
+ &pm.merchant_id,
+ pm.customer_id.as_ref(),
+ )
+ .await;
+
let pm = db
.update_payment_method(
provider.get_key_store(),
pm,
pm_update,
provider.get_account().storage_scheme,
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3168,6 +3224,7 @@ pub async fn update_payment_method_metadata_and_network_token_data_and_last_used
pm_network_token_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>>,
storage_scheme: MerchantStorageScheme,
initiator: Option<&domain::Initiator>,
+ compat_action: Option<domain::PaymentMethodCompatAction>,
) -> errors::CustomResult<(), errors::VaultError> {
let pm_update = payment_method::PaymentMethodUpdate::AdditionalDataUpdate {
locker_id: None,
@@ -3188,7 +3245,7 @@ pub async fn update_payment_method_metadata_and_network_token_data_and_last_used
network_tokenization_data: None, // setting this to None as write path will be introduced in a later PR
};
- db.update_payment_method(key_store, pm, pm_update, storage_scheme)
+ db.update_payment_method(key_store, pm, pm_update, storage_scheme, compat_action)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;
Ok(())
@@ -3205,6 +3262,7 @@ pub async fn update_payment_method_network_token_data(
pm_network_token_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>>,
storage_scheme: MerchantStorageScheme,
initiator: Option<&domain::Initiator>,
+ compat_action: Option<domain::PaymentMethodCompatAction>,
) -> errors::CustomResult<(), errors::VaultError> {
let pm_update = payment_method::PaymentMethodUpdate::NetworkTokenDataUpdate {
network_token_requestor_reference_id,
@@ -3216,12 +3274,13 @@ pub async fn update_payment_method_network_token_data(
network_tokenization_data: None, // setting this to None as write path will be introduced in a later PR
};
- db.update_payment_method(key_store, pm, pm_update, storage_scheme)
+ db.update_payment_method(key_store, pm, pm_update, storage_scheme, compat_action)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;
Ok(())
}
+#[allow(clippy::too_many_arguments)]
pub async fn update_payment_method_and_last_used(
key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
@@ -3230,6 +3289,7 @@ pub async fn update_payment_method_and_last_used(
storage_scheme: MerchantStorageScheme,
card_scheme: Option<String>,
initiator: Option<&domain::Initiator>,
+ compat_action: Option<domain::PaymentMethodCompatAction>,
) -> errors::CustomResult<(), errors::VaultError> {
let pm_update = payment_method::PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
payment_method_data: payment_method_update,
@@ -3239,7 +3299,7 @@ pub async fn update_payment_method_and_last_used(
.and_then(|initiator| initiator.to_created_by())
.map(|last_modified_by| last_modified_by.to_string()),
};
- db.update_payment_method(key_store, pm, pm_update, storage_scheme)
+ db.update_payment_method(key_store, pm, pm_update, storage_scheme, compat_action)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;
Ok(())
@@ -3262,9 +3322,15 @@ pub async fn update_payment_method_connector_mandate_details(
.map(|last_modified_by| last_modified_by.to_string()),
};
- db.update_payment_method(key_store, pm, pm_update, storage_scheme)
- .await
- .change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;
+ db.update_payment_method(
+ key_store,
+ pm,
+ pm_update,
+ storage_scheme,
+ Some(super::payment_method_modular_backward_compat_action(state)),
+ )
+ .await
+ .change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;
Ok(())
}
@@ -3276,6 +3342,7 @@ pub async fn update_payment_method_connector_mandate_details(
connector_mandate_details: Option<CommonMandateReference>,
storage_scheme: MerchantStorageScheme,
initiator: Option<&domain::Initiator>,
+ compat_action: Option<domain::PaymentMethodCompatAction>,
) -> errors::CustomResult<(), errors::VaultError> {
let connector_mandate_details_value = connector_mandate_details
.map(|common_mandate| {
@@ -3293,7 +3360,7 @@ pub async fn update_payment_method_connector_mandate_details(
.map(|last_modified_by| last_modified_by.to_string()),
};
- db.update_payment_method(key_store, pm, pm_update, storage_scheme)
+ db.update_payment_method(key_store, pm, pm_update, storage_scheme, compat_action)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;
Ok(())
@@ -3311,6 +3378,7 @@ pub async fn update_payment_method_connector_mandate_details_and_network_token_d
pm_network_token_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>>,
storage_scheme: MerchantStorageScheme,
initiator: Option<&domain::Initiator>,
+ compat_action: Option<domain::PaymentMethodCompatAction>,
) -> errors::CustomResult<(), errors::VaultError> {
let connector_mandate_details_value = connector_mandate_details
.map(|common_mandate| {
@@ -3339,7 +3407,7 @@ pub async fn update_payment_method_connector_mandate_details_and_network_token_d
network_tokenization_data: None, // setting this to None as write path will be introduced in a later PR
};
- db.update_payment_method(key_store, pm, pm_update, storage_scheme)
+ db.update_payment_method(key_store, pm, pm_update, storage_scheme, compat_action)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;
Ok(())
@@ -3353,6 +3421,7 @@ pub async fn update_payment_method_network_transaction_link_id(
network_transaction_link_id: Option<String>,
storage_scheme: MerchantStorageScheme,
initiator: Option<&domain::Initiator>,
+ compat_action: Option<domain::PaymentMethodCompatAction>,
) -> errors::CustomResult<(), errors::VaultError> {
let pm_update = payment_method::PaymentMethodUpdate::NetworkTransactionLinkIdUpdate {
network_transaction_link_id,
@@ -3361,7 +3430,7 @@ pub async fn update_payment_method_network_transaction_link_id(
.map(|last_modified_by| last_modified_by.to_string()),
};
- db.update_payment_method(key_store, pm, pm_update, storage_scheme)
+ db.update_payment_method(key_store, pm, pm_update, storage_scheme, compat_action)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodTableFailed)?;
Ok(())
@@ -3456,6 +3525,18 @@ pub async fn delete_card_from_vault<'a>(
}
}
+#[cfg(feature = "v1")]
+pub async fn update_metadata_changed_card_in_vault(
+ state: &routes::SessionState,
+ customer_id: &id_type::CustomerId,
+ merchant_id: &id_type::MerchantId,
+ old_card_reference: &str,
+ locker_req: &payment_methods::StoreLockerReq,
+) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> {
+ delete_card_from_vault(state, customer_id, merchant_id, old_card_reference).await?;
+ add_card_to_vault(state, locker_req, customer_id).await
+}
+
///Mock api for local testing
pub async fn mock_call_to_locker_hs(
db: &dyn db::StorageInterface,
@@ -6342,6 +6423,8 @@ pub async fn update_last_used_at(
payment_method.clone(),
update_last_used,
storage_scheme,
+ // Last-used-only updates do not change PM modular compatibility data.
+ None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payment_methods/migration.rs b/crates/router/src/core/payment_methods/migration.rs
index c4c4d6955c..1f4b7fee14 100644
--- a/crates/router/src/core/payment_methods/migration.rs
+++ b/crates/router/src/core/payment_methods/migration.rs
@@ -381,6 +381,8 @@ pub async fn update_payment_method_record(
payment_method,
pm_update,
platform.get_provider().get_account().storage_scheme,
+ // Migration writes are explicit one-off transforms and must not enqueue compat PTs.
+ None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
index b63ec2698d..7da430058f 100644
--- a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
+++ b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs
@@ -9,7 +9,7 @@ use super::{
NetworkTokenizationResponse, State, TransitionTo,
};
use crate::{
- core::payment_methods::transformers as pm_transformers,
+ core::payment_methods::{self, transformers as pm_transformers},
errors::{self, RouterResult},
types::{api, domain},
};
@@ -414,6 +414,12 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest> {
.map(|last_modified_by| last_modified_by.to_string()),
network_tokenization_data: None,
};
+ let compat_action = payment_methods::payment_method_modular_forward_compat_action(
+ self.state,
+ &payment_method.merchant_id,
+ payment_method.customer_id.as_ref(),
+ )
+ .await;
self.state
.store
.update_payment_method(
@@ -421,6 +427,7 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest> {
payment_method,
payment_method_update,
self.merchant_account.storage_scheme,
+ compat_action,
)
.await
.inspect_err(|err| logger::info!("Error updating payment method: {:?}", err))
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 117e6f32cf..e9d979a9be 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1258,15 +1258,23 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
)
.await
{
- Ok(storage::PaymentTokenData::Permanent(card_token_data))
- | Ok(storage::PaymentTokenData::PermanentCard(card_token_data)) => {
- card_token_data
- .payment_method_id
- .as_deref()
- .unwrap_or(payment_method_ref)
- .to_owned()
+ Ok(
+ storage::PaymentTokenData::Permanent(card_token_data)
+ | storage::PaymentTokenData::PermanentCard(card_token_data),
+ ) => card_token_data
+ .payment_method_id
+ .as_deref()
+ .unwrap_or(payment_method_ref)
+ .to_owned(),
+ Ok(_) => payment_method_ref.to_owned(),
+ Err(err) => {
+ logger::warn!(
+ ?err,
+ payment_method_ref,
+ "Failed to fetch payment token from payment server; falling back to PM Modular Service"
+ );
+ payment_method_ref.to_owned()
}
- _ => payment_method_ref.to_owned(),
}
}
_ => payment_method_ref.to_owned(),
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index fe833cff4c..f17f34fecc 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -318,6 +318,12 @@ where
if payment_method.network_transaction_link_id.is_none()
&& connector_network_transaction_link_id.is_some()
{
+ let compat_action = payment_methods::payment_method_modular_forward_compat_action(
+ state,
+ &payment_method.merchant_id,
+ payment_method.customer_id.as_ref(),
+ )
+ .await;
payment_methods::cards::update_payment_method_network_transaction_link_id(
provider.get_key_store(),
&*state.store,
@@ -325,6 +331,7 @@ where
connector_network_transaction_link_id,
provider.get_account().storage_scheme,
initiator,
+ compat_action,
)
.await
.map_err(|err| {
@@ -386,6 +393,12 @@ where
connector_mandate_request_reference_id,
)?;
+ let compat_action = payment_methods::payment_method_modular_forward_compat_action(
+ state,
+ &payment_method.merchant_id,
+ payment_method.customer_id.as_ref(),
+ )
+ .await;
payment_methods::cards::update_payment_method_connector_mandate_details(
provider.get_key_store(),
&*state.store,
@@ -393,6 +406,7 @@ where
connector_mandate_details,
provider.get_account().storage_scheme,
initiator,
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3269,9 +3283,22 @@ async fn update_payment_method_status_and_ntid<F: Clone>(
}
};
+ let compat_action = payment_methods::payment_method_modular_forward_compat_action(
+ state,
+ &payment_method.merchant_id,
+ payment_method.customer_id.as_ref(),
+ )
+ .await;
+
state
.store
- .update_payment_method(key_store, payment_method, pm_update, storage_scheme)
+ .update_payment_method(
+ key_store,
+ payment_method,
+ pm_update,
+ storage_scheme,
+ compat_action,
+ )
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 229d9a1b9e..1c43ab86fa 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -520,6 +520,12 @@ where
pm.metadata.as_ref(),
connector_token,
)?;
+ let compat_action = payment_methods::payment_method_modular_forward_compat_action(
+ state,
+ &pm.merchant_id,
+ pm.customer_id.as_ref(),
+ )
+ .await;
payment_methods::cards::update_payment_method_metadata_and_network_token_data_and_last_used(
platform.get_provider().get_key_store(),
db,
@@ -530,6 +536,7 @@ where
pm_network_token_data_encrypted,
platform.get_provider().get_account().storage_scheme,
platform.get_initiator(),
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -664,6 +671,12 @@ where
} else {
None
};
+ let compat_action = payment_methods::payment_method_modular_forward_compat_action(
+ state,
+ &pm.merchant_id,
+ pm.customer_id.as_ref(),
+ )
+ .await;
payment_methods::cards::update_payment_method_connector_mandate_details_and_network_token_data(
platform.get_provider().get_key_store(),
db,
@@ -674,6 +687,7 @@ where
pm_network_token_data_encrypted,
platform.get_provider().get_account().storage_scheme,
platform.get_initiator(),
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -849,6 +863,13 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
+ let compat_action =
+ payment_methods::payment_method_modular_forward_compat_action(
+ state,
+ &existing_pm.merchant_id,
+ existing_pm.customer_id.as_ref(),
+ )
+ .await;
payment_methods::cards::update_payment_method_and_last_used(
platform.get_provider().get_key_store(),
db,
@@ -857,6 +878,7 @@ where
platform.get_provider().get_account().storage_scheme,
card_scheme,
platform.get_initiator(),
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -2219,6 +2241,12 @@ async fn generate_network_token_and_update_payment_method(
// Update the payment method with network token details
let db = &*state.store;
+ let compat_action = payment_methods::payment_method_modular_forward_compat_action(
+ state,
+ &pm_info.merchant_id,
+ pm_info.customer_id.as_ref(),
+ )
+ .await;
payment_methods::cards::update_payment_method_network_token_data(
platform.get_provider().get_key_store(),
db,
@@ -2228,6 +2256,7 @@ async fn generate_network_token_and_update_payment_method(
pm_network_token_data_encrypted,
platform.get_provider().get_account().storage_scheme,
platform.get_initiator(),
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index fbaf5ccaf2..9f77b92af2 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -2463,6 +2463,8 @@ pub async fn create_recipient_disburse_account(
pm_method,
pm_update,
platform.get_processor().get_account().storage_scheme,
+ // Payout payment method writes are outside PM modular card compat.
+ None,
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 10c3dffd92..d0817b29ff 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -832,6 +832,8 @@ pub async fn save_payout_data_to_locker(
existing_pm,
pm_update,
platform.get_processor().get_account().storage_scheme,
+ // Payout payment method writes are outside PM modular card compat.
+ None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index 01d4fd2862..9ed4e4b6ae 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -584,12 +584,18 @@ async fn store_in_db(
) -> RouterResult<()> {
let update_entries_futures = update_entries
.into_iter()
- .map(|(pm, pm_update)| db.update_payment_method(key_store, pm, pm_update, storage_scheme))
+ .map(|(pm, pm_update)| {
+ // PM auth bulk storage is outside the card PM modular compat scheduling path.
+ db.update_payment_method(key_store, pm, pm_update, storage_scheme, None)
+ })
.collect::<Vec<_>>();
let new_entries_futures = new_entries
.into_iter()
- .map(|pm_new| db.insert_payment_method(key_store, pm_new, storage_scheme))
+ .map(|pm_new| {
+ // PM auth bulk storage is outside the card PM modular compat scheduling path.
+ db.insert_payment_method(key_store, pm_new, storage_scheme, None)
+ })
.collect::<Vec<_>>();
let update_futures = futures::future::join_all(update_entries_futures);
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index b283b8f5f4..8e150bea3e 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -2891,6 +2891,12 @@ async fn update_connector_mandate_details(
.map(|webhook_network_transaction_id| webhook_network_transaction_id.get_id().clone()),
last_modified_by: platform.get_initiator().and_then(|initiator| initiator.to_created_by()).map(|last_modified_by| last_modified_by.to_string()),
};
+ let compat_action = payment_methods::payment_method_modular_compat_action(
+ state,
+ &payment_method_info.merchant_id,
+ payment_method_info.customer_id.as_ref(),
+ )
+ .await;
state
.store
@@ -2899,6 +2905,7 @@ async fn update_connector_mandate_details(
payment_method_info,
pm_update,
platform.get_provider().get_account().storage_scheme,
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/webhooks/network_tokenization_incoming.rs b/crates/router/src/core/webhooks/network_tokenization_incoming.rs
index 7ae7b442f8..5f6b41cb0b 100644
--- a/crates/router/src/core/webhooks/network_tokenization_incoming.rs
+++ b/crates/router/src/core/webhooks/network_tokenization_incoming.rs
@@ -17,7 +17,7 @@ use crate::{
configs::settings,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
- payment_methods::cards,
+ payment_methods::{self, cards},
utils::create_encrypted_data,
},
logger,
@@ -373,12 +373,19 @@ pub async fn handle_metadata_update(
}
};
let db = &*state.store;
+ let compat_action = payment_methods::payment_method_modular_compat_action(
+ state,
+ &payment_method.merchant_id,
+ payment_method.customer_id.as_ref(),
+ )
+ .await;
db.update_payment_method(
platform.get_processor().get_key_store(),
payment_method.clone(),
pm_update,
platform.get_processor().get_account().storage_scheme,
+ compat_action,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 8d5a63dfb1..c56423fbc7 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -2493,9 +2493,10 @@ impl PaymentMethodInterface for KafkaStore {
key_store: &domain::MerchantKeyStore,
m: domain::PaymentMethod,
storage_scheme: MerchantStorageScheme,
+ compat_action: Option<domain::PaymentMethodCompatAction>,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
- .insert_payment_method(key_store, m, storage_scheme)
+ .insert_payment_method(key_store, m, storage_scheme, compat_action)
.await
}
@@ -2505,6 +2506,7 @@ impl PaymentMethodInterface for KafkaStore {
payment_method: domain::PaymentMethod,
payment_method_update: storage::PaymentMethodUpdate,
storage_scheme: MerchantStorageScheme,
+ compat_action: Option<domain::PaymentMethodCompatAction>,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
self.diesel_store
.update_payment_method(
@@ -2512,6 +2514,7 @@ impl PaymentMethodInterface for KafkaStore {
payment_method,
payment_method_update,
storage_scheme,
+ compat_action,
)
.await
}
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 664d479b63..f80694cdee 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -650,13 +650,13 @@ pub async fn save_payment_method_api(
req.client_secret = Some(client_secret);
}
- cards::add_payment_method_data(
+ Box::pin(cards::add_payment_method_data(
state,
req,
auth.platform.get_provider().clone(),
auth.platform.get_initiator().cloned(),
pm_id,
- )
+ ))
.await
})
},
diff --git a/crates/router/src/workflows/payment_method_modular_backward_compat.rs b/crates/router/src/workflows/payment_method_modular_backward_compat.rs
index 220628d654..7c4b492256 100644
--- a/crates/router/src/workflows/payment_method_modular_backward_compat.rs
+++ b/crates/router/src/workflows/payment_method_modular_backward_compat.rs
@@ -1,18 +1,23 @@
+use std::marker::PhantomData;
+
#[cfg(feature = "v1")]
use api_models::payment_methods::Card;
-use common_utils::ext_traits::{OptionExt, StringExt, ValueExt};
-#[cfg(feature = "v2")]
-use common_utils::id_type;
+use common_utils::{
+ ext_traits::{OptionExt, StringExt, ValueExt},
+ id_type,
+};
use error_stack::ResultExt;
use hyperswitch_masking::PeekInterface;
use scheduler::{
consumer::types::process_data, utils as pt_utils, workflows::ProcessTrackerWorkflow,
};
-#[cfg(feature = "v2")]
-use crate::core::payment_methods::add_payment_method_to_legacy_locker;
#[cfg(feature = "v1")]
use crate::core::payment_methods::transformers;
+#[cfg(feature = "v2")]
+use crate::core::payment_methods::{
+ add_payment_method_to_legacy_locker, update_metadata_changed_payment_method_in_legacy_locker,
+};
use crate::{
core::payment_methods::{cards, utils as payment_method_utils, vault},
errors,
@@ -25,389 +30,780 @@ use crate::{
};
#[cfg(feature = "v1")]
-pub async fn backfill_legacy_db_fields(
- db: &dyn StorageInterface,
- key_store: &domain::MerchantKeyStore,
- payment_method: domain::PaymentMethod,
- storage_scheme: common_enums::MerchantStorageScheme,
- tracking_data: &PaymentMethodModularCompatTrackingData,
- process_id: &str,
-) -> Result<domain::PaymentMethod, errors::ProcessTrackerError> {
- let legacy_payment_method = payment_method.get_payment_method_type();
- let legacy_payment_method_type = payment_method.get_payment_method_subtype();
- let should_update_legacy_db_fields =
- legacy_payment_method.is_some() || legacy_payment_method_type.is_some();
+struct BackwardCompatUpdates {
+ payment_method: Option<common_enums::PaymentMethod>,
+ payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_mandate_details: Option<diesel_models::payment_method::ConnectorMandateCompatDetails>,
+}
- if should_update_legacy_db_fields {
- let pm_update = storage::PaymentMethodUpdate::PopulateLegacyCompatFields {
- payment_method: legacy_payment_method,
- payment_method_type: legacy_payment_method_type,
- last_modified_by: tracking_data.last_modified_by.clone(),
- };
+#[cfg(feature = "v2")]
+struct BackwardCompatUpdates {
+ payment_method: Option<common_enums::PaymentMethod>,
+ payment_method_type: Option<common_enums::PaymentMethodType>,
+ connector_mandate_details: Option<diesel_models::payment_method::CommonMandateReference>,
+}
- let updated_payment_method = db
- .update_payment_method(key_store, payment_method, pm_update, storage_scheme)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
+#[cfg(feature = "v1")]
+impl BackwardCompatUpdates {
+ fn connector_mandate_details_for_update(&self) -> Option<serde_json::Value> {
+ self.connector_mandate_details
+ .clone()
+ .and_then(|connector_mandate_details| connector_mandate_details.into_value())
+ }
+}
+
+#[cfg(feature = "v2")]
+impl BackwardCompatUpdates {
+ fn connector_mandate_details_for_update(
+ &self,
+ ) -> Option<diesel_models::payment_method::CommonMandateReference> {
+ self.connector_mandate_details.clone()
+ }
+}
+
+struct BackwardCompatWorkflowBuilder<S: BackwardCompatState> {
+ _state: PhantomData<S>,
+ tracking_data: Option<PaymentMethodModularCompatTrackingData>,
+ merchant_id: Option<id_type::MerchantId>,
+ key_store: Option<domain::MerchantKeyStore>,
+ merchant_account: Option<domain::MerchantAccount>,
+ payment_method: Option<domain::PaymentMethod>,
+ updates: Option<BackwardCompatUpdates>,
+}
+
+trait BackwardCompatState {}
+
+trait BackwardCompatTransitionTo<S: BackwardCompatState> {}
+
+struct BackwardCompatStarted;
+struct BackwardTrackingLoaded;
+struct BackwardContextLoaded;
+struct BackwardPaymentMethodLoaded;
+struct BackwardDbCompatPrepared;
+struct BackwardLockerCompatApplied;
+
+impl BackwardCompatState for BackwardCompatStarted {}
+impl BackwardCompatState for BackwardTrackingLoaded {}
+impl BackwardCompatState for BackwardContextLoaded {}
+impl BackwardCompatState for BackwardPaymentMethodLoaded {}
+impl BackwardCompatState for BackwardDbCompatPrepared {}
+impl BackwardCompatState for BackwardLockerCompatApplied {}
+
+impl BackwardCompatTransitionTo<BackwardTrackingLoaded> for BackwardCompatStarted {}
+impl BackwardCompatTransitionTo<BackwardContextLoaded> for BackwardTrackingLoaded {}
+impl BackwardCompatTransitionTo<BackwardPaymentMethodLoaded> for BackwardContextLoaded {}
+impl BackwardCompatTransitionTo<BackwardDbCompatPrepared> for BackwardPaymentMethodLoaded {}
+impl BackwardCompatTransitionTo<BackwardLockerCompatApplied> for BackwardDbCompatPrepared {}
+
+impl<S: BackwardCompatState> BackwardCompatWorkflowBuilder<S> {
+ fn transition<T: BackwardCompatState>(self) -> BackwardCompatWorkflowBuilder<T>
+ where
+ S: BackwardCompatTransitionTo<T>,
+ {
+ BackwardCompatWorkflowBuilder {
+ _state: PhantomData,
+ tracking_data: self.tracking_data,
+ merchant_id: self.merchant_id,
+ key_store: self.key_store,
+ merchant_account: self.merchant_account,
+ payment_method: self.payment_method,
+ updates: self.updates,
+ }
+ }
+
+ fn tracking_data(&self) -> errors::RouterResult<&PaymentMethodModularCompatTrackingData> {
+ self.tracking_data
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("tracking data must be loaded in backward compatibility workflow")
+ }
+
+ fn merchant_id(&self) -> errors::RouterResult<&id_type::MerchantId> {
+ self.merchant_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("merchant id must be loaded in backward compatibility workflow")
+ }
+
+ fn key_store(&self) -> errors::RouterResult<&domain::MerchantKeyStore> {
+ self.key_store
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
- "Failed to populate legacy payment method fields in backward compatibility PT",
- )?;
+ "merchant key store must be loaded in backward compatibility workflow",
+ )
+ }
- Ok(updated_payment_method)
- } else {
- logger::info!(
- process_id=%process_id,
- payment_method_id=%tracking_data.payment_method_id,
- "Skipping legacy DB field backfill in modular backward compatibility PT because fields are already populated"
+ fn merchant_account(&self) -> errors::RouterResult<&domain::MerchantAccount> {
+ self.merchant_account
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("merchant account must be loaded in backward compatibility workflow")
+ }
+
+ fn payment_method(&self) -> errors::RouterResult<&domain::PaymentMethod> {
+ self.payment_method
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("payment method must be loaded in backward compatibility workflow")
+ }
+
+ fn updates(&self) -> errors::RouterResult<&BackwardCompatUpdates> {
+ self.updates
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("updates must be prepared in backward compatibility workflow")
+ }
+}
+
+impl BackwardCompatWorkflowBuilder<BackwardCompatStarted> {
+ fn new() -> Self {
+ Self {
+ _state: PhantomData,
+ tracking_data: None,
+ merchant_id: None,
+ key_store: None,
+ merchant_account: None,
+ payment_method: None,
+ updates: None,
+ }
+ }
+
+ fn load_tracking_data(
+ mut self,
+ tracking_data: PaymentMethodModularCompatTrackingData,
+ ) -> BackwardCompatWorkflowBuilder<BackwardTrackingLoaded> {
+ self.merchant_id = Some(tracking_data.merchant_id.clone());
+ self.tracking_data = Some(tracking_data);
+ self.transition()
+ }
+}
+
+impl BackwardCompatWorkflowBuilder<BackwardTrackingLoaded> {
+ fn load_context(
+ mut self,
+ key_store: domain::MerchantKeyStore,
+ merchant_account: domain::MerchantAccount,
+ ) -> BackwardCompatWorkflowBuilder<BackwardContextLoaded> {
+ self.key_store = Some(key_store);
+ self.merchant_account = Some(merchant_account);
+ self.transition()
+ }
+}
+
+impl BackwardCompatWorkflowBuilder<BackwardContextLoaded> {
+ fn load_payment_method(
+ mut self,
+ payment_method: domain::PaymentMethod,
+ ) -> BackwardCompatWorkflowBuilder<BackwardPaymentMethodLoaded> {
+ self.payment_method = Some(payment_method);
+ self.transition()
+ }
+}
+
+impl BackwardCompatWorkflowBuilder<BackwardPaymentMethodLoaded> {
+ fn should_skip(&self) -> errors::RouterResult<bool> {
+ Ok(self.payment_method()?.version == common_enums::ApiVersion::V1)
+ }
+
+ fn prepare_db_compat(
+ mut self,
+ ) -> errors::RouterResult<BackwardCompatWorkflowBuilder<BackwardDbCompatPrepared>> {
+ let payment_method = self.payment_method()?;
+ let updates = BackwardCompatUpdates {
+ payment_method: payment_method.get_payment_method_type(),
+ payment_method_type: payment_method.get_payment_method_subtype(),
+ connector_mandate_details: Self::connector_mandate_details(payment_method),
+ };
+ self.updates = Some(updates);
+ Ok(self.transition())
+ }
+
+ #[cfg(feature = "v1")]
+ fn connector_mandate_details(
+ payment_method: &domain::PaymentMethod,
+ ) -> Option<diesel_models::payment_method::ConnectorMandateCompatDetails> {
+ diesel_models::payment_method::CommonMandateReference::parse_connector_mandate_compat_details(
+ payment_method.connector_mandate_details.clone(),
+ )
+ .map(diesel_models::payment_method::CommonMandateReference::add_v1_connector_mandate_fields)
+ }
+
+ #[cfg(feature = "v2")]
+ fn connector_mandate_details(
+ payment_method: &domain::PaymentMethod,
+ ) -> Option<diesel_models::payment_method::CommonMandateReference> {
+ payment_method
+ .connector_mandate_details
+ .clone()
+ .map(Into::into)
+ }
+}
+
+impl BackwardCompatWorkflowBuilder<BackwardDbCompatPrepared> {
+ #[cfg(feature = "v1")]
+ async fn apply_locker_compat(
+ self,
+ state: &SessionState,
+ db: &dyn StorageInterface,
+ process_id: &str,
+ ) -> Result<
+ BackwardCompatWorkflowBuilder<BackwardLockerCompatApplied>,
+ errors::ProcessTrackerError,
+ > {
+ Self::backfill_legacy_locker_card(
+ state,
+ db,
+ self.key_store()?,
+ self.merchant_id()?,
+ self.payment_method()?,
+ self.merchant_account()?.storage_scheme,
+ self.tracking_data()?,
+ process_id,
+ )
+ .await?;
+
+ Ok(self.transition())
+ }
+
+ #[cfg(feature = "v2")]
+ async fn apply_locker_compat(
+ self,
+ state: &SessionState,
+ _db: &dyn StorageInterface,
+ process_id: &str,
+ ) -> Result<
+ BackwardCompatWorkflowBuilder<BackwardLockerCompatApplied>,
+ errors::ProcessTrackerError,
+ > {
+ let platform = domain::Platform::new(
+ self.merchant_account()?.clone(),
+ self.key_store()?.clone(),
+ self.merchant_account()?.clone(),
+ self.key_store()?.clone(),
+ None,
);
- Ok(payment_method)
+
+ Box::pin(Self::backfill_legacy_locker_card(
+ state,
+ &platform,
+ self.payment_method()?,
+ self.tracking_data()?,
+ process_id,
+ ))
+ .await?;
+
+ Ok(self.transition())
}
}
-#[cfg(feature = "v2")]
-pub async fn backfill_legacy_db_fields(
- db: &dyn StorageInterface,
- key_store: &domain::MerchantKeyStore,
- payment_method: domain::PaymentMethod,
- storage_scheme: common_enums::MerchantStorageScheme,
- tracking_data: &PaymentMethodModularCompatTrackingData,
- process_id: &str,
-) -> Result<domain::PaymentMethod, errors::ProcessTrackerError> {
- let legacy_payment_method = payment_method.get_payment_method_type();
- let legacy_payment_method_type = payment_method.get_payment_method_subtype();
- let should_update_legacy_db_fields =
- legacy_payment_method.is_some() || legacy_payment_method_type.is_some();
+impl BackwardCompatWorkflowBuilder<BackwardLockerCompatApplied> {
+ async fn mark_complete(
+ self,
+ db: &dyn StorageInterface,
+ ) -> Result<domain::PaymentMethod, errors::ProcessTrackerError> {
+ let tracking_data = self.tracking_data()?;
+ let key_store = self.key_store()?;
+ let merchant_account = self.merchant_account()?;
+ let payment_method = self.payment_method()?;
+ let updates = self.updates()?;
- if should_update_legacy_db_fields {
let pm_update = storage::PaymentMethodUpdate::PopulateLegacyCompatFields {
- payment_method: legacy_payment_method,
- payment_method_type: legacy_payment_method_type,
+ payment_method: updates.payment_method,
+ payment_method_type: updates.payment_method_type,
+ connector_mandate_details: updates.connector_mandate_details_for_update(),
last_modified_by: tracking_data.last_modified_by.clone(),
};
- let updated_payment_method = db
- .update_payment_method(key_store, payment_method, pm_update, storage_scheme)
+ Ok(db
+ .update_payment_method(
+ key_store,
+ payment_method.clone(),
+ pm_update,
+ merchant_account.storage_scheme,
+ // Backward compat completion update must not recursively enqueue compat again.
+ None,
+ )
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
- "Failed to populate legacy payment method fields in backward compatibility inline flow",
- )?;
-
- Ok(updated_payment_method)
- } else {
- logger::info!(
- process_id=%process_id,
- payment_method_id=%tracking_data.payment_method_id,
- "Skipping legacy DB field backfill in modular backward compatibility inline flow because fields are already populated"
- );
- Ok(payment_method)
+ "Failed to populate legacy payment method fields in backward compatibility flow",
+ )?)
}
}
#[cfg(feature = "v1")]
-pub async fn backfill_legacy_locker_card(
- state: &SessionState,
- platform: &domain::Platform,
- payment_method: &domain::PaymentMethod,
- tracking_data: &PaymentMethodModularCompatTrackingData,
- process_id: &str,
-) -> Result<(), errors::ProcessTrackerError> {
- let legacy_locker_skip_reason = match (
- payment_method.get_payment_method_type(),
- payment_method.locker_id.as_ref(),
- payment_method.customer_id.as_ref(),
- ) {
- (Some(common_enums::PaymentMethod::Card), Some(_), Some(_)) => None,
- (Some(common_enums::PaymentMethod::Card), None, _) => Some("locker reference is missing"),
- (Some(common_enums::PaymentMethod::Card), Some(_), None) => Some("customer_id is missing"),
- _ => Some("payment method is not card"),
- };
-
- let merchant_id = platform.get_provider().get_account().get_id();
-
- if let Some(skip_reason) = legacy_locker_skip_reason {
- logger::info!(
- process_id=%process_id,
- payment_method_id=%tracking_data.payment_method_id,
- skip_reason,
- "Skipping legacy locker card backfill in modular backward compatibility PT"
- );
- } else {
- let customer_id = payment_method
- .customer_id
- .clone()
- .get_required_value("customer_id")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "customer_id not found for card payment method in backward compatibility PT",
- )?;
-
- let card_reference = payment_method
- .locker_id
- .clone()
- .get_required_value("locker_id")?
- .to_string();
-
- let legacy_card_exists = match cards::get_card_from_vault(
- state,
- &customer_id,
- merchant_id,
- &card_reference,
- )
- .await
- {
- Ok(_) => {
- logger::info!(
- process_id=%process_id,
- payment_method_id=%tracking_data.payment_method_id,
- card_reference=%card_reference,
- "Skipping legacy locker write in modular backward compatibility PT because card already exists"
- );
- true
+impl BackwardCompatWorkflowBuilder<BackwardDbCompatPrepared> {
+ #[allow(clippy::too_many_arguments)]
+ async fn backfill_legacy_locker_card(
+ state: &SessionState,
+ db: &dyn StorageInterface,
+ key_store: &domain::MerchantKeyStore,
+ merchant_id: &id_type::MerchantId,
+ payment_method: &domain::PaymentMethod,
+ storage_scheme: common_enums::MerchantStorageScheme,
+ tracking_data: &PaymentMethodModularCompatTrackingData,
+ process_id: &str,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ let legacy_locker_skip_reason = match (
+ payment_method.get_payment_method_type(),
+ payment_method.locker_id.as_ref(),
+ payment_method.customer_id.as_ref(),
+ ) {
+ (Some(common_enums::PaymentMethod::Card), Some(_), Some(_)) => None,
+ (Some(common_enums::PaymentMethod::Card), None, _) => {
+ Some("locker reference is missing")
}
- Err(err) => {
- logger::info!(
- ?err,
- process_id=%process_id,
- payment_method_id=%tracking_data.payment_method_id,
- card_reference=%card_reference,
- "Legacy locker card not found or not readable in modular backward compatibility PT; proceeding with legacy locker upsert"
- );
- false
+ (Some(common_enums::PaymentMethod::Card), Some(_), None) => {
+ Some("customer_id is missing")
}
+ _ => Some("payment method is not card"),
};
- if !legacy_card_exists {
- let should_trigger_fingerprint_migration =
- payment_method_utils::get_should_trigger_fingerprint_migration(
- state,
- None,
- platform.get_provider().get_provider_merchant_id(),
- )
- .await;
+ if let Some(skip_reason) = legacy_locker_skip_reason {
+ logger::info!(
+ process_id=%process_id,
+ payment_method_id=%tracking_data.payment_method_id,
+ skip_reason,
+ "Skipping legacy locker card backfill in modular backward compatibility PT"
+ );
+ } else {
+ let customer_id = payment_method
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "customer_id not found for card payment method in backward compatibility PT",
+ )?;
- let payload = cards::encode_vault_retrieve_request(
- should_trigger_fingerprint_migration,
- merchant_id.clone(),
+ let card_reference = payment_method
+ .locker_id
+ .clone()
+ .get_required_value("locker_id")?;
+
+ let legacy_card_exists = match cards::get_card_from_vault(
+ state,
&customer_id,
+ merchant_id,
&card_reference,
)
- .attach_printable(
- "Failed to encode generic locker retrieve request in backward compatibility PT",
- )?;
-
- let vault_response =
- vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None, None)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to retrieve card from generic locker in backward compatibility PT",
- )?;
- let stored_pm_resp: pm_types::VaultRetrieveResponse = vault_response
+ .await
+ {
+ Ok(_) => {
+ logger::info!(
+ process_id=%process_id,
+ payment_method_id=%tracking_data.payment_method_id,
+ card_reference=%card_reference,
+ "Skipping legacy locker write in modular backward compatibility PT because card already exists"
+ );
+ true
+ }
+ Err(err) => {
+ logger::info!(
+ ?err,
+ process_id=%process_id,
+ payment_method_id=%tracking_data.payment_method_id,
+ card_reference=%card_reference,
+ "Legacy locker card not found or not readable in modular backward compatibility PT; proceeding with legacy locker upsert"
+ );
+ false
+ }
+ };
+
+ if !legacy_card_exists {
+ let should_trigger_fingerprint_migration =
+ payment_method_utils::get_should_trigger_fingerprint_migration(
+ state,
+ Some(&customer_id),
+ hyperswitch_domain_models::platform::ProviderMerchantId::new(
+ merchant_id.clone(),
+ ),
+ )
+ .await;
+
+ let generic_vault_id = domain::VaultId::generate(card_reference.clone());
+ let payload = cards::encode_v2_pm_vault_retrieve_request(
+ should_trigger_fingerprint_migration,
+ merchant_id.clone(),
+ &customer_id,
+ &generic_vault_id,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to encode generic locker retrieve request in backward compatibility PT",
+ )?;
+ let vault_response = vault::call_to_vault::<pm_types::VaultRetrieve>(
+ state, payload, None, None,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to retrieve card from generic locker in backward compatibility PT",
+ )?;
+ let stored_pm_resp: pm_types::VaultRetrieveResponse = vault_response
.parse_struct("VaultRetrieveResponse")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to parse generic locker retrieve response in backward compatibility PT",
)?;
- let locker_card_detail =
- if let hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card) =
- stored_pm_resp.data
- {
- card
- } else {
- Err(
+ let locker_card_detail =
+ if let hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card) =
+ stored_pm_resp.data
+ {
+ card
+ } else {
+ Err(
error_stack::report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Generic locker returned non-card data in backward compatibility PT",
),
)?
- };
-
- let card_isin = locker_card_detail.card_number.get_card_isin();
- let locker_req = transformers::StoreLockerReq::LockerCard(transformers::StoreCardReq {
- merchant_id: merchant_id.clone(),
- merchant_customer_id: customer_id.clone(),
- requestor_card_reference: Some(card_reference.to_owned()),
- card: Card {
- card_number: locker_card_detail.card_number,
- name_on_card: locker_card_detail.card_holder_name,
- card_exp_month: locker_card_detail.card_exp_month,
- card_exp_year: locker_card_detail.card_exp_year,
- card_brand: locker_card_detail
- .card_network
- .map(|network| network.to_string()),
- card_isin: Some(card_isin),
- nick_name: locker_card_detail
- .nick_name
- .as_ref()
- .map(|nick_name| nick_name.peek().to_owned()),
- },
- ttl: state.conf.locker.ttl_for_storage_in_secs,
- });
-
- let _ = cards::add_card_to_vault(state, &locker_req, &customer_id)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to add card to legacy locker in backward compatibility PT",
- )?;
-
- logger::info!(
- process_id=%process_id,
- payment_method_id=%tracking_data.payment_method_id,
- "Upserted card into legacy locker in modular backward compatibility PT"
- );
- }
- }
+ };
+
+ let card_isin = locker_card_detail.card_number.get_card_isin();
+ let locker_req =
+ transformers::StoreLockerReq::LockerCard(transformers::StoreCardReq {
+ merchant_id: merchant_id.clone(),
+ merchant_customer_id: customer_id.clone(),
+ requestor_card_reference: Some(card_reference.clone()),
+ card: Card {
+ card_number: locker_card_detail.card_number,
+ name_on_card: locker_card_detail.card_holder_name,
+ card_exp_month: locker_card_detail.card_exp_month,
+ card_exp_year: locker_card_detail.card_exp_year,
+ card_brand: locker_card_detail
+ .card_network
+ .map(|network| network.to_string()),
+ card_isin: Some(card_isin),
+ nick_name: locker_card_detail
+ .nick_name
+ .as_ref()
+ .map(|nick_name| nick_name.peek().to_owned()),
+ },
+ ttl: state.conf.locker.ttl_for_storage_in_secs,
+ });
+
+ let add_card_resp = cards::add_card_to_vault(state, &locker_req, &customer_id)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to add card to legacy locker in backward compatibility PT",
+ )?;
- Ok(())
-}
+ if matches!(
+ add_card_resp.duplication_check,
+ Some(transformers::DataDuplicationCheck::MetaDataChanged)
+ ) {
+ let older_payment_method = db
+ .find_payment_method_by_locker_id(
+ key_store,
+ &add_card_resp.card_reference,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to fetch legacy PM referencing metadata-changed locker id",
+ )?;
-#[cfg(feature = "v2")]
-pub async fn backfill_legacy_locker_card(
- state: &SessionState,
- platform: &domain::Platform,
- payment_method: &domain::PaymentMethod,
- tracking_data: &PaymentMethodModularCompatTrackingData,
- process_id: &str,
-) -> Result<(), errors::ProcessTrackerError> {
- let legacy_locker_skip_reason = match (
- payment_method.get_payment_method_type(),
- payment_method.locker_id.as_ref(),
- payment_method.customer_id.as_ref(),
- ) {
- (Some(common_enums::PaymentMethod::Card), Some(_), Some(_)) => None,
- (Some(common_enums::PaymentMethod::Card), None, _) => Some("locker reference is missing"),
- (Some(common_enums::PaymentMethod::Card), Some(_), None) => Some("customer_id is missing"),
- _ => Some("payment method is not card"),
- };
-
- let pm_customer_id = payment_method
- .customer_id
- .clone()
- .get_required_value("customer_id")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "customer_id not found for card payment method in backward compatibility inline flow",
- )?;
+ let updated_card_resp = cards::update_metadata_changed_card_in_vault(
+ state,
+ &customer_id,
+ merchant_id,
+ &add_card_resp.card_reference,
+ &locker_req,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to update metadata-changed card in legacy locker during backward compatibility PT",
+ )?;
- if let Some(skip_reason) = legacy_locker_skip_reason {
- logger::info!(
- process_id=%process_id,
- payment_method_id=%tracking_data.payment_method_id,
- skip_reason,
- "Skipping legacy locker card backfill in modular backward compatibility inline flow"
- );
- } else {
- let customer_id = id_type::CustomerId::try_from(pm_customer_id.clone())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to convert global customer id for backward compatibility inline flow",
- )?;
+ if older_payment_method.locker_id.as_deref()
+ != Some(updated_card_resp.card_reference.as_str())
+ {
+ let pm_update = storage::PaymentMethodUpdate::AdditionalDataUpdate {
+ payment_method_data: None,
+ status: None,
+ locker_id: Some(updated_card_resp.card_reference.clone()),
+ payment_method: None,
+ payment_method_type: None,
+ payment_method_issuer: None,
+ network_token_requestor_reference_id: None,
+ network_token_locker_id: None,
+ network_token_payment_method_data: None,
+ last_modified_by: tracking_data.last_modified_by.clone(),
+ metadata: None,
+ last_used_at: None,
+ connector_mandate_details: None,
+ network_tokenization_data: None,
+ };
+
+ db.update_payment_method(
+ key_store,
+ older_payment_method,
+ pm_update,
+ storage_scheme,
+ // Metadata-change locker reconciliation is already inside backward compat.
+ None,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to update legacy PM locker id after metadata-changed backward compatibility PT",
+ )?;
+ }
- let card_reference = payment_method
- .locker_id
- .clone()
- .get_required_value("locker_id")?
- .get_string_repr()
- .to_owned();
+ logger::info!(
+ process_id=%process_id,
+ payment_method_id=%tracking_data.payment_method_id,
+ old_card_reference=%add_card_resp.card_reference,
+ new_card_reference=%updated_card_resp.card_reference,
+ "Reinserted metadata-changed card and updated referencing PM in backward compatibility PT"
+ );
+ }
- let legacy_card_exists = match cards::get_card_from_locker(
- state,
- &customer_id,
- platform.get_provider().get_account().get_id(),
- &card_reference,
- )
- .await
- {
- Ok(_) => {
logger::info!(
process_id=%process_id,
payment_method_id=%tracking_data.payment_method_id,
- card_reference=%card_reference,
- "Skipping legacy locker write in modular backward compatibility inline flow because card already exists"
+ "Upserted card into legacy locker in modular backward compatibility PT"
);
- true
}
- Err(err) => {
- logger::info!(
- ?err,
- process_id=%process_id,
- payment_method_id=%tracking_data.payment_method_id,
- card_reference=%card_reference,
- "Legacy locker card not found or not readable in modular backward compatibility inline flow; proceeding with legacy locker upsert"
- );
- false
+ }
+
+ Ok(())
+ }
+}
+
+#[cfg(feature = "v2")]
+impl BackwardCompatWorkflowBuilder<BackwardDbCompatPrepared> {
+ async fn backfill_legacy_locker_card(
+ state: &SessionState,
+ platform: &domain::Platform,
+ payment_method: &domain::PaymentMethod,
+ tracking_data: &PaymentMethodModularCompatTrackingData,
+ process_id: &str,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ let legacy_locker_skip_reason = match (
+ payment_method.get_payment_method_type(),
+ payment_method.locker_id.as_ref(),
+ payment_method.customer_id.as_ref(),
+ ) {
+ (Some(common_enums::PaymentMethod::Card), Some(_), Some(_)) => None,
+ (Some(common_enums::PaymentMethod::Card), None, _) => {
+ Some("locker reference is missing")
+ }
+ (Some(common_enums::PaymentMethod::Card), Some(_), None) => {
+ Some("customer_id is missing")
}
+ _ => Some("payment method is not card"),
};
- if !legacy_card_exists {
- let should_trigger_fingerprint_migration =
- payment_method_utils::get_should_trigger_fingerprint_migration(
- state,
- None,
- platform.get_provider().get_provider_merchant_id(),
- )
- .await;
+ if let Some(skip_reason) = legacy_locker_skip_reason {
+ logger::info!(
+ process_id=%process_id,
+ payment_method_id=%tracking_data.payment_method_id,
+ skip_reason,
+ "Skipping legacy locker card backfill in modular backward compatibility inline flow"
+ );
+ } else {
+ let pm_customer_id = payment_method
+ .customer_id
+ .clone()
+ .get_required_value("customer_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "customer_id not found for card payment method in backward compatibility inline flow",
+ )?;
+
+ let customer_id = id_type::CustomerId::try_from(pm_customer_id.clone())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to convert global customer id for backward compatibility inline flow",
+ )?;
- let payload = cards::encode_vault_retrieve_request(
- should_trigger_fingerprint_migration,
- platform.get_provider().get_account().get_id().clone(),
- &pm_customer_id,
+ let card_reference = payment_method
+ .locker_id
+ .clone()
+ .get_required_value("locker_id")?
+ .get_string_repr()
+ .to_owned();
+
+ let legacy_card_exists = match cards::get_card_from_locker(
+ state,
+ &customer_id,
+ platform.get_provider().get_account().get_id(),
&card_reference,
)
- .attach_printable(
+ .await
+ {
+ Ok(_) => {
+ logger::info!(
+ process_id=%process_id,
+ payment_method_id=%tracking_data.payment_method_id,
+ card_reference=%card_reference,
+ "Skipping legacy locker write in modular backward compatibility inline flow because card already exists"
+ );
+ true
+ }
+ Err(err) => {
+ logger::info!(
+ ?err,
+ process_id=%process_id,
+ payment_method_id=%tracking_data.payment_method_id,
+ card_reference=%card_reference,
+ "Legacy locker card not found or not readable in modular backward compatibility inline flow; proceeding with legacy locker upsert"
+ );
+ false
+ }
+ };
+
+ if !legacy_card_exists {
+ let should_trigger_fingerprint_migration =
+ payment_method_utils::get_should_trigger_fingerprint_migration(
+ state,
+ None,
+ platform.get_provider().get_provider_merchant_id(),
+ )
+ .await;
+
+ let payload = cards::encode_vault_retrieve_request(
+ should_trigger_fingerprint_migration,
+ platform.get_provider().get_account().get_id().clone(),
+ &pm_customer_id,
+ &card_reference,
+ )
+ .attach_printable(
"Failed to encode generic locker retrieve request in backward compatibility inline flow",
)?;
-
- let vault_response = vault::call_to_vault::<pm_types::VaultRetrieve>(
- state, payload, None, None,
- )
+ let vault_response =
+ vault::call_to_vault::<pm_types::VaultRetrieve>(state, payload, None, None)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to retrieve card from generic locker in backward compatibility inline flow",
)?;
- let stored_pm_resp: pm_types::VaultRetrieveResponse = vault_response
+ let stored_pm_resp: pm_types::VaultRetrieveResponse = vault_response
.parse_struct("VaultRetrieveResponse")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to parse generic locker retrieve response in backward compatibility inline flow",
)?;
- if !matches!(
- stored_pm_resp.data,
- hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(_)
- ) {
- Err(
+ if !matches!(
+ stored_pm_resp.data,
+ hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(_)
+ ) {
+ Err(
error_stack::report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Generic locker returned non-card data in backward compatibility inline flow",
),
)?
- }
+ }
- let _ = add_payment_method_to_legacy_locker(
- state,
- platform,
- &stored_pm_resp.data,
- Some(domain::VaultId::generate(card_reference.clone())),
- &pm_customer_id,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to add card to legacy locker in backward compatibility inline flow",
- )?;
+ let add_card_resp = add_payment_method_to_legacy_locker(
+ state,
+ platform,
+ &stored_pm_resp.data,
+ Some(domain::VaultId::generate(card_reference.clone())),
+ &pm_customer_id,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to add card to legacy locker in backward compatibility inline flow",
+ )?;
- logger::info!(
- process_id=%process_id,
- payment_method_id=%tracking_data.payment_method_id,
- "Upserted card into legacy locker in modular backward compatibility inline flow"
- );
+ if matches!(
+ add_card_resp.duplication_check,
+ Some(crate::core::payment_methods::transformers::DataDuplicationCheck::MetaDataChanged)
+ ) {
+ let db = &*state.store;
+ let old_card_reference = add_card_resp.card_reference;
+ let older_payment_method = db
+ .find_payment_method_by_locker_id(
+ platform.get_provider().get_key_store(),
+ &old_card_reference,
+ platform.get_provider().get_account().storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to fetch legacy PM referencing metadata-changed locker id",
+ )?;
+
+ let updated_card_resp = update_metadata_changed_payment_method_in_legacy_locker(
+ state,
+ platform,
+ &stored_pm_resp.data,
+ Some(domain::VaultId::generate(card_reference.clone())),
+ &pm_customer_id,
+ old_card_reference.clone(),
+ )
+ .await
+ .attach_printable(
+ "Failed to update metadata-changed card in legacy locker during backward compatibility inline flow",
+ )?;
+
+ let updated_card_reference = updated_card_resp.vault_id.get_string_repr().to_owned();
+ let older_locker_id = older_payment_method
+ .locker_id
+ .as_ref()
+ .map(|locker_id| locker_id.get_string_repr().to_owned());
+
+ if older_locker_id.as_deref() != Some(updated_card_reference.as_str()) {
+ let pm_update = storage::PaymentMethodUpdate::GenericUpdate {
+ payment_method_data: None,
+ status: None,
+ locker_id: Some(updated_card_reference.clone()),
+ payment_method_type_v2: None,
+ payment_method_subtype: None,
+ network_token_requestor_reference_id: None,
+ network_token_locker_id: None,
+ network_token_payment_method_data: None,
+ locker_fingerprint_id: None,
+ connector_mandate_details: Box::new(None),
+ external_vault_source: None,
+ network_transaction_id: None,
+ network_transaction_link_id: None,
+ last_modified_by: tracking_data.last_modified_by.clone(),
+ };
+
+ db.update_payment_method(
+ platform.get_provider().get_key_store(),
+ older_payment_method,
+ pm_update,
+ platform.get_provider().get_account().storage_scheme,
+ // Backfill of the older PM is already part of backward compat execution.
+ None,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to update legacy PM locker id after metadata-changed backward compatibility inline flow",
+ )?;
+ }
+
+ logger::info!(
+ process_id=%process_id,
+ payment_method_id=%tracking_data.payment_method_id,
+ old_card_reference=%old_card_reference,
+ new_card_reference=%updated_card_reference,
+ "Reinserted metadata-changed card and updated referencing PM in backward compatibility inline flow"
+ );
+ }
+
+ logger::info!(
+ process_id=%process_id,
+ payment_method_id=%tracking_data.payment_method_id,
+ "Upserted card into legacy locker in modular backward compatibility inline flow"
+ );
+ }
}
- }
- Ok(())
+ Ok(())
+ }
}
pub async fn run_payment_method_modular_backward_compat_backfill(
@@ -416,7 +812,8 @@ pub async fn run_payment_method_modular_backward_compat_backfill(
process_id: &str,
) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
- let merchant_id = tracking_data.merchant_id.clone();
+ let workflow = BackwardCompatWorkflowBuilder::new().load_tracking_data(tracking_data);
+ let merchant_id = workflow.merchant_id()?.clone();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
@@ -428,77 +825,53 @@ pub async fn run_payment_method_modular_backward_compat_backfill(
let merchant_account = db
.find_merchant_account_by_merchant_id(&merchant_id, &key_store)
.await?;
+ let workflow = workflow.load_context(key_store, merchant_account);
#[cfg(feature = "v1")]
- let payment_method_id = tracking_data.payment_method_id.as_str();
+ let payment_method_id = workflow.tracking_data()?.payment_method_id.as_str();
#[cfg(feature = "v2")]
let payment_method_id = id_type::GlobalPaymentMethodId::generate_from_string(
- tracking_data.payment_method_id.clone(),
+ workflow.tracking_data()?.payment_method_id.clone(),
);
let payment_method = db
.find_payment_method(
- &key_store,
+ workflow.key_store()?,
#[cfg(feature = "v1")]
payment_method_id,
#[cfg(feature = "v2")]
&payment_method_id,
- merchant_account.storage_scheme,
+ workflow.merchant_account()?.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to fetch payment method for modular backward compatibility backfill",
)?;
+ let workflow = workflow.load_payment_method(payment_method);
- let payment_method = backfill_legacy_db_fields(
- db,
- &key_store,
- payment_method,
- merchant_account.storage_scheme,
- &tracking_data,
- process_id,
- )
- .await?;
-
- let platform = domain::Platform::new(
- merchant_account.clone(),
- key_store.clone(),
- merchant_account,
- key_store,
- None,
- );
-
- #[cfg(feature = "v1")]
- {
- backfill_legacy_locker_card(
- state,
- &platform,
- &payment_method,
- &tracking_data,
- process_id,
- )
- .await
+ if workflow.should_skip()? {
+ logger::info!(
+ process_id=%process_id,
+ payment_method_id=%workflow.tracking_data()?.payment_method_id,
+ "Skipping modular backward compatibility backfill because legacy PM is not forward compatible"
+ );
+ } else {
+ workflow
+ .prepare_db_compat()?
+ .apply_locker_compat(state, db, process_id)
+ .await?
+ .mark_complete(db)
+ .await?;
}
- #[cfg(feature = "v2")]
- {
- backfill_legacy_locker_card(
- state,
- &platform,
- &payment_method,
- &tracking_data,
- process_id,
- )
- .await
- }
+ Ok(())
}
pub struct PaymentMethodModularBackwardCompatWorkflow;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularBackwardCompatWorkflow {
- #[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
@@ -512,8 +885,12 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularBackwardCompat
.parse_value("PaymentMethodModularCompatTrackingData")?;
logger::info!(process_id=%process.id, ?tracking_data, "Parsed modular backward compatibility PT tracking data");
- run_payment_method_modular_backward_compat_backfill(state, tracking_data, &process.id)
- .await?;
+ Box::pin(run_payment_method_modular_backward_compat_backfill(
+ state,
+ tracking_data,
+ &process.id,
+ ))
+ .await?;
let db = &*state.store;
db.as_scheduler()
@@ -527,15 +904,6 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularBackwardCompat
Ok(())
}
- #[cfg(feature = "v2")]
- async fn execute_workflow<'a>(
- &'a self,
- _state: &'a SessionState,
- _process: storage::ProcessTracker,
- ) -> Result<(), errors::ProcessTrackerError> {
- Err(errors::ProcessTrackerError::NotImplemented)
- }
-
async fn error_handler<'a>(
&'a self,
state: &'a SessionState,
diff --git a/crates/router/src/workflows/payment_method_modular_forward_compat.rs b/crates/router/src/workflows/payment_method_modular_forward_compat.rs
index 3651eaf4ad..0d422b4ce7 100644
--- a/crates/router/src/workflows/payment_method_modular_forward_compat.rs
+++ b/crates/router/src/workflows/payment_method_modular_forward_compat.rs
@@ -1,4 +1,4 @@
-use std::str::FromStr;
+use std::{marker::PhantomData, str::FromStr};
use common_utils::ext_traits::{Encode, OptionExt, StringExt, ValueExt};
use error_stack::ResultExt;
@@ -8,90 +8,231 @@ use scheduler::{
};
#[cfg(feature = "v1")]
-use crate::types::{domain, payment_methods as pm_types};
+use crate::types::payment_methods as pm_types;
use crate::{
core::payment_methods::{cards, utils as payment_method_utils, vault},
errors,
logger::{self, error},
- routes::SessionState,
- types::storage::{self, PaymentMethodModularCompatTrackingData},
+ routes::{app::StorageInterface, SessionState},
+ types::{domain, storage, storage::PaymentMethodModularCompatTrackingData},
};
pub struct PaymentMethodModularForwardCompatWorkflow;
-#[async_trait::async_trait]
-impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularForwardCompatWorkflow {
- #[cfg(feature = "v1")]
- async fn execute_workflow<'a>(
- &'a self,
- state: &'a SessionState,
- process: storage::ProcessTracker,
- ) -> Result<(), errors::ProcessTrackerError> {
- // Step 1: Parse PT tracking payload and load merchant context (key store + account).
- logger::info!(process_id=%process.id, "Starting payment method modular compatibility PT");
- let db = &*state.store;
- let tracking_data: PaymentMethodModularCompatTrackingData =
- process
- .tracking_data
- .clone()
- .parse_value("PaymentMethodModularCompatTrackingData")?;
- logger::info!(process_id=%process.id, ?tracking_data, "Parsed modular compatibility PT tracking data");
+#[cfg(feature = "v1")]
+#[derive(Default)]
+struct ForwardCompatUpdates {
+ connector_mandate_details: Option<diesel_models::payment_method::ConnectorMandateCompatDetails>,
+ locker_fingerprint_id: Option<String>,
+ auxiliary_fingerprint_id: Option<String>,
+}
- let merchant_id = tracking_data.merchant_id;
- let key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- &merchant_id,
- &state.store.get_master_key().to_vec().into(),
- )
- .await?;
+#[cfg(feature = "v1")]
+struct ForwardCompatWorkflowBuilder<S: ForwardCompatState> {
+ _state: PhantomData<S>,
+ tracking_data: Option<PaymentMethodModularCompatTrackingData>,
+ merchant_id: Option<common_utils::id_type::MerchantId>,
+ key_store: Option<domain::MerchantKeyStore>,
+ merchant_account: Option<domain::MerchantAccount>,
+ payment_method: Option<domain::PaymentMethod>,
+ updates: Option<ForwardCompatUpdates>,
+}
- let merchant_account = db
- .find_merchant_account_by_merchant_id(&merchant_id, &key_store)
- .await?;
+#[cfg(feature = "v1")]
+trait ForwardCompatState {}
- let payment_method = db
- .find_payment_method(
- &key_store,
- &tracking_data.payment_method_id,
- merchant_account.storage_scheme,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch payment method for modular compatibility PT")?;
+#[cfg(feature = "v1")]
+trait ForwardCompatTransitionTo<S: ForwardCompatState> {}
- // Step 2: Populate v1 compat fields used by PM modular service.
- let pm_id_update = storage::PaymentMethodUpdate::PopulateModularCompatFields {
- id: tracking_data.payment_method_id.clone(),
- payment_method_type_v2: payment_method.payment_method,
- payment_method_subtype: payment_method.payment_method_type,
- last_modified_by: tracking_data.last_modified_by.clone(),
- };
+#[cfg(feature = "v1")]
+struct ForwardCompatStarted;
+#[cfg(feature = "v1")]
+struct ForwardTrackingLoaded;
+#[cfg(feature = "v1")]
+struct ForwardContextLoaded;
+#[cfg(feature = "v1")]
+struct ForwardPaymentMethodLoaded;
+#[cfg(feature = "v1")]
+struct ForwardDbCompatPrepared;
+#[cfg(feature = "v1")]
+struct ForwardLockerCompatApplied;
- let payment_method = db
- .update_payment_method(
- &key_store,
- payment_method,
- pm_id_update,
- merchant_account.storage_scheme,
+#[cfg(feature = "v1")]
+impl ForwardCompatState for ForwardCompatStarted {}
+#[cfg(feature = "v1")]
+impl ForwardCompatState for ForwardTrackingLoaded {}
+#[cfg(feature = "v1")]
+impl ForwardCompatState for ForwardContextLoaded {}
+#[cfg(feature = "v1")]
+impl ForwardCompatState for ForwardPaymentMethodLoaded {}
+#[cfg(feature = "v1")]
+impl ForwardCompatState for ForwardDbCompatPrepared {}
+#[cfg(feature = "v1")]
+impl ForwardCompatState for ForwardLockerCompatApplied {}
+
+#[cfg(feature = "v1")]
+impl ForwardCompatTransitionTo<ForwardTrackingLoaded> for ForwardCompatStarted {}
+#[cfg(feature = "v1")]
+impl ForwardCompatTransitionTo<ForwardContextLoaded> for ForwardTrackingLoaded {}
+#[cfg(feature = "v1")]
+impl ForwardCompatTransitionTo<ForwardPaymentMethodLoaded> for ForwardContextLoaded {}
+#[cfg(feature = "v1")]
+impl ForwardCompatTransitionTo<ForwardDbCompatPrepared> for ForwardPaymentMethodLoaded {}
+#[cfg(feature = "v1")]
+impl ForwardCompatTransitionTo<ForwardLockerCompatApplied> for ForwardDbCompatPrepared {}
+
+#[cfg(feature = "v1")]
+impl<S: ForwardCompatState> ForwardCompatWorkflowBuilder<S> {
+ fn transition<T: ForwardCompatState>(self) -> ForwardCompatWorkflowBuilder<T>
+ where
+ S: ForwardCompatTransitionTo<T>,
+ {
+ ForwardCompatWorkflowBuilder {
+ _state: PhantomData,
+ tracking_data: self.tracking_data,
+ merchant_id: self.merchant_id,
+ key_store: self.key_store,
+ merchant_account: self.merchant_account,
+ payment_method: self.payment_method,
+ updates: self.updates,
+ }
+ }
+
+ fn tracking_data(&self) -> errors::RouterResult<&PaymentMethodModularCompatTrackingData> {
+ self.tracking_data
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("tracking data must be loaded in forward compatibility workflow")
+ }
+
+ fn merchant_id(&self) -> errors::RouterResult<&common_utils::id_type::MerchantId> {
+ self.merchant_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("merchant id must be loaded in forward compatibility workflow")
+ }
+
+ fn key_store(&self) -> errors::RouterResult<&domain::MerchantKeyStore> {
+ self.key_store
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("merchant key store must be loaded in forward compatibility workflow")
+ }
+
+ fn merchant_account(&self) -> errors::RouterResult<&domain::MerchantAccount> {
+ self.merchant_account
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("merchant account must be loaded in forward compatibility workflow")
+ }
+
+ fn payment_method(&self) -> errors::RouterResult<&domain::PaymentMethod> {
+ self.payment_method
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("payment method must be loaded in forward compatibility workflow")
+ }
+
+ fn updates(&self) -> errors::RouterResult<&ForwardCompatUpdates> {
+ self.updates
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("updates must be prepared in forward compatibility workflow")
+ }
+
+ fn updates_mut(&mut self) -> errors::RouterResult<&mut ForwardCompatUpdates> {
+ self.updates
+ .as_mut()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("updates must be prepared in forward compatibility workflow")
+ }
+}
+
+#[cfg(feature = "v1")]
+impl ForwardCompatWorkflowBuilder<ForwardCompatStarted> {
+ fn new() -> Self {
+ Self {
+ _state: PhantomData,
+ tracking_data: None,
+ merchant_id: None,
+ key_store: None,
+ merchant_account: None,
+ payment_method: None,
+ updates: None,
+ }
+ }
+
+ fn load_tracking_data(
+ mut self,
+ tracking_data: PaymentMethodModularCompatTrackingData,
+ ) -> ForwardCompatWorkflowBuilder<ForwardTrackingLoaded> {
+ self.merchant_id = Some(tracking_data.merchant_id.clone());
+ self.tracking_data = Some(tracking_data);
+ self.transition()
+ }
+}
+
+#[cfg(feature = "v1")]
+impl ForwardCompatWorkflowBuilder<ForwardTrackingLoaded> {
+ fn load_context(
+ mut self,
+ key_store: domain::MerchantKeyStore,
+ merchant_account: domain::MerchantAccount,
+ ) -> ForwardCompatWorkflowBuilder<ForwardContextLoaded> {
+ self.key_store = Some(key_store);
+ self.merchant_account = Some(merchant_account);
+ self.transition()
+ }
+}
+
+#[cfg(feature = "v1")]
+impl ForwardCompatWorkflowBuilder<ForwardContextLoaded> {
+ fn load_payment_method(
+ mut self,
+ payment_method: domain::PaymentMethod,
+ ) -> ForwardCompatWorkflowBuilder<ForwardPaymentMethodLoaded> {
+ self.payment_method = Some(payment_method);
+ self.transition()
+ }
+}
+
+#[cfg(feature = "v1")]
+impl ForwardCompatWorkflowBuilder<ForwardPaymentMethodLoaded> {
+ fn is_complete(&self) -> errors::RouterResult<bool> {
+ let payment_method = self.payment_method()?;
+ // TODO: Revisit the version check once payment method version follows customer version.
+ Ok(payment_method.version == common_enums::ApiVersion::V2
+ && payment_method.compatibility_updated_at == Some(payment_method.last_modified))
+ }
+
+ fn prepare_db_compat(
+ mut self,
+ ) -> errors::RouterResult<ForwardCompatWorkflowBuilder<ForwardDbCompatPrepared>> {
+ let connector_mandate_details =
+ diesel_models::payment_method::CommonMandateReference::parse_connector_mandate_compat_details(
+ self.payment_method()?.connector_mandate_details.clone(),
)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to populate id for payment method in modular compatibility PT",
- )?;
+ .map(diesel_models::payment_method::CommonMandateReference::add_v2_connector_mandate_fields);
+ self.updates = Some(ForwardCompatUpdates {
+ connector_mandate_details,
+ ..Default::default()
+ });
+ Ok(self.transition())
+ }
+}
- let business_status = if payment_method.payment_method
- != Some(common_enums::PaymentMethod::Card)
- {
- // Step 3: Non-card payment methods do not require locker migration.
- crate::logger::info!(
- process_id=%process.id,
- payment_method_id=%payment_method.payment_method_id,
- "Payment method is non-card; skipping locker migration in modular compatibility PT"
- );
- "COMPLETED_BY_PT"
- } else {
+#[cfg(feature = "v1")]
+impl ForwardCompatWorkflowBuilder<ForwardDbCompatPrepared> {
+ async fn apply_locker_compat(
+ mut self,
+ state: &SessionState,
+ process_id: &str,
+ ) -> Result<ForwardCompatWorkflowBuilder<ForwardLockerCompatApplied>, errors::ProcessTrackerError>
+ {
+ let merchant_id = self.merchant_id()?.clone();
+ let payment_method = self.payment_method()?.clone();
+
+ if payment_method.payment_method == Some(common_enums::PaymentMethod::Card) {
let customer_id = payment_method
.customer_id
.clone()
@@ -106,7 +247,6 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularForwardCompatW
.as_ref()
.and_then(|scheme| common_enums::CardNetwork::from_str(scheme).ok());
- // Step 4: Fetch card payload from legacy locker only when locker_id is present.
if let Some(card_reference) = payment_method.locker_id.clone() {
let locker_card =
cards::get_card_from_vault(state, &customer_id, &merchant_id, &card_reference)
@@ -120,68 +260,48 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularForwardCompatW
locker_card.get_card(),
card_network.clone(),
));
- let pmd =
- hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card_detail);
-
- // Step 5: Upsert the card into generic locker via direct AddVault call.
-
- let should_trigger_fingerprint_migration =
- payment_method_utils::get_should_trigger_fingerprint_migration(
- state,
- None,
- hyperswitch_domain_models::platform::ProviderMerchantId::new(
- merchant_id.clone(),
- ),
- )
- .await;
-
- let payload = cards::encode_add_vault_request(
- should_trigger_fingerprint_migration,
- merchant_id.clone(),
- &customer_id,
- pmd,
- state.conf.locker.ttl_for_storage_in_secs,
- Some(domain::VaultId::generate(card_reference.clone())),
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to add payment method in generic locker in compatibility PT",
- )?;
-
- let query_params =
- Some(pm_types::VaultQueryParam::from(pm_types::WriteMode::Upsert));
+ let pmd = hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(
+ card_detail.clone(),
+ );
- let resp =
- vault::call_to_vault::<pm_types::AddVault>(state, payload, query_params, None)
- .await
- .change_context(errors::VaultError::VaultAPIError)
- .attach_printable("Call to vault failed")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to add payment method in generic locker in compatibility PT",
- )?;
+ let customer_id_key = customer_id.get_string_repr().to_owned();
+ let locker_fingerprint_id = Self::get_vault_fingerprint_id(
+ state,
+ customer_id_key.clone(),
+ pmd.to_fingerprint_data(),
+ )
+ .await?;
+ let auxiliary_fingerprint_id = Self::get_vault_fingerprint_id(
+ state,
+ customer_id_key,
+ pmd.to_auxiliary_fingerprint_data(),
+ )
+ .await?;
- let _stored_pm_resp =
- cards::parse_add_vault_response(should_trigger_fingerprint_migration, resp)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to add payment method in generic locker in compatibility PT",
- )?;
+ self.updates_mut()?.locker_fingerprint_id = Some(locker_fingerprint_id);
+ self.updates_mut()?.auxiliary_fingerprint_id = Some(auxiliary_fingerprint_id);
+ Self::upsert_payment_method_to_generic_vault(
+ state,
+ &merchant_id,
+ &customer_id,
+ domain::VaultId::generate(card_reference),
+ &pmd,
+ )
+ .await?;
logger::info!(
- process_id=%process.id,
+ process_id=%process_id,
payment_method_id=%payment_method.payment_method_id,
"Upserted card into generic locker in modular compatibility PT"
);
} else {
logger::info!(
- process_id=%process.id,
+ process_id=%process_id,
payment_method_id=%payment_method.payment_method_id,
"Skipping card migration in modular compatibility PT as locker_id is absent"
);
}
- // Step 6: Migrate network token to generic locker when an NT locker id is present.
if let Some(network_token_locker_id) = payment_method.network_token_locker_id.clone() {
let locker_network_token = cards::get_card_from_vault(
state,
@@ -213,82 +333,245 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularForwardCompatW
let network_token_pmd =
hyperswitch_domain_models::vault::PaymentMethodVaultingData::NetworkToken(
- network_token_details.clone(),
- );
-
- let network_token_entity_id =
- hyperswitch_domain_models::vault::V1VaultEntityId::new(
- key_store.merchant_id.clone(),
- customer_id,
+ network_token_details,
);
- let network_token_payload = pm_types::AddVaultRequest {
- entity_id: network_token_entity_id,
- vault_id: domain::VaultId::generate(network_token_locker_id.clone()),
- data: &network_token_pmd,
- ttl: state.conf.locker.ttl_for_storage_in_secs,
- }
- .encode_to_vec()
- .change_context(errors::VaultError::RequestEncodingFailed)
- .attach_printable("Failed to encode AddVaultRequest for network token")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to add network token in generic locker in compatibility PT",
- )?;
-
- let network_token_query_params =
- Some(pm_types::VaultQueryParam::from(pm_types::WriteMode::Upsert));
-
- let network_token_resp = vault::call_to_vault::<pm_types::AddVault>(
+ Self::upsert_payment_method_to_generic_vault(
state,
- network_token_payload,
- network_token_query_params,
- None,
+ &merchant_id,
+ &customer_id,
+ domain::VaultId::generate(network_token_locker_id),
+ &network_token_pmd,
)
- .await
- .change_context(errors::VaultError::VaultAPIError)
- .attach_printable("Call to vault failed for network token")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to add network token in generic locker in compatibility PT",
- )?;
+ .await?;
- let _stored_network_token_resp: pm_types::InternalAddVaultResponse =
- network_token_resp
- .parse_struct("InternalAddVaultResponse")
- .change_context(errors::VaultError::ResponseDeserializationFailed)
- .attach_printable(
- "Failed to parse network token response into InternalAddVaultResponse",
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to add network token in generic locker in compatibility PT",
- )?;
-
- crate::logger::info!(
- process_id=%process.id,
+ logger::info!(
+ process_id=%process_id,
payment_method_id=%payment_method.payment_method_id,
"Upserted network token into generic locker in modular compatibility PT"
);
} else {
- crate::logger::info!(
- process_id=%process.id,
+ logger::info!(
+ process_id=%process_id,
payment_method_id=%payment_method.payment_method_id,
"Skipping network token migration in modular compatibility PT as network_token_locker_id is absent"
);
}
+ } else {
+ logger::info!(
+ process_id=%process_id,
+ payment_method_id=%payment_method.payment_method_id,
+ "Payment method is non-card; skipping locker migration in modular compatibility PT"
+ );
+ }
+
+ Ok(self.transition())
+ }
+
+ async fn get_vault_fingerprint_id(
+ state: &SessionState,
+ key: String,
+ data: impl serde::Serialize,
+ ) -> Result<String, errors::ProcessTrackerError> {
+ let data = serde_json::to_string(&data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to serialize vault fingerprint data")?;
+
+ let payload = ForwardCompatVaultFingerprintRequest { data, key }
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)
+ .attach_printable("Failed to encode VaultFingerprintRequest")
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
+ let resp =
+ vault::call_to_vault::<pm_types::GetVaultFingerprint>(state, payload, None, None)
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Call to vault failed")
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
+ let fingerprint_resp: pm_types::VaultFingerprintResponse = resp
+ .parse_struct("VaultFingerprintResponse")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed to parse data into VaultFingerprintResponse")
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
+ Ok(fingerprint_resp.fingerprint_id)
+ }
+
+ async fn upsert_payment_method_to_generic_vault(
+ state: &SessionState,
+ merchant_id: &common_utils::id_type::MerchantId,
+ customer_id: &common_utils::id_type::CustomerId,
+ vault_id: domain::VaultId,
+ data: &hyperswitch_domain_models::vault::PaymentMethodVaultingData,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ let should_trigger_fingerprint_migration =
+ payment_method_utils::get_should_trigger_fingerprint_migration(
+ state,
+ Some(customer_id),
+ hyperswitch_domain_models::platform::ProviderMerchantId::new(merchant_id.clone()),
+ )
+ .await;
+
+ let payload = cards::encode_add_vault_request(
+ should_trigger_fingerprint_migration,
+ merchant_id.clone(),
+ customer_id,
+ data.clone(),
+ state.conf.locker.ttl_for_storage_in_secs,
+ Some(vault_id.clone()),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in generic locker in compatibility PT")?;
+
+ let query_params = Some(pm_types::VaultQueryParam::from(pm_types::WriteMode::Upsert));
+
+ let resp = vault::call_to_vault::<pm_types::AddVault>(state, payload, query_params, None)
+ .await
+ .change_context(errors::VaultError::VaultAPIError)
+ .attach_printable("Call to vault failed")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to add payment method in generic locker in compatibility PT",
+ )?;
+
+ let returned_vault_id =
+ cards::parse_add_vault_response(should_trigger_fingerprint_migration, resp)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to add payment method in generic locker in compatibility PT",
+ )?;
+
+ if returned_vault_id.get_string_repr() != vault_id.get_string_repr() {
+ Err(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| {
+ format!(
+ "Generic locker returned vault ID {} for requested vault ID {}",
+ returned_vault_id.get_string_repr(),
+ vault_id.get_string_repr()
+ )
+ })?;
+ }
+
+ Ok(())
+ }
+}
+
+#[cfg(feature = "v1")]
+impl ForwardCompatWorkflowBuilder<ForwardLockerCompatApplied> {
+ async fn mark_complete(
+ self,
+ db: &dyn StorageInterface,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ let tracking_data = self.tracking_data()?;
+ let payment_method = self.payment_method()?;
+ let updates = self.updates()?;
- "COMPLETED_BY_PT"
+ let pm_update = storage::PaymentMethodUpdate::PopulateModularCompatFields {
+ id: tracking_data.payment_method_id.clone(),
+ payment_method_type_v2: payment_method.payment_method,
+ payment_method_subtype: payment_method.payment_method_type,
+ connector_mandate_details: updates
+ .connector_mandate_details
+ .clone()
+ .and_then(|connector_mandate_details| connector_mandate_details.into_value()),
+ locker_fingerprint_id: updates.locker_fingerprint_id.clone(),
+ auxiliary_fingerprint_id: updates.auxiliary_fingerprint_id.clone(),
+ last_modified_by: tracking_data.last_modified_by.clone(),
};
- // Step 7: Mark process as completed once the required branch is done.
- db.as_scheduler()
- .finish_process_with_business_status(process, business_status)
+ db.update_payment_method(
+ self.key_store()?,
+ payment_method.clone(),
+ pm_update,
+ self.merchant_account()?.storage_scheme,
+ // Forward compat completion update must not recursively enqueue another compat PT.
+ None,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to populate modular fields for payment method in compatibility PT",
+ )?;
+
+ Ok(())
+ }
+}
+
+#[cfg(feature = "v1")]
+#[derive(Debug, serde::Serialize)]
+struct ForwardCompatVaultFingerprintRequest {
+ data: String,
+ key: String,
+}
+
+#[async_trait::async_trait]
+impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularForwardCompatWorkflow {
+ #[cfg(feature = "v1")]
+ async fn execute_workflow<'a>(
+ &'a self,
+ state: &'a SessionState,
+ process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ logger::info!(process_id=%process.id, "Starting payment method modular compatibility PT");
+ let db = &*state.store;
+ let tracking_data: PaymentMethodModularCompatTrackingData =
+ process
+ .tracking_data
+ .clone()
+ .parse_value("PaymentMethodModularCompatTrackingData")?;
+ logger::info!(process_id=%process.id, ?tracking_data, "Parsed modular compatibility PT tracking data");
+ let workflow = ForwardCompatWorkflowBuilder::new().load_tracking_data(tracking_data);
+
+ let merchant_id = workflow.merchant_id()?.clone();
+ let key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ &merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
.await?;
- crate::logger::info!(
- business_status,
- "Finished payment method modular compatibility PT"
- );
+
+ let merchant_account = db
+ .find_merchant_account_by_merchant_id(&merchant_id, &key_store)
+ .await?;
+ let workflow = workflow.load_context(key_store, merchant_account);
+
+ let payment_method = db
+ .find_payment_method(
+ workflow.key_store()?,
+ &workflow.tracking_data()?.payment_method_id,
+ workflow.merchant_account()?.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch payment method for modular compatibility PT")?;
+ let workflow = workflow.load_payment_method(payment_method);
+
+ if workflow.is_complete()? {
+ db.as_scheduler()
+ .finish_process_with_business_status(process, "COMPLETED_BY_PT")
+ .await?;
+ crate::logger::info!(
+ business_status = "COMPLETED_BY_PT",
+ "Finished payment method modular compatibility PT; already forward compatible"
+ );
+ } else {
+ workflow
+ .prepare_db_compat()?
+ .apply_locker_compat(state, &process.id)
+ .await?
+ .mark_complete(db)
+ .await?;
+
+ db.as_scheduler()
+ .finish_process_with_business_status(process, "COMPLETED_BY_PT")
+ .await?;
+ crate::logger::info!(
+ business_status = "COMPLETED_BY_PT",
+ "Finished payment method modular compatibility PT"
+ );
+ }
Ok(())
}
diff --git a/crates/router/src/workflows/payment_method_status_update.rs b/crates/router/src/workflows/payment_method_status_update.rs
index ebc3dbf0ea..185a886f76 100644
--- a/crates/router/src/workflows/payment_method_status_update.rs
+++ b/crates/router/src/workflows/payment_method_status_update.rs
@@ -69,6 +69,8 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow
payment_method,
pm_update,
merchant_account.storage_scheme,
+ // Status update workflow completion must not recursively enqueue PM modular compat.
+ None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rs
index 8ca5c9d861..e7c697b5bf 100644
--- a/crates/storage_impl/src/payment_method.rs
+++ b/crates/storage_impl/src/payment_method.rs
@@ -15,7 +15,9 @@ use hyperswitch_domain_models::platform::Initiator;
use hyperswitch_domain_models::{
behaviour::Conversion,
merchant_key_store::MerchantKeyStore,
- payment_methods::{PaymentMethod as DomainPaymentMethod, PaymentMethodInterface},
+ payment_methods::{
+ PaymentMethod as DomainPaymentMethod, PaymentMethodCompatAction, PaymentMethodInterface,
+ },
};
use router_env::{instrument, tracing};
@@ -149,9 +151,10 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
storage_scheme: MerchantStorageScheme,
+ compat_action: Option<PaymentMethodCompatAction>,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
self.router_store
- .insert_payment_method(key_store, payment_method, storage_scheme)
+ .insert_payment_method(key_store, payment_method, storage_scheme, compat_action)
.await
}
@@ -162,6 +165,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
storage_scheme: MerchantStorageScheme,
+ compat_action: Option<PaymentMethodCompatAction>,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_write(self).await?;
let mut payment_method_new = payment_method
@@ -190,20 +194,27 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
.change_context(errors::StorageError::KVError)
.attach_printable("Failed to generate payment method insert query")?;
- self.insert_resource(
- key_store,
- storage_scheme,
- payment_method_new.clone().insert(&conn),
- payment_method,
- InsertResourceParams {
- drainer_query,
- reverse_lookups,
- key,
- identifier,
- resource_type: "payment_method",
- },
- )
- .await
+ let payment_method: DomainPaymentMethod = self
+ .insert_resource(
+ key_store,
+ storage_scheme,
+ payment_method_new.clone().insert(&conn),
+ payment_method,
+ InsertResourceParams {
+ drainer_query,
+ reverse_lookups,
+ key,
+ identifier,
+ resource_type: "payment_method",
+ },
+ )
+ .await?;
+
+ if let Some(compat_action) = compat_action {
+ compat_action.execute(&payment_method).await;
+ }
+
+ Ok(payment_method)
}
#[cfg(feature = "v1")]
@@ -214,6 +225,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
payment_method: DomainPaymentMethod,
payment_method_update: PaymentMethodUpdate,
storage_scheme: MerchantStorageScheme,
+ compat_action: Option<PaymentMethodCompatAction>,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method = Conversion::convert(payment_method)
.await
@@ -242,7 +254,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
.change_context(errors::StorageError::KVError)
.attach_printable("Failed to generate payment method update query")?;
- Box::pin(
+ let payment_method: DomainPaymentMethod = Box::pin(
self.update_resource(
key_store,
storage_scheme,
@@ -260,7 +272,13 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
},
),
)
- .await
+ .await?;
+
+ if let Some(compat_action) = compat_action {
+ compat_action.execute(&payment_method).await;
+ }
+
+ Ok(payment_method)
}
#[cfg(feature = "v2")]
@@ -271,6 +289,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
payment_method: DomainPaymentMethod,
payment_method_update: PaymentMethodUpdate,
storage_scheme: MerchantStorageScheme,
+ compat_action: Option<PaymentMethodCompatAction>,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
self.router_store
.update_payment_method(
@@ -278,6 +297,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
payment_method,
payment_method_update,
storage_scheme,
+ compat_action,
)
.await
}
@@ -586,6 +606,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
_storage_scheme: MerchantStorageScheme,
+ compat_action: Option<PaymentMethodCompatAction>,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method_new = payment_method
.construct_new()
@@ -593,8 +614,15 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
.change_context(errors::StorageError::DecryptionError)?;
let conn = pg_connection_write(self).await?;
- self.call_database(key_store, payment_method_new.insert(&conn))
- .await
+ let payment_method: DomainPaymentMethod = self
+ .call_database(key_store, payment_method_new.insert(&conn))
+ .await?;
+
+ if let Some(compat_action) = compat_action {
+ compat_action.execute(&payment_method).await;
+ }
+
+ Ok(payment_method)
}
#[cfg(feature = "v1")]
@@ -605,17 +633,25 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
payment_method: DomainPaymentMethod,
payment_method_update: PaymentMethodUpdate,
_storage_scheme: MerchantStorageScheme,
+ compat_action: Option<PaymentMethodCompatAction>,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method = Conversion::convert(payment_method)
.await
.change_context(errors::StorageError::DecryptionError)?;
let conn = pg_connection_write(self).await?;
- self.call_database(
- key_store,
- payment_method.update_with_payment_method_id(&conn, payment_method_update.into()),
- )
- .await
+ let payment_method: DomainPaymentMethod = self
+ .call_database(
+ key_store,
+ payment_method.update_with_payment_method_id(&conn, payment_method_update.into()),
+ )
+ .await?;
+
+ if let Some(compat_action) = compat_action {
+ compat_action.execute(&payment_method).await;
+ }
+
+ Ok(payment_method)
}
#[cfg(feature = "v2")]
@@ -626,16 +662,24 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
payment_method: DomainPaymentMethod,
payment_method_update: PaymentMethodUpdate,
_storage_scheme: MerchantStorageScheme,
+ compat_action: Option<PaymentMethodCompatAction>,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method = Conversion::convert(payment_method)
.await
.change_context(errors::StorageError::DecryptionError)?;
let conn = pg_connection_write(self).await?;
- self.call_database(
- key_store,
- payment_method.update_with_id(&conn, payment_method_update.into()),
- )
- .await
+ let payment_method: DomainPaymentMethod = self
+ .call_database(
+ key_store,
+ payment_method.update_with_id(&conn, payment_method_update.into()),
+ )
+ .await?;
+
+ if let Some(compat_action) = compat_action {
+ compat_action.execute(&payment_method).await;
+ }
+
+ Ok(payment_method)
}
#[cfg(feature = "v1")]
@@ -943,6 +987,7 @@ impl PaymentMethodInterface for MockDb {
_key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
_storage_scheme: MerchantStorageScheme,
+ compat_action: Option<PaymentMethodCompatAction>,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let mut payment_methods = self.payment_methods.lock().await;
@@ -951,6 +996,9 @@ impl PaymentMethodInterface for MockDb {
.change_context(errors::StorageError::DecryptionError)?;
payment_methods.push(pm);
+ if let Some(compat_action) = compat_action {
+ compat_action.execute(&payment_method).await;
+ }
Ok(payment_method)
}
@@ -1116,6 +1164,7 @@ impl PaymentMethodInterface for MockDb {
payment_method: DomainPaymentMethod,
payment_method_update: PaymentMethodUpdate,
_storage_scheme: MerchantStorageScheme,
+ compat_action: Option<PaymentMethodCompatAction>,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method_updated = PaymentMethodUpdateInternal::from(payment_method_update)
.apply_changeset(
@@ -1123,14 +1172,21 @@ impl PaymentMethodInterface for MockDb {
.await
.change_context(errors::StorageError::EncryptionError)?,
);
- self.update_resource::<PaymentMethod, _>(
- key_store,
- self.payment_methods.lock().await,
- payment_method_updated,
- |pm| pm.get_id() == payment_method.get_id(),
- "cannot update payment method".to_string(),
- )
- .await
+ let payment_method: DomainPaymentMethod = self
+ .update_resource::<PaymentMethod, _>(
+ key_store,
+ self.payment_methods.lock().await,
+ payment_method_updated,
+ |pm| pm.get_id() == payment_method.get_id(),
+ "cannot update payment method".to_string(),
+ )
+ .await?;
+
+ if let Some(compat_action) = compat_action {
+ compat_action.execute(&payment_method).await;
+ }
+
+ Ok(payment_method)
}
#[cfg(feature = "v2")]
diff --git a/migrations/2026-05-27-000001_add_auxiliary_fingerprint_id_to_payment_methods/down.sql b/migrations/2026-05-27-000001_add_auxiliary_fingerprint_id_to_payment_methods/down.sql
new file mode 100644
index 0000000000..21e6f2f926
--- /dev/null
+++ b/migrations/2026-05-27-000001_add_auxiliary_fingerprint_id_to_payment_methods/down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE payment_methods
+ DROP COLUMN IF EXISTS auxiliary_fingerprint_id;
diff --git a/migrations/2026-05-27-000001_add_auxiliary_fingerprint_id_to_payment_methods/up.sql b/migrations/2026-05-27-000001_add_auxiliary_fingerprint_id_to_payment_methods/up.sql
new file mode 100644
index 0000000000..707be9e69f
--- /dev/null
+++ b/migrations/2026-05-27-000001_add_auxiliary_fingerprint_id_to_payment_methods/up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE payment_methods
+ ADD COLUMN IF NOT EXISTS auxiliary_fingerprint_id VARCHAR(64);
diff --git a/v2_compatible_migrations/2026-05-06-140219-0000_add-auxiliary-fingerprint/down.sql b/v2_compatible_migrations/2026-05-06-140219-0000_add-auxiliary-fingerprint/down.sql
deleted file mode 100644
index 7be3fbeadb..0000000000
--- a/v2_compatible_migrations/2026-05-06-140219-0000_add-auxiliary-fingerprint/down.sql
+++ /dev/null
@@ -1,2 +0,0 @@
--- This file should undo anything in `up.sql`
-Alter table payment_methods drop column auxiliary_fingerprint_id;
\ No newline at end of file
diff --git a/v2_compatible_migrations/2026-05-06-140219-0000_add-auxiliary-fingerprint/up.sql b/v2_compatible_migrations/2026-05-06-140219-0000_add-auxiliary-fingerprint/up.sql
deleted file mode 100644
index 4fbd3317ad..0000000000
--- a/v2_compatible_migrations/2026-05-06-140219-0000_add-auxiliary-fingerprint/up.sql
+++ /dev/null
@@ -1,2 +0,0 @@
--- Your SQL goes here
-Alter table payment_methods add column auxiliary_fingerprint_id varchar(64);
\ No newline at end of file