Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(payment-methods): backwards compatibility for payments flow (#12205)
Kashif76f9af1fa086
diff --git a/config/superposition_seed.toml b/config/superposition_seed.tomlindex b7e83d48be..10b780bb1a 100644--- a/config/superposition_seed.toml+++ b/config/superposition_seed.toml@@ -145,6 +145,12 @@ schema = { type = "boolean" }description = "Whether to schedule PM modular forward compatibility PT for a merchant"change_reason = "Initial setup"+[default-configs.should_schedule_modular_backward_compat]+value = false+schema = { type = "boolean" }+description = "Whether to schedule PM modular backward compatibility PT for a merchant"+change_reason = "Initial setup"+[default-configs.should_return_raw_payment_method_details]value = falseschema = { type = "boolean" }diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex bc833d8c34..c73f86dd45 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -10731,6 +10731,7 @@ pub enum ProcessTrackerRunner {AttachPayoutAccountWorkflow,PaymentMethodStatusUpdateWorkflow,PaymentMethodModularForwardCompatWorkflow,+ PaymentMethodModularBackwardCompatWorkflow,PassiveRecoveryWorkflow,ProcessDisputeWorkflow,DisputeListWorkflow,diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rsindex 374cef2a02..0f645cc40e 100644--- a/crates/diesel_models/src/payment_method.rs+++ b/crates/diesel_models/src/payment_method.rs@@ -76,7 +76,7 @@ pub struct PaymentMethod {pub payment_method_type_v2: Option<storage_enums::PaymentMethod>,// Compatibility-only field: backfilled by modular-compat PT for v2 interoperability.// Do not use this column in v1 business logic.- pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,+ pub payment_method_subtype: Option<String>,pub network_transaction_link_id: Option<String>,}@@ -320,6 +320,13 @@ pub enum PaymentMethodUpdate {payment_method_subtype: Option<storage_enums::PaymentMethodType>,last_modified_by: Option<String>,},+ // Compatibility-only update used by modular backward-compat PT.+ // Do not use this for normal v1 payment method updates.+ PopulateLegacyCompatFields {+ payment_method: Option<storage_enums::PaymentMethod>,+ payment_method_type: Option<storage_enums::PaymentMethodType>,+ last_modified_by: Option<String>,+ },}#[cfg(feature = "v2")]@@ -587,7 +594,9 @@ impl PaymentMethodUpdateInternal {network_tokenization_data: network_tokenization_data.or(source.network_tokenization_data),payment_method_type_v2: payment_method_type_v2.or(source.payment_method_type_v2),- payment_method_subtype: payment_method_subtype.or(source.payment_method_subtype),+ payment_method_subtype: payment_method_subtype+ .map(|payment_method_subtype| payment_method_subtype.to_string())+ .or(source.payment_method_subtype),id: id.or(source.id),}}@@ -960,6 +969,35 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {payment_method_subtype,id: Some(id),},+ PaymentMethodUpdate::PopulateLegacyCompatFields {+ payment_method,+ payment_method_type,+ 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,+ },}}}diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rsindex 51c8dde8c0..c4787ac3b4 100644--- a/crates/hyperswitch_domain_models/src/payment_methods.rs+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs@@ -615,6 +615,24 @@ impl super::behaviour::Conversion for PaymentMethod {item.vault_type,item.external_vault_source,))?;+ let payment_method_subtype =+ item.payment_method_subtype+ .and_then(|payment_method_subtype| {+ if payment_method_subtype.eq_ignore_ascii_case("card") {+ None+ } else {+ payment_method_subtype+ .parse::<storage_enums::PaymentMethodType>()+ .map_err(|error| {+ logger::warn!(+ ?error,+ payment_method_subtype,+ "Failed to parse payment_method_subtype compatibility field"+ );+ })+ .ok()+ }+ });// Construct the domain type// Storage always has customer_id, wrap in Some for domain@@ -634,8 +652,8 @@ impl super::behaviour::Conversion for PaymentMethod {direct_debit_token: item.direct_debit_token,created_at: item.created_at,last_modified: item.last_modified,- payment_method: item.payment_method,- payment_method_type: item.payment_method_type,+ payment_method: item.payment_method.or(item.payment_method_type_v2),+ payment_method_type: item.payment_method_type.or(payment_method_subtype),payment_method_issuer: item.payment_method_issuer,payment_method_issuer_code: item.payment_method_issuer_code,metadata: item.metadata,diff --git a/crates/payment_methods/src/client/retrieve.rs b/crates/payment_methods/src/client/retrieve.rsindex aafcad9150..cf87f95af0 100644--- a/crates/payment_methods/src/client/retrieve.rs+++ b/crates/payment_methods/src/client/retrieve.rs@@ -27,7 +27,7 @@ pub struct RetrievePaymentMethodResponse {pub merchant_id: id_type::MerchantId,pub customer_id: Option<id_type::CustomerId>,pub payment_method: common_enums::PaymentMethod,- pub payment_method_type: common_enums::PaymentMethodType,+ pub payment_method_type: Option<common_enums::PaymentMethodType>,pub recurring_enabled: Option<bool>,pub created: Option<PrimitiveDateTime>,pub last_used_at: Option<PrimitiveDateTime>,diff --git a/crates/payment_methods/src/client/update.rs b/crates/payment_methods/src/client/update.rsindex 9c23dc27cc..6b8c0b572b 100644--- a/crates/payment_methods/src/client/update.rs+++ b/crates/payment_methods/src/client/update.rs@@ -98,7 +98,7 @@ pub struct UpdatePaymentMethodResponse {/// The type of payment method.pub payment_method_type: PaymentMethod,/// The payment method subtype.- pub payment_method_subtype: PaymentMethodType,+ pub payment_method_subtype: Option<PaymentMethodType>,/// Indicates whether recurring is enabled.pub recurring_enabled: Option<bool>,/// Timestamp for creation time.diff --git a/crates/payment_methods/src/types.rs b/crates/payment_methods/src/types.rsindex 6d2950de10..e413247d66 100644--- a/crates/payment_methods/src/types.rs+++ b/crates/payment_methods/src/types.rs@@ -93,7 +93,7 @@ pub struct ModularPMRetrieveResponse {pub merchant_id: id_type::MerchantId,pub customer_id: Option<id_type::CustomerId>,pub payment_method_type: PaymentMethod,- pub payment_method_subtype: PaymentMethodType,+ pub payment_method_subtype: Option<PaymentMethodType>,pub recurring_enabled: Option<bool>,#[serde(default, with = "common_utils::custom_serde::iso8601::option")]pub created: Option<PrimitiveDateTime>,diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rsindex f84de3443f..0799123f3e 100644--- a/crates/router/src/bin/scheduler.rs+++ b/crates/router/src/bin/scheduler.rs@@ -340,6 +340,9 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {storage::ProcessTrackerRunner::PaymentMethodModularForwardCompatWorkflow => Ok(Box::new(workflows::payment_method_modular_forward_compat::PaymentMethodModularForwardCompatWorkflow,)),+ storage::ProcessTrackerRunner::PaymentMethodModularBackwardCompatWorkflow => Ok(Box::new(+ workflows::payment_method_modular_backward_compat::PaymentMethodModularBackwardCompatWorkflow,+ )),storage::ProcessTrackerRunner::PassiveRecoveryWorkflow => {Ok(Box::new(workflows::revenue_recovery::ExecutePcrWorkflow))}diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 4cde3fa48f..3775097e65 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -385,6 +385,9 @@ pub mod superposition {/// Schedule PM modular forward compatibility PT configuration keypub const SHOULD_SCHEDULE_MODULAR_FORWARD_COMPAT: &str ="should_schedule_modular_forward_compat";+ /// Schedule PM modular backward compatibility PT configuration key+ pub const SHOULD_SCHEDULE_MODULAR_BACKWARD_COMPAT: &str =+ "should_schedule_modular_backward_compat";/// dynamic fields configuration key for sdk configpub const DYNAMIC_FIELDS: &str = "dynamic_fields";/// payout sync tracker configuration keydiff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rsindex c46d84a480..4539f15752 100644--- a/crates/router/src/core/configs/dimension_config.rs+++ b/crates/router/src/core/configs/dimension_config.rs@@ -451,6 +451,24 @@ impl DatabaseBackedConfig for ShouldScheduleModularForwardCompat {}}+config! {+ superposition_key = SHOULD_SCHEDULE_MODULAR_BACKWARD_COMPAT,+ output = bool,+ default = false,+ requires = dimension_state::DimensionsWithProviderMerchantId,+ targeting_key = id_type::CustomerId+}++impl DatabaseBackedConfig for ShouldScheduleModularBackwardCompat {+ const KEY: &'static str = "should_schedule_modular_backward_compat";++ fn db_key(dimensions: &impl dimension_state::DimensionsBase) -> Option<String> {+ dimensions+ .get_provider_merchant_id()+ .map(|id| format!("{}_{}", Self::KEY, id.get_string_repr()))+ }+}+config! {superposition_key = PAYOUT_TRACKER_MAPPING,output = RetryMapping,diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 3444ca19a2..c6ed2348b2 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -109,8 +109,12 @@ use crate::{const PAYMENT_METHOD_STATUS_UPDATE_TASK: &str = "PAYMENT_METHOD_STATUS_UPDATE";const PAYMENT_METHOD_STATUS_TAG: &str = "PAYMENT_METHOD_STATUS";-const PAYMENT_METHOD_MODULAR_FORWARD_COMPAT_TASK: &str = "PAYMENT_METHOD_MODULAR_FORWARD_COMPAT";-const PAYMENT_METHOD_MODULAR_FORWARD_COMPAT_TAG: &str = "PAYMENT_METHOD_MODULAR_FORWARD_COMPAT";+const PAYMENT_METHOD_MODULAR_FORWARD_COMPAT_TASK: &str = "PM_MOD_FORWARD_COMPAT";+const PAYMENT_METHOD_MODULAR_FORWARD_COMPAT_TAG: &str = "PM_MOD_FORWARD_COMPAT";+#[cfg(feature = "v2")]+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";#[cfg(feature = "v2")]const PAYMENT_METHOD_REDACTED_FINGERPRINT_ID: &str = "FINGERPRINT_ID_REDACTED";@@ -561,7 +565,7 @@ pub async fn add_payment_method_modular_forward_compat_task(tracking_data,None,common_utils::date_time::now(),- common_types::consts::API_VERSION,+ common_enums::ApiVersion::V1,application_source,).change_context(errors::ApiErrorResponse::InternalServerError)@@ -582,6 +586,62 @@ pub async fn add_payment_method_modular_forward_compat_task(Ok(())}+#[cfg(feature = "v2")]+pub async fn add_payment_method_modular_backward_compat_task(+ db: &dyn StorageInterface,+ payment_method: &domain::PaymentMethod,+ merchant_id: &id_type::MerchantId,+ application_source: common_enums::ApplicationSource,+ initiator: Option<&hyperswitch_domain_models::platform::Initiator>,+) -> 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()),+ };++ 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(+ &payment_method_id,+ runner,+ task,+ );++ let process_tracker_entry = storage::ProcessTrackerNew::new(+ process_tracker_id,+ task,+ runner,+ tag,+ tracking_data,+ None,+ common_utils::date_time::now(),+ common_enums::ApiVersion::V1,+ application_source,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to construct PAYMENT_METHOD_MODULAR_BACKWARD_COMPAT process tracker task",+ )?;++ db.insert_process(process_tracker_entry)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable_lazy(|| {+ format!(+ "Failed while inserting PAYMENT_METHOD_MODULAR_BACKWARD_COMPAT task to process_tracker for payment_method_id: {}",+ payment_method_id+ )+ })?;++ Ok(())+}+#[cfg(feature = "v2")]#[allow(clippy::too_many_arguments)]#[instrument(skip_all)]@@ -2541,6 +2601,53 @@ async fn execute_payment_method_create(None,)?;+ let merchant_id = platform.get_provider().get_account().get_id().to_owned();+ let should_schedule_modular_backward_compat =+ utils::get_should_schedule_modular_backward_compat(+ state,+ &dimension_state::Dimensions::new().with_provider_merchant_id(+ platform.get_provider().get_provider_merchant_id(),+ ),+ None,+ )+ .await;++ if should_schedule_modular_backward_compat {+ let res = add_payment_method_modular_backward_compat_task(+ &*state.store,+ &payment_method,+ &merchant_id,+ state.conf.application_source,+ platform.get_initiator(),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to add payment method modular backward compatibility task in process tracker",+ );++ if let Err(err) = res {+ logger::error!(+ ?err,+ payment_method_id = %payment_method.get_id().get_string_repr(),+ merchant_id=%merchant_id.get_string_repr(),+ "Failed to schedule modular backward compatibility PT; continuing payment method create flow"+ );+ } else {+ logger::info!(+ payment_method_id = %payment_method.get_id().get_string_repr(),+ merchant_id=%merchant_id.get_string_repr(),+ "Scheduled payment method modular backward compatibility PT"+ );+ }+ } else {+ logger::debug!(+ payment_method_id = %payment_method.get_id().get_string_repr(),+ merchant_id=%merchant_id.get_string_repr(),+ "Skipping modular backward compatibility PT scheduling by config"+ );+ }+Ok((resp, payment_method))}Err(e) => {diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex c89f66a553..8b488a5aae 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -1384,7 +1384,7 @@ impl DomainPaymentMethodWrapper {token_detail.connector_id.clone(),hyperswitch_domain_models::mandates::PaymentsMandateReferenceRecord {connector_mandate_id: token_detail.token.clone().expose(),- payment_method_type: Some(response.payment_method_type),+ payment_method_type: response.payment_method_type,original_payment_authorized_amount: token_detail.original_payment_authorized_amount.map(|amount| amount.get_amount_as_i64()),@@ -1437,7 +1437,7 @@ impl DomainPaymentMethodWrapper {.last_used_at.unwrap_or_else(common_utils::date_time::now),payment_method: Some(response.payment_method),- payment_method_type: Some(response.payment_method_type),+ payment_method_type: response.payment_method_type,payment_method_issuer: None,payment_method_issuer_code: None,metadata: None,diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rsindex 6be1a4329f..dc703292fd 100644--- a/crates/router/src/core/payment_methods/utils.rs+++ b/crates/router/src/core/payment_methods/utils.rs@@ -839,6 +839,20 @@ pub async fn get_should_schedule_modular_forward_compat(.await}+pub async fn get_should_schedule_modular_backward_compat(+ state: &SessionState,+ dimensions: &dimension_state::DimensionsWithProviderMerchantId,+ customer_id: Option<&common_utils::id_type::CustomerId>,+) -> bool {+ dimensions+ .get_should_schedule_modular_backward_compat(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ customer_id,+ )+ .await+}+pub async fn get_sdk_next_action_for_payment_method_list(state: &SessionState,dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantIdAndProfileId,diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex f41b547ba4..4ff5adf539 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -1237,6 +1237,30 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for)?;if let Some(payment_method_ref) = self.get_payment_method_reference(req) {+ let payment_method_ref_to_use = match req.payment_token.as_deref() {+ Some(payment_token) if payment_token == payment_method_ref => {+ let token_data = helpers::retrieve_payment_token_data(+ state,+ payment_method_ref.to_string(),+ req.payment_method,+ )+ .await?;++ match token_data {+ 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()+ }+ _ => payment_method_ref.to_owned(),+ }+ }+ _ => payment_method_ref.to_owned(),+ };+logger::debug!("Organization is enabled for modular service, fetching payment method from PM Modular Service");@@ -1245,7 +1269,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forstate,req,platform,- payment_method_ref,+ &payment_method_ref_to_use,).await?;@@ -2322,17 +2346,27 @@ impl PaymentConfirm {.clone().and_then(|pmd| pmd.payment_method_data).map(Into::into);- let payment_method_data = match pmd {+ let mut card_token_data = match pmd {Some(domain::PaymentMethodData::CardToken(token)) => Some(token),_ => None,};+ if let Some(card_cvc) = req.card_cvc.clone() {+ if let Some(card_token_data) = card_token_data.as_mut() {+ card_token_data.card_cvc = Some(card_cvc);+ } else {+ card_token_data = Some(domain::CardToken {+ card_holder_name: None,+ card_cvc: Some(card_cvc),+ });+ }+ }let pm_info = pm_transformers::fetch_payment_method_from_modular_service(state,platform,&profile_id,payment_method_ref,- payment_method_data,+ card_token_data,).await?;logger::info!("Payment method fetched from PM Modular Service.");diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex 30982d64af..a6a9f19372 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -820,7 +820,8 @@ pub async fn list_customer_payment_method_api_client(payload,|state, auth: auth::AuthenticationData, mut req, _| {Box::pin(async move {- validate_legacy_endpoint_access(&state, &auth.platform).await?;+ // TODO: Enable it back once combined PML API is provisioned+ // validate_legacy_endpoint_access(&state, &auth.platform).await?;if let Some(client_secret) = auth.client_secret {req.client_secret = Some(client_secret);}@@ -1322,7 +1323,8 @@ pub async fn default_payment_method_set_api(&req,payload,|state, auth: auth::AuthenticationData, default_payment_method, _| async move {- validate_legacy_endpoint_access(&state, &auth.platform).await?;+ // TODO: Enable it back once combined PML API is provisioned+ // validate_legacy_endpoint_access(&state, &auth.platform).await?;cards::PmCards {state: &state,provider: auth.platform.get_provider(),diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rsindex 08b100033a..69ea6116f1 100644--- a/crates/router/src/types/payment_methods.rs+++ b/crates/router/src/types/payment_methods.rs@@ -159,6 +159,12 @@ pub struct VaultRetrieveRequest {pub vault_id: domain::VaultId,}+#[derive(Debug, serde::Deserialize, serde::Serialize)]+pub struct GenericVaultRetrieveRequest {+ pub entity_id: id_type::CustomerId,+ pub vault_id: domain::VaultId,+}+#[derive(Debug, serde::Deserialize, serde::Serialize)]pub struct VaultRetrieveResponse {pub data: hyperswitch_domain_models::vault::PaymentMethodVaultingData,diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rsindex ca0c4b2f1a..2c9d4653f5 100644--- a/crates/router/src/workflows.rs+++ b/crates/router/src/workflows.rs@@ -3,6 +3,7 @@ pub mod api_key_expiry;#[cfg(feature = "payouts")]pub mod attach_payout_account_workflow;pub mod outgoing_webhook_retry;+pub mod payment_method_modular_backward_compat;pub mod payment_method_modular_forward_compat;pub mod payment_method_status_update;pub mod payment_sync;diff --git a/crates/router/src/workflows/payment_method_modular_backward_compat.rs b/crates/router/src/workflows/payment_method_modular_backward_compat.rsnew file mode 100644index 0000000000..bfe32dfd11--- /dev/null+++ b/crates/router/src/workflows/payment_method_modular_backward_compat.rs@@ -0,0 +1,328 @@+use api_models::payment_methods::Card;+use common_utils::ext_traits::{Encode, OptionExt, StringExt, ValueExt};+use error_stack::ResultExt;+use hyperswitch_masking::PeekInterface;+use scheduler::{+ consumer::types::process_data, utils as pt_utils, workflows::ProcessTrackerWorkflow,+};++use crate::{+ core::payment_methods::{cards, transformers, vault},+ errors,+ logger::{self, error},+ routes::{app::StorageInterface, SessionState},+ types::{+ domain, payment_methods as pm_types,+ storage::{self, PaymentMethodModularCompatTrackingData},+ },+};++#[cfg(feature = "v1")]+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();++ 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(),+ };++ let updated_payment_method = db+ .update_payment_method(key_store, payment_method, pm_update, storage_scheme)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to populate legacy payment method fields in backward compatibility PT",+ )?;++ 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"+ );+ Ok(payment_method)+ }+}++#[cfg(feature = "v1")]+async fn backfill_legacy_locker_card(+ state: &SessionState,+ merchant_id: &common_utils::id_type::MerchantId,+ 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 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+ }+ 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 vault_request = pm_types::GenericVaultRetrieveRequest {+ entity_id: customer_id.clone(),+ vault_id: domain::VaultId::generate(card_reference.clone()),+ };+ let payload = vault_request+ .encode_to_vec()+ .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)+ .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(+ 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"+ );+ }+ }++ 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,+ process: storage::ProcessTracker,+ ) -> Result<(), errors::ProcessTrackerError> {+ logger::info!(process_id=%process.id, "Starting payment method modular backward 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 backward compatibility PT tracking data");++ let merchant_id = tracking_data.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?;++ let merchant_account = db+ .find_merchant_account_by_merchant_id(&merchant_id, &key_store)+ .await?;++ 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 backward compatibility PT",+ )?;++ let payment_method = backfill_legacy_db_fields(+ db,+ &key_store,+ payment_method,+ merchant_account.storage_scheme,+ &tracking_data,+ &process.id,+ )+ .await?;++ backfill_legacy_locker_card(+ state,+ &merchant_id,+ &payment_method,+ &tracking_data,+ &process.id,+ )+ .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 backward compatibility PT"+ );++ 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,+ process: storage::ProcessTracker,+ _error: errors::ProcessTrackerError,+ ) -> errors::CustomResult<(), errors::ProcessTrackerError> {+ let db = &*state.store;+ let retry_count = process.retry_count;+ let mapping = process_data::PaymentMethodsPTMapping::default();++ let time_delta = if retry_count == 0 {+ Some(mapping.default_mapping.start_after)+ } else {+ pt_utils::get_delay(retry_count + 1, &mapping.default_mapping.frequencies)+ };++ let schedule_time = pt_utils::get_time_from_delta(time_delta);++ match schedule_time {+ Some(s_time) => {+ db.as_scheduler()+ .retry_process(process, s_time)+ .await+ .map_err(Into::<errors::ProcessTrackerError>::into)?;+ }+ None => {+ db.as_scheduler()+ .finish_process_with_business_status(process, "RETRIES_EXCEEDED")+ .await+ .map_err(Into::<errors::ProcessTrackerError>::into)?;+ }+ }++ error!("Failed while executing payment method modular backward compatibility workflow");+ Ok(())+ }+}