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
refactor(paymentMethods): move all pm migration related changes to payment methods crate (#7786)
Jagan9c8cf93662ed
diff --git a/Cargo.lock b/Cargo.lockindex 39154406f6..461268f3d6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5479,16 +5479,28 @@ checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd"name = "payment_methods"version = "0.1.0"dependencies = [+ "actix-multipart",+ "actix-web","api_models","async-trait",+ "bytes 1.10.1",+ "cards",+ "common_enums",+ "common_types","common_utils",+ "csv","dyn-clone",+ "error-stack","hyperswitch_domain_models","hyperswitch_interfaces","masking",+ "rdkafka",+ "router_env",+ "scheduler","serde","serde_json","storage_impl",+ "thiserror 1.0.63",][[package]]diff --git a/crates/hyperswitch_domain_models/src/cards_info.rs b/crates/hyperswitch_domain_models/src/cards_info.rsnew file mode 100644index 0000000000..6fe3b081c2--- /dev/null+++ b/crates/hyperswitch_domain_models/src/cards_info.rs@@ -0,0 +1,20 @@+use common_utils::errors;+use diesel_models::cards_info;++#[async_trait::async_trait]+pub trait CardsInfoInterface {+ type Error;+ async fn get_card_info(+ &self,+ _card_iin: &str,+ ) -> errors::CustomResult<Option<cards_info::CardInfo>, Self::Error>;+ async fn add_card_info(+ &self,+ data: cards_info::CardInfo,+ ) -> errors::CustomResult<cards_info::CardInfo, Self::Error>;+ async fn update_card_info(+ &self,+ card_iin: String,+ data: cards_info::UpdateCardInfo,+ ) -> errors::CustomResult<cards_info::CardInfo, Self::Error>;+}diff --git a/crates/hyperswitch_domain_models/src/ext_traits.rs b/crates/hyperswitch_domain_models/src/ext_traits.rsnew file mode 100644index 0000000000..a59e0aa8fd--- /dev/null+++ b/crates/hyperswitch_domain_models/src/ext_traits.rs@@ -0,0 +1,84 @@+use common_utils::{+ errors::{self, CustomResult},+ ext_traits::ValueExt,+ fp_utils::when,+};+use error_stack::ResultExt;++use crate::errors::api_error_response;++pub type DomainResult<T> = CustomResult<T, api_error_response::ApiErrorResponse>;+pub trait OptionExt<T> {+ fn check_value_present(&self, field_name: &'static str) -> DomainResult<()>;++ fn get_required_value(self, field_name: &'static str) -> DomainResult<T>;++ fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>+ where+ T: AsRef<str>,+ E: std::str::FromStr,+ // Requirement for converting the `Err` variant of `FromStr` to `Report<Err>`+ <E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static;++ fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>+ where+ T: ValueExt,+ U: serde::de::DeserializeOwned;++ fn update_value(&mut self, value: Option<T>);+}++impl<T> OptionExt<T> for Option<T> {+ fn check_value_present(&self, field_name: &'static str) -> DomainResult<()> {+ when(self.is_none(), || {+ Err(error_stack::Report::new(+ api_error_response::ApiErrorResponse::MissingRequiredField { field_name },+ )+ .attach_printable(format!("Missing required field {field_name}")))+ })+ }++ // This will allow the error message that was generated in this function to point to the call site+ #[track_caller]+ fn get_required_value(self, field_name: &'static str) -> DomainResult<T> {+ match self {+ Some(v) => Ok(v),+ None => Err(error_stack::Report::new(+ api_error_response::ApiErrorResponse::MissingRequiredField { field_name },+ )+ .attach_printable(format!("Missing required field {field_name}"))),+ }+ }++ fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>+ where+ T: AsRef<str>,+ E: std::str::FromStr,+ <E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,+ {+ let value = self+ .get_required_value(enum_name)+ .change_context(errors::ParsingError::UnknownError)?;++ E::from_str(value.as_ref())+ .change_context(errors::ParsingError::UnknownError)+ .attach_printable_lazy(|| format!("Invalid {{ {enum_name} }} "))+ }++ fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>+ where+ T: ValueExt,+ U: serde::de::DeserializeOwned,+ {+ let value = self+ .get_required_value(type_name)+ .change_context(errors::ParsingError::UnknownError)?;+ value.parse_value(type_name)+ }++ fn update_value(&mut self, value: Self) {+ if let Some(a) = value {+ *self = Some(a)+ }+ }+}diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rsindex d714fb1f7e..a611818d39 100644--- a/crates/hyperswitch_domain_models/src/lib.rs+++ b/crates/hyperswitch_domain_models/src/lib.rs@@ -5,11 +5,13 @@ pub mod bulk_tokenization;pub mod business_profile;pub mod callback_mapper;pub mod card_testing_guard_data;+pub mod cards_info;pub mod configs;pub mod consts;pub mod customer;pub mod disputes;pub mod errors;+pub mod ext_traits;pub mod mandates;pub mod merchant_account;pub mod merchant_connector_account;diff --git a/crates/payment_methods/Cargo.toml b/crates/payment_methods/Cargo.tomlindex c4b0df3447..26572c9e32 100644--- a/crates/payment_methods/Cargo.toml+++ b/crates/payment_methods/Cargo.toml@@ -6,15 +6,27 @@ rust-version.workspace = truelicense.workspace = true[dependencies]+actix-multipart = "0.6.1"+actix-web = "4.5.1"async-trait = "0.1.79"+bytes = "1.6.0"+csv = "1.3.0"dyn-clone = "1.0.17"+error-stack = "0.4.1"masking = { version = "0.1.0", path = "../masking" }+rdkafka = "0.36.2"serde = { version = "1.0.197", features = ["derive"] }serde_json = "1.0.115"+thiserror = "1.0.58"api_models = { version = "0.1.0", path = "../api_models", features = ["errors", "control_center_theme"] }+cards = { version = "0.1.0", path = "../cards" }+common_types = { version = "0.1.0", path = "../common_types" }+common_enums = { version = "0.1.0", path = "../common_enums" }common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager", "encryption_service"] }hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }+router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }+scheduler = { version = "0.1.0", path = "../scheduler", default-features = false }storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false }@@ -22,8 +34,10 @@ hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces"workspace = true[features]-default = ["dummy_connector"]-v1 = ["hyperswitch_domain_models/v1", "storage_impl/v1", "common_utils/v1"]-v2 = [ "payment_methods_v2"]+customer_v2 = ["api_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"]+default = ["dummy_connector", "payouts", "v1"]+v1 = ["hyperswitch_domain_models/v1", "storage_impl/v1", "common_utils/v1", "scheduler/v1", "common_types/v1"]+v2 = ["customer_v2", "payment_methods_v2", "common_utils/v2", "scheduler/v2", "common_types/v2"]payment_methods_v2 = [ "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"]-dummy_connector = ["api_models/dummy_connector", "hyperswitch_interfaces/dummy_connector"]\ No newline at end of file+dummy_connector = ["api_models/dummy_connector", "hyperswitch_interfaces/dummy_connector"]+payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_domain_models/payouts", "storage_impl/payouts", "hyperswitch_interfaces/payouts"]diff --git a/crates/payment_methods/src/controller.rs b/crates/payment_methods/src/controller.rsnew file mode 100644index 0000000000..c8b150af19--- /dev/null+++ b/crates/payment_methods/src/controller.rs@@ -0,0 +1,297 @@+use std::fmt::Debug;++#[cfg(feature = "payouts")]+use api_models::payouts;+use api_models::{enums as api_enums, payment_methods as api};+use common_enums::enums as common_enums;+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]+use common_utils::encryption;+use common_utils::{crypto, ext_traits, id_type, type_name, types::keymanager};+use error_stack::ResultExt;+use hyperswitch_domain_models::{merchant_key_store, payment_methods, type_encryption};+use masking::{PeekInterface, Secret};+use scheduler::errors as sch_errors;+use serde::{Deserialize, Serialize};+use storage_impl::{errors as storage_errors, payment_method};++use crate::core::errors;++#[derive(Debug, Deserialize, Serialize)]+pub struct DeleteCardResp {+ pub status: String,+ pub error_message: Option<String>,+ pub error_code: Option<String>,+}++#[derive(Debug, Deserialize, Serialize, PartialEq)]+#[serde(rename_all = "snake_case")]+pub enum DataDuplicationCheck {+ Duplicated,+ MetaDataChanged,+}++#[async_trait::async_trait]+pub trait PaymentMethodsController {+ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2"),+ not(feature = "customer_v2")+ ))]+ #[allow(clippy::too_many_arguments)]+ async fn create_payment_method(+ &self,+ req: &api::PaymentMethodCreate,+ customer_id: &id_type::CustomerId,+ payment_method_id: &str,+ locker_id: Option<String>,+ merchant_id: &id_type::MerchantId,+ pm_metadata: Option<serde_json::Value>,+ customer_acceptance: Option<serde_json::Value>,+ payment_method_data: crypto::OptionalEncryptableValue,+ connector_mandate_details: Option<serde_json::Value>,+ status: Option<common_enums::PaymentMethodStatus>,+ network_transaction_id: Option<String>,+ payment_method_billing_address: crypto::OptionalEncryptableValue,+ card_scheme: Option<String>,+ network_token_requestor_reference_id: Option<String>,+ network_token_locker_id: Option<String>,+ network_token_payment_method_data: crypto::OptionalEncryptableValue,+ ) -> errors::PmResult<payment_methods::PaymentMethod>;++ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+ ))]+ #[allow(clippy::too_many_arguments)]+ async fn insert_payment_method(+ &self,+ resp: &api::PaymentMethodResponse,+ req: &api::PaymentMethodCreate,+ key_store: &merchant_key_store::MerchantKeyStore,+ merchant_id: &id_type::MerchantId,+ customer_id: &id_type::CustomerId,+ pm_metadata: Option<serde_json::Value>,+ customer_acceptance: Option<serde_json::Value>,+ locker_id: Option<String>,+ connector_mandate_details: Option<serde_json::Value>,+ network_transaction_id: Option<String>,+ payment_method_billing_address: crypto::OptionalEncryptableValue,+ network_token_requestor_reference_id: Option<String>,+ network_token_locker_id: Option<String>,+ network_token_payment_method_data: crypto::OptionalEncryptableValue,+ ) -> errors::PmResult<payment_methods::PaymentMethod>;++ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]+ #[allow(clippy::too_many_arguments)]+ async fn insert_payment_method(+ &self,+ resp: &api::PaymentMethodResponse,+ req: &api::PaymentMethodCreate,+ key_store: &merchant_key_store::MerchantKeyStore,+ merchant_id: &id_type::MerchantId,+ customer_id: &id_type::CustomerId,+ pm_metadata: Option<serde_json::Value>,+ customer_acceptance: Option<serde_json::Value>,+ locker_id: Option<String>,+ connector_mandate_details: Option<serde_json::Value>,+ network_transaction_id: Option<String>,+ payment_method_billing_address: Option<encryption::Encryption>,+ ) -> errors::PmResult<payment_methods::PaymentMethod>;++ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+ ))]+ async fn add_payment_method(+ &self,+ req: &api::PaymentMethodCreate,+ ) -> errors::PmResponse<api::PaymentMethodResponse>;++ #[cfg(all(+ any(feature = "v2", feature = "v1"),+ not(feature = "payment_methods_v2")+ ))]+ async fn retrieve_payment_method(+ &self,+ pm: api::PaymentMethodId,+ ) -> errors::PmResponse<api::PaymentMethodResponse>;++ #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]+ async fn delete_payment_method(+ &self,+ pm_id: api::PaymentMethodId,+ ) -> errors::PmResponse<api::PaymentMethodDeleteResponse>;++ async fn add_card_hs(+ &self,+ req: api::PaymentMethodCreate,+ card: &api::CardDetail,+ customer_id: &id_type::CustomerId,+ locker_choice: api_enums::LockerChoice,+ card_reference: Option<&str>,+ ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>;++ /// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method+ async fn add_card_to_locker(+ &self,+ req: api::PaymentMethodCreate,+ card: &api::CardDetail,+ customer_id: &id_type::CustomerId,+ card_reference: Option<&str>,+ ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>;++ #[cfg(feature = "payouts")]+ async fn add_bank_to_locker(+ &self,+ req: api::PaymentMethodCreate,+ key_store: &merchant_key_store::MerchantKeyStore,+ bank: &payouts::Bank,+ customer_id: &id_type::CustomerId,+ ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>;++ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+ ))]+ async fn get_or_insert_payment_method(+ &self,+ req: api::PaymentMethodCreate,+ resp: &mut api::PaymentMethodResponse,+ customer_id: &id_type::CustomerId,+ key_store: &merchant_key_store::MerchantKeyStore,+ ) -> errors::PmResult<payment_methods::PaymentMethod>;++ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]+ async fn get_or_insert_payment_method(+ &self,+ req: api::PaymentMethodCreate,+ resp: &mut api::PaymentMethodResponse,+ customer_id: &id_type::CustomerId,+ key_store: &merchant_key_store::MerchantKeyStore,+ ) -> errors::PmResult<payment_methods::PaymentMethod> {+ todo!()+ }++ #[cfg(all(+ any(feature = "v2", feature = "v1"),+ not(feature = "payment_methods_v2")+ ))]+ async fn get_card_details_with_locker_fallback(+ &self,+ pm: &payment_methods::PaymentMethod,+ ) -> errors::PmResult<Option<api::CardDetailFromLocker>>;++ #[cfg(all(+ any(feature = "v2", feature = "v1"),+ not(feature = "payment_methods_v2")+ ))]+ async fn get_card_details_without_locker_fallback(+ &self,+ pm: &payment_methods::PaymentMethod,+ ) -> errors::PmResult<api::CardDetailFromLocker>;++ async fn delete_card_from_locker(+ &self,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ card_reference: &str,+ ) -> errors::PmResult<DeleteCardResp>;++ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+ ))]+ fn store_default_payment_method(+ &self,+ req: &api::PaymentMethodCreate,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ ) -> (api::PaymentMethodResponse, Option<DataDuplicationCheck>);++ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]+ fn store_default_payment_method(+ &self,+ req: &api::PaymentMethodCreate,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ ) -> (api::PaymentMethodResponse, Option<DataDuplicationCheck>);++ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2"),+ not(feature = "customer_v2")+ ))]+ #[allow(clippy::too_many_arguments)]+ async fn save_network_token_and_update_payment_method(+ &self,+ req: &api::PaymentMethodMigrate,+ key_store: &merchant_key_store::MerchantKeyStore,+ network_token_data: &api_models::payment_methods::MigrateNetworkTokenData,+ network_token_requestor_ref_id: String,+ pm_id: String,+ ) -> errors::PmResult<bool>;++ #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]+ async fn set_default_payment_method(+ &self,+ merchant_id: &id_type::MerchantId,+ customer_id: &id_type::CustomerId,+ payment_method_id: String,+ ) -> errors::PmResponse<api_models::payment_methods::CustomerDefaultPaymentMethodResponse>;++ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+ ))]+ async fn add_payment_method_status_update_task(+ &self,+ payment_method: &payment_methods::PaymentMethod,+ prev_status: common_enums::PaymentMethodStatus,+ curr_status: common_enums::PaymentMethodStatus,+ merchant_id: &id_type::MerchantId,+ ) -> Result<(), sch_errors::ProcessTrackerError>;++ #[cfg(feature = "v1")]+ async fn validate_merchant_connector_ids_in_connector_mandate_details(+ &self,+ key_store: &merchant_key_store::MerchantKeyStore,+ connector_mandate_details: &api_models::payment_methods::CommonMandateReference,+ merchant_id: &id_type::MerchantId,+ card_network: Option<common_enums::CardNetwork>,+ ) -> errors::PmResult<()>;+}++pub async fn create_encrypted_data<T>(+ key_manager_state: &keymanager::KeyManagerState,+ key_store: &merchant_key_store::MerchantKeyStore,+ data: T,+) -> Result<+ crypto::Encryptable<Secret<serde_json::Value>>,+ error_stack::Report<storage_errors::StorageError>,+>+where+ T: Debug + Serialize,+{+ let key = key_store.key.get_inner().peek();+ let identifier = keymanager::Identifier::Merchant(key_store.merchant_id.clone());++ let encoded_data = ext_traits::Encode::encode_to_value(&data)+ .change_context(storage_errors::StorageError::SerializationFailed)+ .attach_printable("Unable to encode data")?;++ let secret_data = Secret::<_, masking::WithType>::new(encoded_data);++ let encrypted_data = type_encryption::crypto_operation(+ key_manager_state,+ type_name!(payment_method::PaymentMethod),+ type_encryption::CryptoOperation::Encrypt(secret_data),+ identifier.clone(),+ key,+ )+ .await+ .and_then(|val| val.try_into_operation())+ .change_context(storage_errors::StorageError::EncryptionError)+ .attach_printable("Unable to encrypt data")?;++ Ok(encrypted_data)+}diff --git a/crates/payment_methods/src/core.rs b/crates/payment_methods/src/core.rsnew file mode 100644index 0000000000..b1cb73e27e--- /dev/null+++ b/crates/payment_methods/src/core.rs@@ -0,0 +1,2 @@+pub mod errors;+pub mod migration;diff --git a/crates/payment_methods/src/core/errors.rs b/crates/payment_methods/src/core/errors.rsnew file mode 100644index 0000000000..1c8823c11b--- /dev/null+++ b/crates/payment_methods/src/core/errors.rs@@ -0,0 +1,49 @@+pub use common_utils::errors::{CustomResult, ParsingError, ValidationError};+pub use hyperswitch_domain_models::{+ api,+ errors::api_error_response::{self, *},+};++pub type PmResult<T> = CustomResult<T, ApiErrorResponse>;+pub type PmResponse<T> = CustomResult<api::ApplicationResponse<T>, ApiErrorResponse>;+pub type VaultResult<T> = CustomResult<T, VaultError>;++#[derive(Debug, thiserror::Error)]+pub enum VaultError {+ #[error("Failed to save card in card vault")]+ SaveCardFailed,+ #[error("Failed to fetch card details from card vault")]+ FetchCardFailed,+ #[error("Failed to delete card in card vault")]+ DeleteCardFailed,+ #[error("Failed to encode card vault request")]+ RequestEncodingFailed,+ #[error("Failed to deserialize card vault response")]+ ResponseDeserializationFailed,+ #[error("Failed to create payment method")]+ PaymentMethodCreationFailed,+ #[error("The given payment method is currently not supported in vault")]+ PaymentMethodNotSupported,+ #[error("The given payout method is currently not supported in vault")]+ PayoutMethodNotSupported,+ #[error("Missing required field: {field_name}")]+ MissingRequiredField { field_name: &'static str },+ #[error("The card vault returned an unexpected response: {0:?}")]+ UnexpectedResponseError(bytes::Bytes),+ #[error("Failed to update in PMD table")]+ UpdateInPaymentMethodDataTableFailed,+ #[error("Failed to fetch payment method in vault")]+ FetchPaymentMethodFailed,+ #[error("Failed to save payment method in vault")]+ SavePaymentMethodFailed,+ #[error("Failed to generate fingerprint")]+ GenerateFingerprintFailed,+ #[error("Failed to encrypt vault request")]+ RequestEncryptionFailed,+ #[error("Failed to decrypt vault response")]+ ResponseDecryptionFailed,+ #[error("Failed to call vault")]+ VaultAPIError,+ #[error("Failed while calling locker API")]+ ApiError,+}diff --git a/crates/router/src/core/payment_methods/migration.rs b/crates/payment_methods/src/core/migration.rssimilarity index 71%rename from crates/router/src/core/payment_methods/migration.rsrename to crates/payment_methods/src/core/migration.rsindex aa0844a536..1166dd82ee 100644--- a/crates/router/src/core/payment_methods/migration.rs+++ b/crates/payment_methods/src/core/migration.rs@@ -1,27 +1,34 @@-use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm};-use api_models::payment_methods::{PaymentMethodMigrationResponse, PaymentMethodRecord};+use actix_multipart::form::{self, bytes, text};+use api_models::payment_methods as pm_api;use csv::Reader;use error_stack::ResultExt;+use hyperswitch_domain_models::{api, merchant_context};use masking::PeekInterface;use rdkafka::message::ToBytes;use router_env::{instrument, tracing};-use crate::{- core::{errors, payment_methods::cards::migrate_payment_method},- routes, services,- types::{api, domain},-};+use crate::{controller as pm, core::errors, state};+pub mod payment_methods;+pub use payment_methods::migrate_payment_method;+type PmMigrationResult<T> =+ errors::CustomResult<api::ApplicationResponse<T>, errors::ApiErrorResponse>;++#[cfg(all(+ any(feature = "v2", feature = "v1"),+ not(feature = "payment_methods_v2")+))]pub async fn migrate_payment_methods(- state: routes::SessionState,- payment_methods: Vec<PaymentMethodRecord>,+ state: &state::PaymentMethodsState,+ payment_methods: Vec<pm_api::PaymentMethodRecord>,merchant_id: &common_utils::id_type::MerchantId,- merchant_context: &domain::MerchantContext,+ merchant_context: &merchant_context::MerchantContext,mca_id: Option<common_utils::id_type::MerchantConnectorAccountId>,-) -> errors::RouterResponse<Vec<PaymentMethodMigrationResponse>> {+ controller: &dyn pm::PaymentMethodsController,+) -> PmMigrationResult<Vec<pm_api::PaymentMethodMigrationResponse>> {let mut result = Vec::new();for record in payment_methods {- let req = api::PaymentMethodMigrate::try_from((+ let req = pm_api::PaymentMethodMigrate::try_from((record.clone(),merchant_id.clone(),mca_id.clone(),@@ -30,45 +37,46 @@ pub async fn migrate_payment_methods(message: format!("error: {:?}", err),}).attach_printable("record deserialization failed");- match req {- Ok(_) => (),- Err(e) => {- result.push(PaymentMethodMigrationResponse::from((- Err(e.to_string()),- record,- )));- continue;+ let res = match req {+ Ok(migrate_request) => {+ let res = migrate_payment_method(+ state,+ migrate_request,+ merchant_id,+ merchant_context,+ controller,+ )+ .await;+ match res {+ Ok(api::ApplicationResponse::Json(response)) => Ok(response),+ Err(e) => Err(e.to_string()),+ _ => Err("Failed to migrate payment method".to_string()),+ }}+ Err(e) => Err(e.to_string()),};- let res = migrate_payment_method(state.clone(), req?, merchant_id, merchant_context).await;- result.push(PaymentMethodMigrationResponse::from((- match res {- Ok(services::api::ApplicationResponse::Json(response)) => Ok(response),- Err(e) => Err(e.to_string()),- _ => Err("Failed to migrate payment method".to_string()),- },- record,- )));+ result.push(pm_api::PaymentMethodMigrationResponse::from((res, record)));}- Ok(services::api::ApplicationResponse::Json(result))+ Ok(api::ApplicationResponse::Json(result))}-#[derive(Debug, MultipartForm)]+#[derive(Debug, form::MultipartForm)]pub struct PaymentMethodsMigrateForm {#[multipart(limit = "1MB")]- pub file: Bytes,+ pub file: bytes::Bytes,- pub merchant_id: Text<common_utils::id_type::MerchantId>,+ pub merchant_id: text::Text<common_utils::id_type::MerchantId>,- pub merchant_connector_id: Text<Option<common_utils::id_type::MerchantConnectorAccountId>>,+ pub merchant_connector_id:+ text::Text<Option<common_utils::id_type::MerchantConnectorAccountId>>,}-fn parse_csv(data: &[u8]) -> csv::Result<Vec<PaymentMethodRecord>> {+fn parse_csv(data: &[u8]) -> csv::Result<Vec<pm_api::PaymentMethodRecord>> {let mut csv_reader = Reader::from_reader(data);let mut records = Vec::new();let mut id_counter = 0;for result in csv_reader.deserialize() {- let mut record: PaymentMethodRecord = result?;+ let mut record: pm_api::PaymentMethodRecord = result?;id_counter += 1;record.line_number = Some(id_counter);records.push(record);@@ -80,7 +88,7 @@ pub fn get_payment_method_records() -> Result<(common_utils::id_type::MerchantId,- Vec<PaymentMethodRecord>,+ Vec<pm_api::PaymentMethodRecord>,Option<common_utils::id_type::MerchantConnectorAccountId>,),errors::ApiErrorResponse,diff --git a/crates/payment_methods/src/core/migration/payment_methods.rs b/crates/payment_methods/src/core/migration/payment_methods.rsnew file mode 100644index 0000000000..3dc8f3a5e5--- /dev/null+++ b/crates/payment_methods/src/core/migration/payment_methods.rs@@ -0,0 +1,710 @@+use std::str::FromStr;++#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]+use api_models::enums as api_enums;+use api_models::{enums, payment_methods as pm_api};+use common_utils::{+ consts,+ crypto::Encryptable,+ errors::CustomResult,+ ext_traits::{AsyncExt, ConfigExt},+ generate_id, id_type,+};+use error_stack::ResultExt;+use hyperswitch_domain_models::{+ api::ApplicationResponse, errors::api_error_response as errors, ext_traits::OptionExt,+ merchant_context, payment_methods as domain_pm,+};+use masking::{PeekInterface, Secret};+use router_env::{instrument, logger, tracing};+use serde_json::json;+use storage_impl::cards_info;++use crate::{+ controller::{create_encrypted_data, PaymentMethodsController},+ core::migration,+ helpers::{ForeignFrom, ForeignTryFrom, StorageErrorExt},+ state,+};++#[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+))]+pub async fn migrate_payment_method(+ state: &state::PaymentMethodsState,+ req: pm_api::PaymentMethodMigrate,+ merchant_id: &id_type::MerchantId,+ merchant_context: &merchant_context::MerchantContext,+ controller: &dyn PaymentMethodsController,+) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodMigrateResponse>, errors::ApiErrorResponse>+{+ let mut req = req;+ let card_details = &req.card.get_required_value("card")?;++ let card_number_validation_result =+ cards::CardNumber::from_str(card_details.card_number.peek());++ let card_bin_details =+ populate_bin_details_for_masked_card(card_details, &*state.store).await?;++ req.card = Some(api_models::payment_methods::MigrateCardDetail {+ card_issuing_country: card_bin_details.issuer_country.clone(),+ card_network: card_bin_details.card_network.clone(),+ card_issuer: card_bin_details.card_issuer.clone(),+ card_type: card_bin_details.card_type.clone(),+ ..card_details.clone()+ });++ if let Some(connector_mandate_details) = &req.connector_mandate_details {+ controller+ .validate_merchant_connector_ids_in_connector_mandate_details(+ merchant_context.get_merchant_key_store(),+ connector_mandate_details,+ merchant_id,+ card_bin_details.card_network.clone(),+ )+ .await?;+ };++ let should_require_connector_mandate_details = req.network_token.is_none();++ let mut migration_status = migration::RecordMigrationStatusBuilder::new();++ let resp = match card_number_validation_result {+ Ok(card_number) => {+ let payment_method_create_request =+ pm_api::PaymentMethodCreate::get_payment_method_create_from_payment_method_migrate(+ card_number,+ &req,+ );++ logger::debug!("Storing the card in locker and migrating the payment method");+ get_client_secret_or_add_payment_method_for_migration(+ state,+ payment_method_create_request,+ merchant_context,+ &mut migration_status,+ controller,+ )+ .await?+ }+ Err(card_validation_error) => {+ logger::debug!("Card number to be migrated is invalid, skip saving in locker {card_validation_error}");+ skip_locker_call_and_migrate_payment_method(+ state,+ &req,+ merchant_id.to_owned(),+ merchant_context,+ card_bin_details.clone(),+ should_require_connector_mandate_details,+ &mut migration_status,+ controller,+ )+ .await?+ }+ };+ let payment_method_response = match resp {+ ApplicationResponse::Json(response) => response,+ _ => Err(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch the payment method response")?,+ };++ let pm_id = payment_method_response.payment_method_id.clone();++ let network_token = req.network_token.clone();++ let network_token_migrated = match network_token {+ Some(nt_detail) => {+ logger::debug!("Network token migration");+ let network_token_requestor_ref_id = nt_detail.network_token_requestor_ref_id.clone();+ let network_token_data = &nt_detail.network_token_data;++ Some(+ controller+ .save_network_token_and_update_payment_method(+ &req,+ merchant_context.get_merchant_key_store(),+ network_token_data,+ network_token_requestor_ref_id,+ pm_id,+ )+ .await+ .map_err(|err| logger::error!(?err, "Failed to save network token"))+ .ok()+ .unwrap_or_default(),+ )+ }+ None => {+ logger::debug!("Network token data is not available");+ None+ }+ };+ migration_status.network_token_migrated(network_token_migrated);+ let migrate_status = migration_status.build();++ Ok(ApplicationResponse::Json(+ pm_api::PaymentMethodMigrateResponse {+ payment_method_response,+ card_migrated: migrate_status.card_migrated,+ network_token_migrated: migrate_status.network_token_migrated,+ connector_mandate_details_migrated: migrate_status.connector_mandate_details_migrated,+ network_transaction_id_migrated: migrate_status.network_transaction_migrated,+ },+ ))+}++#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]+pub async fn migrate_payment_method(+ _state: &state::PaymentMethodsState,+ _req: pm_api::PaymentMethodMigrate,+ _merchant_id: &id_type::MerchantId,+ merchant_context: &merchant_context::MerchantContext,+ controller: &dyn PaymentMethodsController,+) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodMigrateResponse>, errors::ApiErrorResponse>+{+ todo!()+}++#[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+))]+pub async fn populate_bin_details_for_masked_card(+ card_details: &api_models::payment_methods::MigrateCardDetail,+ db: &dyn state::PaymentMethodsStorageInterface,+) -> CustomResult<pm_api::CardDetailFromLocker, errors::ApiErrorResponse> {+ migration::validate_card_expiry(&card_details.card_exp_month, &card_details.card_exp_year)?;+ let card_number = card_details.card_number.clone();++ let (card_isin, _last4_digits) = get_card_bin_and_last4_digits_for_masked_card(+ card_number.peek(),+ )+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "Invalid card number".to_string(),+ })?;++ let card_bin_details = if card_details.card_issuer.is_some()+ && card_details.card_network.is_some()+ && card_details.card_type.is_some()+ && card_details.card_issuing_country.is_some()+ {+ pm_api::CardDetailFromLocker::foreign_try_from((card_details, None))?+ } else {+ let card_info = db+ .get_card_info(&card_isin)+ .await+ .map_err(|error| logger::error!(card_info_error=?error))+ .ok()+ .flatten();++ pm_api::CardDetailFromLocker::foreign_try_from((card_details, card_info))?+ };+ Ok(card_bin_details)+}++#[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+))]+impl+ ForeignTryFrom<(+ &api_models::payment_methods::MigrateCardDetail,+ Option<cards_info::CardInfo>,+ )> for pm_api::CardDetailFromLocker+{+ type Error = error_stack::Report<errors::ApiErrorResponse>;+ fn foreign_try_from(+ (card_details, card_info): (+ &api_models::payment_methods::MigrateCardDetail,+ Option<cards_info::CardInfo>,+ ),+ ) -> Result<Self, Self::Error> {+ let (card_isin, last4_digits) =+ get_card_bin_and_last4_digits_for_masked_card(card_details.card_number.peek())+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "Invalid card number".to_string(),+ })?;+ if let Some(card_bin_info) = card_info {+ Ok(Self {+ scheme: card_details+ .card_network+ .clone()+ .or(card_bin_info.card_network.clone())+ .map(|card_network| card_network.to_string()),+ last4_digits: Some(last4_digits.clone()),+ issuer_country: card_details+ .card_issuing_country+ .clone()+ .or(card_bin_info.card_issuing_country),+ card_number: None,+ expiry_month: Some(card_details.card_exp_month.clone()),+ expiry_year: Some(card_details.card_exp_year.clone()),+ card_token: None,+ card_fingerprint: None,+ card_holder_name: card_details.card_holder_name.clone(),+ nick_name: card_details.nick_name.clone(),+ card_isin: Some(card_isin.clone()),+ card_issuer: card_details+ .card_issuer+ .clone()+ .or(card_bin_info.card_issuer),+ card_network: card_details+ .card_network+ .clone()+ .or(card_bin_info.card_network),+ card_type: card_details.card_type.clone().or(card_bin_info.card_type),+ saved_to_locker: false,+ })+ } else {+ Ok(Self {+ scheme: card_details+ .card_network+ .clone()+ .map(|card_network| card_network.to_string()),+ last4_digits: Some(last4_digits.clone()),+ issuer_country: card_details.card_issuing_country.clone(),+ card_number: None,+ expiry_month: Some(card_details.card_exp_month.clone()),+ expiry_year: Some(card_details.card_exp_year.clone()),+ card_token: None,+ card_fingerprint: None,+ card_holder_name: card_details.card_holder_name.clone(),+ nick_name: card_details.nick_name.clone(),+ card_isin: Some(card_isin.clone()),+ card_issuer: card_details.card_issuer.clone(),+ card_network: card_details.card_network.clone(),+ card_type: card_details.card_type.clone(),+ saved_to_locker: false,+ })+ }+ }+}++#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]+impl+ ForeignTryFrom<(+ &api_models::payment_methods::MigrateCardDetail,+ Option<cards_info::CardInfo>,+ )> for pm_api::CardDetailFromLocker+{+ type Error = error_stack::Report<errors::ApiErrorResponse>;+ fn foreign_try_from(+ (card_details, card_info): (+ &api_models::payment_methods::MigrateCardDetail,+ Option<cards_info::CardInfo>,+ ),+ ) -> Result<Self, Self::Error> {+ let (card_isin, last4_digits) =+ get_card_bin_and_last4_digits_for_masked_card(card_details.card_number.peek())+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "Invalid card number".to_string(),+ })?;+ if let Some(card_bin_info) = card_info {+ Ok(Self {+ last4_digits: Some(last4_digits.clone()),+ issuer_country: card_details+ .card_issuing_country+ .as_ref()+ .map(|c| api_enums::CountryAlpha2::from_str(c))+ .transpose()+ .ok()+ .flatten()+ .or(card_bin_info+ .card_issuing_country+ .as_ref()+ .map(|c| api_enums::CountryAlpha2::from_str(c))+ .transpose()+ .ok()+ .flatten()),+ card_number: None,+ expiry_month: Some(card_details.card_exp_month.clone()),+ expiry_year: Some(card_details.card_exp_year.clone()),+ card_fingerprint: None,+ card_holder_name: card_details.card_holder_name.clone(),+ nick_name: card_details.nick_name.clone(),+ card_isin: Some(card_isin.clone()),+ card_issuer: card_details+ .card_issuer+ .clone()+ .or(card_bin_info.card_issuer),+ card_network: card_details+ .card_network+ .clone()+ .or(card_bin_info.card_network),+ card_type: card_details.card_type.clone().or(card_bin_info.card_type),+ saved_to_locker: false,+ })+ } else {+ Ok(Self {+ last4_digits: Some(last4_digits.clone()),+ issuer_country: card_details+ .card_issuing_country+ .as_ref()+ .map(|c| api_enums::CountryAlpha2::from_str(c))+ .transpose()+ .ok()+ .flatten(),+ card_number: None,+ expiry_month: Some(card_details.card_exp_month.clone()),+ expiry_year: Some(card_details.card_exp_year.clone()),+ card_fingerprint: None,+ card_holder_name: card_details.card_holder_name.clone(),+ nick_name: card_details.nick_name.clone(),+ card_isin: Some(card_isin.clone()),+ card_issuer: card_details.card_issuer.clone(),+ card_network: card_details.card_network.clone(),+ card_type: card_details.card_type.clone(),+ saved_to_locker: false,+ })+ }+ }+}++#[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+))]+#[instrument(skip_all)]+pub async fn get_client_secret_or_add_payment_method_for_migration(+ state: &state::PaymentMethodsState,+ req: pm_api::PaymentMethodCreate,+ merchant_context: &merchant_context::MerchantContext,+ migration_status: &mut migration::RecordMigrationStatusBuilder,+ controller: &dyn PaymentMethodsController,+) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> {+ let merchant_id = merchant_context.get_merchant_account().get_id();+ let customer_id = req.customer_id.clone().get_required_value("customer_id")?;++ #[cfg(not(feature = "payouts"))]+ let condition = req.card.is_some();+ #[cfg(feature = "payouts")]+ let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();+ let key_manager_state = &state.into();++ let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req+ .billing+ .clone()+ .async_map(|billing| {+ create_encrypted_data(+ key_manager_state,+ merchant_context.get_merchant_key_store(),+ billing,+ )+ })+ .await+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt Payment method billing address")?;++ let connector_mandate_details = req+ .connector_mandate_details+ .clone()+ .map(serde_json::to_value)+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ if condition {+ Box::pin(save_migration_payment_method(+ req,+ migration_status,+ controller,+ ))+ .await+ } else {+ let payment_method_id = generate_id(consts::ID_LENGTH, "pm");++ let res = controller+ .create_payment_method(+ &req,+ &customer_id,+ payment_method_id.as_str(),+ None,+ merchant_id,+ None,+ None,+ None,+ connector_mandate_details.clone(),+ Some(enums::PaymentMethodStatus::AwaitingData),+ None,+ payment_method_billing_address,+ None,+ None,+ None,+ None,+ )+ .await?;+ migration_status.connector_mandate_details_migrated(+ connector_mandate_details+ .clone()+ .and_then(|val| (val != json!({})).then_some(true))+ .or_else(|| {+ req.connector_mandate_details+ .clone()+ .and_then(|val| (!val.0.is_empty()).then_some(false))+ }),+ );+ //card is not migrated in this case+ migration_status.card_migrated(false);++ if res.status == enums::PaymentMethodStatus::AwaitingData {+ controller+ .add_payment_method_status_update_task(+ &res,+ enums::PaymentMethodStatus::AwaitingData,+ enums::PaymentMethodStatus::Inactive,+ merchant_id,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to add payment method status update task in process tracker",+ )?;+ }++ Ok(ApplicationResponse::Json(+ pm_api::PaymentMethodResponse::foreign_from((None, res)),+ ))+ }+}+#[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2"),+ not(feature = "customer_v2")+))]+#[allow(clippy::too_many_arguments)]+pub async fn skip_locker_call_and_migrate_payment_method(+ state: &state::PaymentMethodsState,+ req: &pm_api::PaymentMethodMigrate,+ merchant_id: id_type::MerchantId,+ merchant_context: &merchant_context::MerchantContext,+ card: pm_api::CardDetailFromLocker,+ should_require_connector_mandate_details: bool,+ migration_status: &mut migration::RecordMigrationStatusBuilder,+ controller: &dyn PaymentMethodsController,+) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> {+ let db = &*state.store;+ let customer_id = req.customer_id.clone().get_required_value("customer_id")?;++ // In this case, since we do not have valid card details, recurring payments can only be done through connector mandate details.+ //if network token data is present, then connector mandate details are not mandatory++ let connector_mandate_details = if should_require_connector_mandate_details {+ let connector_mandate_details_req = req+ .connector_mandate_details+ .clone()+ .and_then(|c| c.payments)+ .clone()+ .get_required_value("connector mandate details")?;++ Some(+ serde_json::to_value(&connector_mandate_details_req)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse connector mandate details")?,+ )+ } else {+ req.connector_mandate_details+ .clone()+ .and_then(|c| c.payments)+ .map(|mandate_details_req| {+ serde_json::to_value(&mandate_details_req)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to parse connector mandate details")+ })+ .transpose()?+ };+ let key_manager_state = &state.into();+ let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req+ .billing+ .clone()+ .async_map(|billing| {+ create_encrypted_data(+ key_manager_state,+ merchant_context.get_merchant_key_store(),+ billing,+ )+ })+ .await+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt Payment method billing address")?;++ let customer = db+ .find_customer_by_customer_id_merchant_id(+ &state.into(),+ &customer_id,+ &merchant_id,+ merchant_context.get_merchant_key_store(),+ merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;++ let payment_method_card_details =+ pm_api::PaymentMethodsData::Card(pm_api::CardDetailsPaymentMethod::from(card.clone()));++ let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = Some(+ create_encrypted_data(+ &state.into(),+ merchant_context.get_merchant_key_store(),+ payment_method_card_details,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt Payment method card details")?,+ );++ let payment_method_metadata: Option<serde_json::Value> =+ req.metadata.as_ref().map(|data| data.peek()).cloned();++ let network_transaction_id = req.network_transaction_id.clone();++ let payment_method_id = generate_id(consts::ID_LENGTH, "pm");++ let current_time = common_utils::date_time::now();++ let response = db+ .insert_payment_method(+ &state.into(),+ merchant_context.get_merchant_key_store(),+ domain_pm::PaymentMethod {+ customer_id: customer_id.to_owned(),+ merchant_id: merchant_id.to_owned(),+ payment_method_id: payment_method_id.to_string(),+ locker_id: None,+ payment_method: req.payment_method,+ payment_method_type: req.payment_method_type,+ payment_method_issuer: req.payment_method_issuer.clone(),+ scheme: req.card_network.clone().or(card.scheme.clone()),+ metadata: payment_method_metadata.map(Secret::new),+ payment_method_data: payment_method_data_encrypted,+ connector_mandate_details: connector_mandate_details.clone(),+ customer_acceptance: None,+ client_secret: None,+ status: enums::PaymentMethodStatus::Active,+ network_transaction_id: network_transaction_id.clone(),+ payment_method_issuer_code: None,+ accepted_currency: None,+ token: None,+ cardholder_name: None,+ issuer_name: None,+ issuer_country: None,+ payer_country: None,+ is_stored: None,+ swift_code: None,+ direct_debit_token: None,+ created_at: current_time,+ last_modified: current_time,+ last_used_at: current_time,+ payment_method_billing_address,+ updated_by: None,+ version: common_types::consts::API_VERSION,+ network_token_requestor_reference_id: None,+ network_token_locker_id: None,+ network_token_payment_method_data: None,+ },+ merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to add payment method in db")?;++ logger::debug!("Payment method inserted in db");++ migration_status.network_transaction_id_migrated(+ network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)),+ );++ migration_status.connector_mandate_details_migrated(+ connector_mandate_details+ .clone()+ .and_then(|val| if val == json!({}) { None } else { Some(true) })+ .or_else(|| {+ req.connector_mandate_details.clone().and_then(|val| {+ val.payments+ .and_then(|payin_val| (!payin_val.0.is_empty()).then_some(false))+ })+ }),+ );++ if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {+ let _ = controller+ .set_default_payment_method(&merchant_id, &customer_id, payment_method_id.to_owned())+ .await+ .map_err(|error| logger::error!(?error, "Failed to set the payment method as default"));+ }+ Ok(ApplicationResponse::Json(+ pm_api::PaymentMethodResponse::foreign_from((Some(card), response)),+ ))+}++// need to discuss regarding the migration APIs for v2+#[cfg(all(+ feature = "v2",+ feature = "payment_methods_v2",+ feature = "customer_v2"+))]+pub async fn skip_locker_call_and_migrate_payment_method(+ _state: state::PaymentMethodsState,+ _req: &pm_api::PaymentMethodMigrate,+ _merchant_id: id_type::MerchantId,+ _merchant_context: &merchant_context::MerchantContext,+ _card: pm_api::CardDetailFromLocker,+) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> {+ todo!()+}+pub fn get_card_bin_and_last4_digits_for_masked_card(+ masked_card_number: &str,+) -> Result<(String, String), cards::CardNumberValidationErr> {+ let last4_digits = masked_card_number+ .chars()+ .rev()+ .take(4)+ .collect::<String>()+ .chars()+ .rev()+ .collect::<String>();++ let card_isin = masked_card_number.chars().take(6).collect::<String>();++ cards::validate::validate_card_number_chars(&card_isin)+ .and_then(|_| cards::validate::validate_card_number_chars(&last4_digits))?;++ Ok((card_isin, last4_digits))+}+#[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+))]+#[instrument(skip_all)]+pub async fn save_migration_payment_method(+ req: pm_api::PaymentMethodCreate,+ migration_status: &mut migration::RecordMigrationStatusBuilder,+ controller: &dyn PaymentMethodsController,+) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> {+ let connector_mandate_details = req+ .connector_mandate_details+ .clone()+ .map(serde_json::to_value)+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ let network_transaction_id = req.network_transaction_id.clone();++ let res = controller.add_payment_method(&req).await?;++ migration_status.card_migrated(true);+ migration_status.network_transaction_id_migrated(+ network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)),+ );++ migration_status.connector_mandate_details_migrated(+ connector_mandate_details+ .and_then(|val| if val == json!({}) { None } else { Some(true) })+ .or_else(|| {+ req.connector_mandate_details+ .and_then(|val| (!val.0.is_empty()).then_some(false))+ }),+ );+ Ok(res)+}diff --git a/crates/payment_methods/src/helpers.rs b/crates/payment_methods/src/helpers.rsnew file mode 100644index 0000000000..1e483b12d7--- /dev/null+++ b/crates/payment_methods/src/helpers.rs@@ -0,0 +1,330 @@+use api_models::{enums as api_enums, payment_methods as api};+use common_utils::ext_traits::AsyncExt;+pub use hyperswitch_domain_models::{errors::api_error_response, payment_methods as domain};+use router_env::logger;++use crate::state;+#[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+))]+pub async fn populate_bin_details_for_payment_method_create(+ card_details: api_models::payment_methods::CardDetail,+ db: Box<dyn state::PaymentMethodsStorageInterface>,+) -> api_models::payment_methods::CardDetail {+ let card_isin: Option<_> = Some(card_details.card_number.get_card_isin());+ if card_details.card_issuer.is_some()+ && card_details.card_network.is_some()+ && card_details.card_type.is_some()+ && card_details.card_issuing_country.is_some()+ {+ api::CardDetail {+ card_issuer: card_details.card_issuer.to_owned(),+ card_network: card_details.card_network.clone(),+ card_type: card_details.card_type.to_owned(),+ card_issuing_country: card_details.card_issuing_country.to_owned(),+ card_exp_month: card_details.card_exp_month.clone(),+ card_exp_year: card_details.card_exp_year.clone(),+ card_holder_name: card_details.card_holder_name.clone(),+ card_number: card_details.card_number.clone(),+ nick_name: card_details.nick_name.clone(),+ }+ } else {+ let card_info = card_isin+ .clone()+ .async_and_then(|card_isin| async move {+ db.get_card_info(&card_isin)+ .await+ .map_err(|error| logger::error!(card_info_error=?error))+ .ok()+ })+ .await+ .flatten()+ .map(|card_info| api::CardDetail {+ card_issuer: card_info.card_issuer,+ card_network: card_info.card_network.clone(),+ card_type: card_info.card_type,+ card_issuing_country: card_info.card_issuing_country,+ card_exp_month: card_details.card_exp_month.clone(),+ card_exp_year: card_details.card_exp_year.clone(),+ card_holder_name: card_details.card_holder_name.clone(),+ card_number: card_details.card_number.clone(),+ nick_name: card_details.nick_name.clone(),+ });+ card_info.unwrap_or_else(|| api::CardDetail {+ card_issuer: None,+ card_network: None,+ card_type: None,+ card_issuing_country: None,+ card_exp_month: card_details.card_exp_month.clone(),+ card_exp_year: card_details.card_exp_year.clone(),+ card_holder_name: card_details.card_holder_name.clone(),+ card_number: card_details.card_number.clone(),+ nick_name: card_details.nick_name.clone(),+ })+ }+}++#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]+pub async fn populate_bin_details_for_payment_method_create(+ _card_details: api_models::payment_methods::CardDetail,+ _db: &dyn state::PaymentMethodsStorageInterface,+) -> api_models::payment_methods::CardDetail {+ todo!()+}++pub fn validate_payment_method_type_against_payment_method(+ payment_method: api_enums::PaymentMethod,+ payment_method_type: api_enums::PaymentMethodType,+) -> bool {+ match payment_method {+ #[cfg(feature = "v1")]+ api_enums::PaymentMethod::Card => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit+ ),+ #[cfg(feature = "v2")]+ api_enums::PaymentMethod::Card => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::Credit+ | api_enums::PaymentMethodType::Debit+ | api_enums::PaymentMethodType::Card+ ),+ api_enums::PaymentMethod::PayLater => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::Affirm+ | api_enums::PaymentMethodType::Alma+ | api_enums::PaymentMethodType::AfterpayClearpay+ | api_enums::PaymentMethodType::Klarna+ | api_enums::PaymentMethodType::PayBright+ | api_enums::PaymentMethodType::Atome+ | api_enums::PaymentMethodType::Walley+ ),+ api_enums::PaymentMethod::Wallet => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::AmazonPay+ | api_enums::PaymentMethodType::ApplePay+ | api_enums::PaymentMethodType::GooglePay+ | api_enums::PaymentMethodType::Paypal+ | api_enums::PaymentMethodType::AliPay+ | api_enums::PaymentMethodType::AliPayHk+ | api_enums::PaymentMethodType::Dana+ | api_enums::PaymentMethodType::MbWay+ | api_enums::PaymentMethodType::MobilePay+ | api_enums::PaymentMethodType::SamsungPay+ | api_enums::PaymentMethodType::Twint+ | api_enums::PaymentMethodType::Vipps+ | api_enums::PaymentMethodType::TouchNGo+ | api_enums::PaymentMethodType::Swish+ | api_enums::PaymentMethodType::WeChatPay+ | api_enums::PaymentMethodType::GoPay+ | api_enums::PaymentMethodType::Gcash+ | api_enums::PaymentMethodType::Momo+ | api_enums::PaymentMethodType::KakaoPay+ | api_enums::PaymentMethodType::Cashapp+ | api_enums::PaymentMethodType::Mifinity+ | api_enums::PaymentMethodType::Paze+ ),+ api_enums::PaymentMethod::BankRedirect => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::Giropay+ | api_enums::PaymentMethodType::Ideal+ | api_enums::PaymentMethodType::Sofort+ | api_enums::PaymentMethodType::Eft+ | api_enums::PaymentMethodType::Eps+ | api_enums::PaymentMethodType::BancontactCard+ | api_enums::PaymentMethodType::Blik+ | api_enums::PaymentMethodType::LocalBankRedirect+ | api_enums::PaymentMethodType::OnlineBankingThailand+ | api_enums::PaymentMethodType::OnlineBankingCzechRepublic+ | api_enums::PaymentMethodType::OnlineBankingFinland+ | api_enums::PaymentMethodType::OnlineBankingFpx+ | api_enums::PaymentMethodType::OnlineBankingPoland+ | api_enums::PaymentMethodType::OnlineBankingSlovakia+ | api_enums::PaymentMethodType::Przelewy24+ | api_enums::PaymentMethodType::Trustly+ | api_enums::PaymentMethodType::Bizum+ | api_enums::PaymentMethodType::Interac+ | api_enums::PaymentMethodType::OpenBankingUk+ | api_enums::PaymentMethodType::OpenBankingPIS+ ),+ api_enums::PaymentMethod::BankTransfer => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::Ach+ | api_enums::PaymentMethodType::SepaBankTransfer+ | api_enums::PaymentMethodType::Bacs+ | api_enums::PaymentMethodType::Multibanco+ | api_enums::PaymentMethodType::Pix+ | api_enums::PaymentMethodType::Pse+ | api_enums::PaymentMethodType::PermataBankTransfer+ | api_enums::PaymentMethodType::BcaBankTransfer+ | api_enums::PaymentMethodType::BniVa+ | api_enums::PaymentMethodType::BriVa+ | api_enums::PaymentMethodType::CimbVa+ | api_enums::PaymentMethodType::DanamonVa+ | api_enums::PaymentMethodType::MandiriVa+ | api_enums::PaymentMethodType::LocalBankTransfer+ | api_enums::PaymentMethodType::InstantBankTransfer+ ),+ api_enums::PaymentMethod::BankDebit => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::Ach+ | api_enums::PaymentMethodType::Sepa+ | api_enums::PaymentMethodType::Bacs+ | api_enums::PaymentMethodType::Becs+ ),+ api_enums::PaymentMethod::Crypto => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::CryptoCurrency+ ),+ api_enums::PaymentMethod::Reward => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::Evoucher | api_enums::PaymentMethodType::ClassicReward+ ),+ api_enums::PaymentMethod::RealTimePayment => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::Fps+ | api_enums::PaymentMethodType::DuitNow+ | api_enums::PaymentMethodType::PromptPay+ | api_enums::PaymentMethodType::VietQr+ ),+ api_enums::PaymentMethod::Upi => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::UpiCollect | api_enums::PaymentMethodType::UpiIntent+ ),+ api_enums::PaymentMethod::Voucher => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::Boleto+ | api_enums::PaymentMethodType::Efecty+ | api_enums::PaymentMethodType::PagoEfectivo+ | api_enums::PaymentMethodType::RedCompra+ | api_enums::PaymentMethodType::RedPagos+ | api_enums::PaymentMethodType::Indomaret+ | api_enums::PaymentMethodType::Alfamart+ | api_enums::PaymentMethodType::Oxxo+ | api_enums::PaymentMethodType::SevenEleven+ | api_enums::PaymentMethodType::Lawson+ | api_enums::PaymentMethodType::MiniStop+ | api_enums::PaymentMethodType::FamilyMart+ | api_enums::PaymentMethodType::Seicomart+ | api_enums::PaymentMethodType::PayEasy+ ),+ api_enums::PaymentMethod::GiftCard => {+ matches!(+ payment_method_type,+ api_enums::PaymentMethodType::Givex | api_enums::PaymentMethodType::PaySafeCard+ )+ }+ api_enums::PaymentMethod::CardRedirect => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::Knet+ | api_enums::PaymentMethodType::Benefit+ | api_enums::PaymentMethodType::MomoAtm+ | api_enums::PaymentMethodType::CardRedirect+ ),+ api_enums::PaymentMethod::OpenBanking => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::OpenBankingPIS+ ),+ api_enums::PaymentMethod::MobilePayment => matches!(+ payment_method_type,+ api_enums::PaymentMethodType::DirectCarrierBilling+ ),+ }+}++pub trait ForeignFrom<F> {+ fn foreign_from(from: F) -> Self;+}++/// Trait for converting from one foreign type to another+pub trait ForeignTryFrom<F>: Sized {+ /// Custom error for conversion failure+ type Error;+ /// Convert from a foreign type to the current type and return an error if the conversion fails+ fn foreign_try_from(from: F) -> Result<Self, Self::Error>;+}++#[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+))]+impl ForeignFrom<(Option<api::CardDetailFromLocker>, domain::PaymentMethod)>+ for api::PaymentMethodResponse+{+ fn foreign_from(+ (card_details, item): (Option<api::CardDetailFromLocker>, domain::PaymentMethod),+ ) -> Self {+ Self {+ merchant_id: item.merchant_id.to_owned(),+ customer_id: Some(item.customer_id.to_owned()),+ payment_method_id: item.get_id().clone(),+ payment_method: item.get_payment_method_type(),+ payment_method_type: item.get_payment_method_subtype(),+ card: card_details,+ recurring_enabled: false,+ installment_payment_enabled: false,+ payment_experience: None,+ metadata: item.metadata,+ created: Some(item.created_at),+ #[cfg(feature = "payouts")]+ bank_transfer: None,+ last_used_at: None,+ client_secret: item.client_secret,+ }+ }+}++#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]+impl ForeignFrom<(Option<api::CardDetailFromLocker>, domain::PaymentMethod)>+ for api::PaymentMethodResponse+{+ fn foreign_from(+ (card_details, item): (Option<api::CardDetailFromLocker>, domain::PaymentMethod),+ ) -> Self {+ todo!()+ }+}++pub trait StorageErrorExt<T, E> {+ #[track_caller]+ fn to_not_found_response(self, not_found_response: E) -> error_stack::Result<T, E>;++ #[track_caller]+ fn to_duplicate_response(self, duplicate_response: E) -> error_stack::Result<T, E>;+}++impl<T> StorageErrorExt<T, api_error_response::ApiErrorResponse>+ for error_stack::Result<T, storage_impl::StorageError>+{+ #[track_caller]+ fn to_not_found_response(+ self,+ not_found_response: api_error_response::ApiErrorResponse,+ ) -> error_stack::Result<T, api_error_response::ApiErrorResponse> {+ self.map_err(|err| {+ let new_err = match err.current_context() {+ storage_impl::StorageError::ValueNotFound(_) => not_found_response,+ storage_impl::StorageError::CustomerRedacted => {+ api_error_response::ApiErrorResponse::CustomerRedacted+ }+ _ => api_error_response::ApiErrorResponse::InternalServerError,+ };+ err.change_context(new_err)+ })+ }++ #[track_caller]+ fn to_duplicate_response(+ self,+ duplicate_response: api_error_response::ApiErrorResponse,+ ) -> error_stack::Result<T, api_error_response::ApiErrorResponse> {+ self.map_err(|err| {+ let new_err = match err.current_context() {+ storage_impl::StorageError::DuplicateValue { .. } => duplicate_response,+ _ => api_error_response::ApiErrorResponse::InternalServerError,+ };+ err.change_context(new_err)+ })+ }+}diff --git a/crates/payment_methods/src/lib.rs b/crates/payment_methods/src/lib.rsindex 015992da4a..ab3252b464 100644--- a/crates/payment_methods/src/lib.rs+++ b/crates/payment_methods/src/lib.rs@@ -1,2 +1,5 @@pub mod configs;+pub mod controller;+pub mod core;+pub mod helpers;pub mod state;diff --git a/crates/payment_methods/src/state.rs b/crates/payment_methods/src/state.rsindex 7f75266017..65cfe3699b 100644--- a/crates/payment_methods/src/state.rs+++ b/crates/payment_methods/src/state.rs@@ -3,22 +3,21 @@not(feature = "payment_methods_v2")))]use common_utils::errors::CustomResult;-use common_utils::types::keymanager::KeyManagerState;-#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2")-))]-use hyperswitch_domain_models::{- merchant_account::MerchantAccount, payment_methods::PaymentMethod,-};+use common_utils::types::keymanager;use hyperswitch_domain_models::{- merchant_key_store::MerchantKeyStore, payment_methods::PaymentMethodInterface,+ cards_info, customer, merchant_account, merchant_key_store, payment_methods as pm_domain,};use storage_impl::{errors, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore};#[async_trait::async_trait]pub trait PaymentMethodsStorageInterface:- Send + Sync + dyn_clone::DynClone + PaymentMethodInterface<Error = errors::StorageError> + 'static+ Send+ + Sync+ + dyn_clone::DynClone+ + pm_domain::PaymentMethodInterface<Error = errors::StorageError>+ + cards_info::CardsInfoInterface<Error = errors::StorageError>+ + customer::CustomerInterface<Error = errors::StorageError>+ + 'static{}dyn_clone::clone_trait_object!(PaymentMethodsStorageInterface);@@ -35,10 +34,10 @@ impl<T: DatabaseStore + 'static> PaymentMethodsStorageInterface for KVRouterStor#[derive(Clone)]pub struct PaymentMethodsState {pub store: Box<dyn PaymentMethodsStorageInterface>,- pub key_store: Option<MerchantKeyStore>,- pub key_manager_state: KeyManagerState,+ pub key_store: Option<merchant_key_store::MerchantKeyStore>,+ pub key_manager_state: keymanager::KeyManagerState,}-impl From<&PaymentMethodsState> for KeyManagerState {+impl From<&PaymentMethodsState> for keymanager::KeyManagerState {fn from(state: &PaymentMethodsState) -> Self {state.key_manager_state.clone()}@@ -50,10 +49,10 @@ impl From<&PaymentMethodsState> for KeyManagerState {impl PaymentMethodsState {pub async fn find_payment_method(&self,- key_store: &MerchantKeyStore,- merchant_account: &MerchantAccount,+ key_store: &merchant_key_store::MerchantKeyStore,+ merchant_account: &merchant_account::MerchantAccount,payment_method_id: String,- ) -> CustomResult<PaymentMethod, errors::StorageError> {+ ) -> CustomResult<pm_domain::PaymentMethod, errors::StorageError> {let db = &*self.store;let key_manager_state = &(self.key_manager_state).clone();diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex d14eaaf83d..0f2d36ebd6 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -29,7 +29,7 @@ vergen = ["router_env/vergen"]dummy_connector = ["api_models/dummy_connector", "euclid/dummy_connector", "hyperswitch_interfaces/dummy_connector", "kgraph_utils/dummy_connector", "payment_methods/dummy_connector", "hyperswitch_domain_models/dummy_connector"]external_access_dc = ["dummy_connector"]detailed_errors = ["api_models/detailed_errors", "error-stack/serde"]-payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors/payouts", "hyperswitch_domain_models/payouts", "storage_impl/payouts"]+payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors/payouts", "hyperswitch_domain_models/payouts", "storage_impl/payouts", "payment_methods/payouts"]payout_retry = ["payouts"]recon = ["email", "api_models/recon"]retry = []diff --git a/crates/router/src/core/cards_info.rs b/crates/router/src/core/cards_info.rsindex 577ced25d8..9b9982df65 100644--- a/crates/router/src/core/cards_info.rs+++ b/crates/router/src/core/cards_info.rs@@ -4,6 +4,7 @@ use common_utils::fp_utils::when;use csv::Reader;use diesel_models::cards_info as card_info_models;use error_stack::{report, ResultExt};+use hyperswitch_domain_models::cards_info;use rdkafka::message::ToBytes;use router_env::{instrument, tracing};@@ -12,7 +13,6 @@ use crate::{errors::{self, RouterResponse, RouterResult, StorageErrorExt},payments::helpers,},- db::cards_info::CardsInfoInterface,routes,services::ApplicationResponse,types::{@@ -62,7 +62,7 @@ pub async fn create_card_info(card_info_request: cards_info_api_types::CardInfoCreateRequest,) -> RouterResponse<cards_info_api_types::CardInfoResponse> {let db = state.store.as_ref();- CardsInfoInterface::add_card_info(db, card_info_request.foreign_into())+ cards_info::CardsInfoInterface::add_card_info(db, card_info_request.foreign_into()).await.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {message: "CardInfo with given key already exists in our records".to_string(),@@ -76,7 +76,7 @@ pub async fn update_card_info(card_info_request: cards_info_api_types::CardInfoUpdateRequest,) -> RouterResponse<cards_info_api_types::CardInfoResponse> {let db = state.store.as_ref();- CardsInfoInterface::update_card_info(+ cards_info::CardsInfoInterface::update_card_info(db,card_info_request.card_iin,card_info_models::UpdateCardInfo {@@ -196,17 +196,18 @@ impl<'a> CardInfoMigrateExecutor<'a> {async fn add_card_info(&self) -> RouterResult<card_info_models::CardInfo> {let db = self.state.store.as_ref();- let card_info = CardsInfoInterface::add_card_info(db, self.record.clone().foreign_into())- .await- .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {- message: "CardInfo with given key already exists in our records".to_string(),- })?;+ let card_info =+ cards_info::CardsInfoInterface::add_card_info(db, self.record.clone().foreign_into())+ .await+ .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {+ message: "CardInfo with given key already exists in our records".to_string(),+ })?;Ok(card_info)}async fn update_card_info(&self) -> RouterResult<card_info_models::CardInfo> {let db = self.state.store.as_ref();- let card_info = CardsInfoInterface::update_card_info(+ let card_info = cards_info::CardsInfoInterface::update_card_info(db,self.record.card_iin.clone(),card_info_models::UpdateCardInfo {diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rsindex 81a56c65ad..b4d95fe9e2 100644--- a/crates/router/src/core/customers.rs+++ b/crates/router/src/core/customers.rs@@ -10,6 +10,7 @@ use common_utils::{};use error_stack::{report, ResultExt};use masking::{ExposeInterface, Secret, SwitchStrategy};+use payment_methods::controller::PaymentMethodsController;use router_env::{instrument, tracing};#[cfg(all(feature = "v2", feature = "customer_v2"))]@@ -836,8 +837,11 @@ impl CustomerDeleteBridge for id_type::CustomerId {Ok(customer_payment_methods) => {for pm in customer_payment_methods.into_iter() {if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) {- cards::delete_card_from_locker(+ cards::PmCards {state,+ merchant_context,+ }+ .delete_card_from_locker(self,merchant_context.get_merchant_account().get_id(),pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),@@ -854,6 +858,7 @@ impl CustomerDeleteBridge for id_type::CustomerId {pm.payment_method_id.clone(),pm.network_token_locker_id,network_token_ref_id,+ merchant_context,).await.switch()?;diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rsindex 213cbfa66d..0a50ca4238 100644--- a/crates/router/src/core/errors.rs+++ b/crates/router/src/core/errors.rs@@ -7,6 +7,7 @@ pub mod utils;use std::fmt::Display;+pub use ::payment_methods::core::errors::VaultError;use actix_web::{body::BoxBody, ResponseError};pub use common_utils::errors::{CustomResult, ParsingError, ValidationError};use diesel_models::errors as storage_errors;@@ -117,46 +118,6 @@ pub enum HealthCheckOutGoing {OutGoingFailed { message: String },}-#[derive(Debug, thiserror::Error)]-pub enum VaultError {- #[error("Failed to save card in card vault")]- SaveCardFailed,- #[error("Failed to fetch card details from card vault")]- FetchCardFailed,- #[error("Failed to delete card in card vault")]- DeleteCardFailed,- #[error("Failed to encode card vault request")]- RequestEncodingFailed,- #[error("Failed to deserialize card vault response")]- ResponseDeserializationFailed,- #[error("Failed to create payment method")]- PaymentMethodCreationFailed,- #[error("The given payment method is currently not supported in vault")]- PaymentMethodNotSupported,- #[error("The given payout method is currently not supported in vault")]- PayoutMethodNotSupported,- #[error("Missing required field: {field_name}")]- MissingRequiredField { field_name: &'static str },- #[error("The card vault returned an unexpected response: {0:?}")]- UnexpectedResponseError(bytes::Bytes),- #[error("Failed to update in PMD table")]- UpdateInPaymentMethodDataTableFailed,- #[error("Failed to fetch payment method in vault")]- FetchPaymentMethodFailed,- #[error("Failed to save payment method in vault")]- SavePaymentMethodFailed,- #[error("Failed to generate fingerprint")]- GenerateFingerprintFailed,- #[error("Failed to encrypt vault request")]- RequestEncryptionFailed,- #[error("Failed to decrypt vault response")]- ResponseDecryptionFailed,- #[error("Failed to call vault")]- VaultAPIError,- #[error("Failed while calling locker API")]- ApiError,-}-#[derive(Debug, thiserror::Error)]pub enum AwsKmsError {#[error("Failed to base64 decode input data")]diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rsindex 203cc2d869..7738b67dee 100644--- a/crates/router/src/core/locker_migration.rs+++ b/crates/router/src/core/locker_migration.rs@@ -1,3 +1,4 @@+use ::payment_methods::controller::PaymentMethodsController;#[cfg(all(any(feature = "v1", feature = "v2"),not(feature = "payment_methods_v2")@@ -196,12 +197,13 @@ pub async fn call_to_locker(network_transaction_id: None,};- let add_card_result = cards::add_card_hs(- state,+ let add_card_result = cards::PmCards{+ state,+ merchant_context,+ }.add_card_hs(pm_create,&card_details,customer_id,- merchant_context,api_enums::LockerChoice::HyperswitchCardVault,Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rsindex 5084f586bb..a4dd1d2b19 100644--- a/crates/router/src/core/mandate.rs+++ b/crates/router/src/core/mandate.rs@@ -50,7 +50,7 @@ pub async fn get_mandate(&state,merchant_context.get_merchant_key_store().clone(),mandate,- merchant_context.get_merchant_account().storage_scheme,+ merchant_context.get_merchant_account(),).await?,))@@ -251,7 +251,7 @@ pub async fn get_customer_mandates(&state,merchant_context.get_merchant_key_store().clone(),mandate,- merchant_context.get_merchant_account().storage_scheme,+ merchant_context.get_merchant_account(),).await?,);@@ -415,7 +415,7 @@ pub async fn retrieve_mandates_list(&state,merchant_context.get_merchant_key_store().clone(),mandate,- merchant_context.get_merchant_account().storage_scheme,+ merchant_context.get_merchant_account(),)})).await?;diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex ab4379466e..00dfe35f79 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -1,9 +1,4 @@pub mod cards;-#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2")-))]-pub mod migration;pub mod network_tokenization;pub mod surcharge_decision_configs;#[cfg(all(diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex c228975faa..a11562c7c2 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -4,8 +4,11 @@ use std::{str::FromStr,};-use ::payment_methods::configs::payment_connector_required_fields::{- get_billing_required_fields, get_shipping_required_fields,+use ::payment_methods::{+ configs::payment_connector_required_fields::{+ get_billing_required_fields, get_shipping_required_fields,+ },+ controller::PaymentMethodsController,};#[cfg(all(any(feature = "v1", feature = "v2"),@@ -30,7 +33,7 @@ use common_utils::{consts,crypto::{self, Encryptable},encryption::Encryption,- ext_traits::{AsyncExt, BytesExt, ConfigExt, Encode, StringExt, ValueExt},+ ext_traits::{AsyncExt, BytesExt, Encode, StringExt, ValueExt},generate_id, id_type,request::Request,type_name,@@ -59,14 +62,9 @@ use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;use kgraph_utils::transformers::IntoDirValue;use masking::Secret;use router_env::{instrument, tracing};-use serde_json::json;+use scheduler::errors as sch_errors;use strum::IntoEnumIterator;-#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2")-))]-use super::migration;#[cfg(feature = "v1")]use super::surcharge_decision_configs::{perform_surcharge_decision_management_for_payment_method_list,@@ -123,1601 +121,1234 @@ use crate::{core::payment_methods as pm_core, headers, types::payment_methods as pm_types,utils::ConnectorResponseExt,};+pub struct PmCards<'a> {+ pub state: &'a routes::SessionState,+ pub merchant_context: &'a domain::MerchantContext,+}-#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2"),- not(feature = "customer_v2")-))]-#[instrument(skip_all)]-#[allow(clippy::too_many_arguments)]-pub async fn create_payment_method(- state: &routes::SessionState,- req: &api::PaymentMethodCreate,- customer_id: &id_type::CustomerId,- payment_method_id: &str,- locker_id: Option<String>,- merchant_id: &id_type::MerchantId,- pm_metadata: Option<serde_json::Value>,- customer_acceptance: Option<serde_json::Value>,- payment_method_data: crypto::OptionalEncryptableValue,- key_store: &domain::MerchantKeyStore,- connector_mandate_details: Option<serde_json::Value>,- status: Option<enums::PaymentMethodStatus>,- network_transaction_id: Option<String>,- storage_scheme: MerchantStorageScheme,- payment_method_billing_address: crypto::OptionalEncryptableValue,- card_scheme: Option<String>,- network_token_requestor_reference_id: Option<String>,- network_token_locker_id: Option<String>,- network_token_payment_method_data: crypto::OptionalEncryptableValue,-) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {- let db = &*state.store;- let customer = db- .find_customer_by_customer_id_merchant_id(- &state.into(),- customer_id,- merchant_id,- key_store,- storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;+#[async_trait::async_trait]+impl PaymentMethodsController for PmCards<'_> {+ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2"),+ not(feature = "customer_v2")+ ))]+ #[instrument(skip_all)]+ #[allow(clippy::too_many_arguments)]+ async fn create_payment_method(+ &self,+ req: &api::PaymentMethodCreate,+ customer_id: &id_type::CustomerId,+ payment_method_id: &str,+ locker_id: Option<String>,+ merchant_id: &id_type::MerchantId,+ pm_metadata: Option<serde_json::Value>,+ customer_acceptance: Option<serde_json::Value>,+ payment_method_data: crypto::OptionalEncryptableValue,+ connector_mandate_details: Option<serde_json::Value>,+ status: Option<enums::PaymentMethodStatus>,+ network_transaction_id: Option<String>,+ payment_method_billing_address: crypto::OptionalEncryptableValue,+ card_scheme: Option<String>,+ network_token_requestor_reference_id: Option<String>,+ network_token_locker_id: Option<String>,+ network_token_payment_method_data: crypto::OptionalEncryptableValue,+ ) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {+ let db = &*self.state.store;+ let customer = db+ .find_customer_by_customer_id_merchant_id(+ &self.state.into(),+ customer_id,+ merchant_id,+ self.merchant_context.get_merchant_key_store(),+ self.merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;- let client_secret = generate_id(- consts::ID_LENGTH,- format!("{payment_method_id}_secret").as_str(),- );+ let client_secret = generate_id(+ consts::ID_LENGTH,+ format!("{payment_method_id}_secret").as_str(),+ );- let current_time = common_utils::date_time::now();+ let current_time = common_utils::date_time::now();- let response = db- .insert_payment_method(- &state.into(),- key_store,- domain::PaymentMethod {- customer_id: customer_id.to_owned(),- merchant_id: merchant_id.to_owned(),- payment_method_id: payment_method_id.to_string(),- locker_id,- payment_method: req.payment_method,- payment_method_type: req.payment_method_type,- payment_method_issuer: req.payment_method_issuer.clone(),- scheme: req.card_network.clone().or(card_scheme),- metadata: pm_metadata.map(Secret::new),- payment_method_data,- connector_mandate_details,- customer_acceptance: customer_acceptance.map(Secret::new),- client_secret: Some(client_secret),- status: status.unwrap_or(enums::PaymentMethodStatus::Active),- network_transaction_id: network_transaction_id.to_owned(),- payment_method_issuer_code: None,- accepted_currency: None,- token: None,- cardholder_name: None,- issuer_name: None,- issuer_country: None,- payer_country: None,- is_stored: None,- swift_code: None,- direct_debit_token: None,- created_at: current_time,- last_modified: current_time,- last_used_at: current_time,- payment_method_billing_address,- updated_by: None,- version: common_types::consts::API_VERSION,- network_token_requestor_reference_id,- network_token_locker_id,- network_token_payment_method_data,- },- storage_scheme,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to add payment method in db")?;+ let response = db+ .insert_payment_method(+ &self.state.into(),+ self.merchant_context.get_merchant_key_store(),+ domain::PaymentMethod {+ customer_id: customer_id.to_owned(),+ merchant_id: merchant_id.to_owned(),+ payment_method_id: payment_method_id.to_string(),+ locker_id,+ payment_method: req.payment_method,+ payment_method_type: req.payment_method_type,+ payment_method_issuer: req.payment_method_issuer.clone(),+ scheme: req.card_network.clone().or(card_scheme),+ metadata: pm_metadata.map(Secret::new),+ payment_method_data,+ connector_mandate_details,+ customer_acceptance: customer_acceptance.map(Secret::new),+ client_secret: Some(client_secret),+ status: status.unwrap_or(enums::PaymentMethodStatus::Active),+ network_transaction_id: network_transaction_id.to_owned(),+ payment_method_issuer_code: None,+ accepted_currency: None,+ token: None,+ cardholder_name: None,+ issuer_name: None,+ issuer_country: None,+ payer_country: None,+ is_stored: None,+ swift_code: None,+ direct_debit_token: None,+ created_at: current_time,+ last_modified: current_time,+ last_used_at: current_time,+ payment_method_billing_address,+ updated_by: None,+ version: common_types::consts::API_VERSION,+ network_token_requestor_reference_id,+ network_token_locker_id,+ network_token_payment_method_data,+ },+ self.merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to add payment method in db")?;- if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {- let _ = set_default_payment_method(- state,- merchant_id,- key_store.clone(),- customer_id,- payment_method_id.to_owned(),- storage_scheme,- )- .await- .map_err(|error| logger::error!(?error, "Failed to set the payment method as default"));+ if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {+ let _ = self+ .set_default_payment_method(merchant_id, customer_id, payment_method_id.to_owned())+ .await+ .map_err(|error| {+ logger::error!(?error, "Failed to set the payment method as default")+ });+ }+ Ok(response)}- Ok(response)-}+ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+ ))]+ fn store_default_payment_method(+ &self,+ req: &api::PaymentMethodCreate,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ ) -> (+ api::PaymentMethodResponse,+ Option<payment_methods::DataDuplicationCheck>,+ ) {+ let pm_id = generate_id(consts::ID_LENGTH, "pm");+ let payment_method_response = api::PaymentMethodResponse {+ merchant_id: merchant_id.to_owned(),+ customer_id: Some(customer_id.to_owned()),+ payment_method_id: pm_id,+ payment_method: req.payment_method,+ payment_method_type: req.payment_method_type,+ #[cfg(feature = "payouts")]+ bank_transfer: None,+ card: None,+ metadata: req.metadata.clone(),+ created: Some(common_utils::date_time::now()),+ recurring_enabled: false, //[#219]+ installment_payment_enabled: false, //[#219]+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),+ last_used_at: Some(common_utils::date_time::now()),+ client_secret: None,+ };-#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2")-))]-pub fn store_default_payment_method(- req: &api::PaymentMethodCreate,- customer_id: &id_type::CustomerId,- merchant_id: &id_type::MerchantId,-) -> (- api::PaymentMethodResponse,- Option<payment_methods::DataDuplicationCheck>,-) {- let pm_id = generate_id(consts::ID_LENGTH, "pm");- let payment_method_response = api::PaymentMethodResponse {- merchant_id: merchant_id.to_owned(),- customer_id: Some(customer_id.to_owned()),- payment_method_id: pm_id,- payment_method: req.payment_method,- payment_method_type: req.payment_method_type,- #[cfg(feature = "payouts")]- bank_transfer: None,- card: None,- metadata: req.metadata.clone(),- created: Some(common_utils::date_time::now()),- recurring_enabled: false, //[#219]- installment_payment_enabled: false, //[#219]- payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),- last_used_at: Some(common_utils::date_time::now()),- client_secret: None,- };+ (payment_method_response, None)+ }- (payment_method_response, None)-}+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]+ fn store_default_payment_method(+ &self,+ _req: &api::PaymentMethodCreate,+ _customer_id: &id_type::CustomerId,+ _merchant_id: &id_type::MerchantId,+ ) -> (+ api::PaymentMethodResponse,+ Option<payment_methods::DataDuplicationCheck>,+ ) {+ todo!()+ }-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]-pub fn store_default_payment_method(- _req: &api::PaymentMethodCreate,- _customer_id: &id_type::CustomerId,- _merchant_id: &id_type::MerchantId,-) -> (- api::PaymentMethodResponse,- Option<payment_methods::DataDuplicationCheck>,-) {- todo!()-}-#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2")-))]-#[instrument(skip_all)]-pub async fn get_or_insert_payment_method(- state: &routes::SessionState,- req: api::PaymentMethodCreate,- resp: &mut api::PaymentMethodResponse,- merchant_context: &domain::MerchantContext,- customer_id: &id_type::CustomerId,-) -> errors::RouterResult<domain::PaymentMethod> {- let mut payment_method_id = resp.payment_method_id.clone();- let mut locker_id = None;- let db = &*state.store;- let key_manager_state = &(state.into());- let payment_method = {- let existing_pm_by_pmid = db- .find_payment_method(- key_manager_state,- merchant_context.get_merchant_key_store(),- &payment_method_id,- merchant_context.get_merchant_account().storage_scheme,- )- .await;+ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+ ))]+ #[instrument(skip_all)]+ async fn get_or_insert_payment_method(+ &self,+ req: api::PaymentMethodCreate,+ resp: &mut api::PaymentMethodResponse,+ customer_id: &id_type::CustomerId,+ key_store: &domain::MerchantKeyStore,+ ) -> errors::RouterResult<domain::PaymentMethod> {+ let mut payment_method_id = resp.payment_method_id.clone();+ let mut locker_id = None;+ let db = &*self.state.store;+ let key_manager_state = &(self.state.into());+ let payment_method = {+ let existing_pm_by_pmid = db+ .find_payment_method(+ key_manager_state,+ key_store,+ &payment_method_id,+ self.merchant_context.get_merchant_account().storage_scheme,+ )+ .await;- if let Err(err) = existing_pm_by_pmid {- if err.current_context().is_db_not_found() {- locker_id = Some(payment_method_id.clone());- let existing_pm_by_locker_id = db- .find_payment_method_by_locker_id(- key_manager_state,- merchant_context.get_merchant_key_store(),- &payment_method_id,- merchant_context.get_merchant_account().storage_scheme,- )- .await;+ if let Err(err) = existing_pm_by_pmid {+ if err.current_context().is_db_not_found() {+ locker_id = Some(payment_method_id.clone());+ let existing_pm_by_locker_id = db+ .find_payment_method_by_locker_id(+ key_manager_state,+ key_store,+ &payment_method_id,+ self.merchant_context.get_merchant_account().storage_scheme,+ )+ .await;- match &existing_pm_by_locker_id {- Ok(pm) => payment_method_id.clone_from(pm.get_id()),- Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"),- };- existing_pm_by_locker_id+ match &existing_pm_by_locker_id {+ Ok(pm) => payment_method_id.clone_from(pm.get_id()),+ Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"),+ };+ existing_pm_by_locker_id+ } else {+ Err(err)+ }} else {- Err(err)+ existing_pm_by_pmid}- } else {- existing_pm_by_pmid- }- };- payment_method_id.clone_into(&mut resp.payment_method_id);-- match payment_method {- Ok(pm) => Ok(pm),- Err(err) => {- if err.current_context().is_db_not_found() {- insert_payment_method(- state,- resp,- &req,- merchant_context.get_merchant_key_store(),- merchant_context.get_merchant_account().get_id(),- customer_id,- resp.metadata.clone().map(|val| val.expose()),- None,- locker_id,- None,- req.network_transaction_id.clone(),- merchant_context.get_merchant_account().storage_scheme,- None,- None,- None,- None,- )- .await- } else {- Err(err)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Error while finding payment method")+ };+ payment_method_id.clone_into(&mut resp.payment_method_id);++ match payment_method {+ Ok(pm) => Ok(pm),+ Err(err) => {+ if err.current_context().is_db_not_found() {+ self.insert_payment_method(+ resp,+ &req,+ key_store,+ self.merchant_context.get_merchant_account().get_id(),+ customer_id,+ resp.metadata.clone().map(|val| val.expose()),+ None,+ locker_id,+ None,+ req.network_transaction_id.clone(),+ None,+ None,+ None,+ None,+ )+ .await+ } else {+ Err(err)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Error while finding payment method")+ }}}}-}-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]-#[instrument(skip_all)]-pub async fn get_or_insert_payment_method(- _state: &routes::SessionState,- _req: api::PaymentMethodCreate,- _resp: &mut api::PaymentMethodResponse,- _merchant_context: &domain::MerchantContext,- _customer_id: &id_type::CustomerId,-) -> errors::RouterResult<domain::PaymentMethod> {- todo!()-}+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]+ async fn get_or_insert_payment_method(+ &self,+ _req: api::PaymentMethodCreate,+ _resp: &mut api::PaymentMethodResponse,+ _customer_id: &id_type::CustomerId,+ _key_store: &domain::MerchantKeyStore,+ ) -> errors::RouterResult<domain::PaymentMethod> {+ todo!()+ }-#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2")-))]-pub async fn migrate_payment_method(- state: routes::SessionState,- req: api::PaymentMethodMigrate,- merchant_id: &id_type::MerchantId,- merchant_context: &domain::MerchantContext,-) -> errors::RouterResponse<api::PaymentMethodMigrateResponse> {- let mut req = req;- let card_details = &req.card.get_required_value("card")?;-- let card_number_validation_result =- cards::CardNumber::from_str(card_details.card_number.peek());-- let card_bin_details =- populate_bin_details_for_masked_card(card_details, &*state.store).await?;-- req.card = Some(api_models::payment_methods::MigrateCardDetail {- card_issuing_country: card_bin_details.issuer_country.clone(),- card_network: card_bin_details.card_network.clone(),- card_issuer: card_bin_details.card_issuer.clone(),- card_type: card_bin_details.card_type.clone(),- ..card_details.clone()- });+ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2"),+ not(feature = "customer_v2")+ ))]+ #[allow(clippy::too_many_arguments)]+ async fn save_network_token_and_update_payment_method(+ &self,+ req: &api::PaymentMethodMigrate,+ key_store: &domain::MerchantKeyStore,+ network_token_data: &api_models::payment_methods::MigrateNetworkTokenData,+ network_token_requestor_ref_id: String,+ pm_id: String,+ ) -> errors::RouterResult<bool> {+ let payment_method_create_request =+ api::PaymentMethodCreate::get_payment_method_create_from_payment_method_migrate(+ network_token_data.network_token_number.clone(),+ req,+ );+ let customer_id = req.customer_id.clone().get_required_value("customer_id")?;++ let network_token_details = api::CardDetail {+ card_number: network_token_data.network_token_number.clone(),+ card_exp_month: network_token_data.network_token_exp_month.clone(),+ card_exp_year: network_token_data.network_token_exp_year.clone(),+ card_holder_name: network_token_data.card_holder_name.clone(),+ nick_name: network_token_data.nick_name.clone(),+ card_issuing_country: network_token_data.card_issuing_country.clone(),+ card_network: network_token_data.card_network.clone(),+ card_issuer: network_token_data.card_issuer.clone(),+ card_type: network_token_data.card_type.clone(),+ };- if let Some(connector_mandate_details) = &req.connector_mandate_details {- helpers::validate_merchant_connector_ids_in_connector_mandate_details(- &state,- merchant_context.get_merchant_key_store(),- connector_mandate_details,- merchant_id,- card_bin_details.card_network.clone(),- )- .await?;- };+ logger::debug!(+ "Adding network token to locker for customer_id: {:?}",+ customer_id+ );- let should_require_connector_mandate_details = req.network_token.is_none();+ let token_resp = Box::pin(self.add_card_to_locker(+ payment_method_create_request.clone(),+ &network_token_details,+ &customer_id,+ None,+ ))+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Add Network Token failed");+ let key_manager_state = &self.state.into();++ match token_resp {+ Ok(resp) => {+ logger::debug!("Network token added to locker");+ let (token_pm_resp, _duplication_check) = resp;+ let pm_token_details = token_pm_resp.card.as_ref().map(|card| {+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))+ });+ let pm_network_token_data_encrypted = pm_token_details+ .async_map(|pm_card| {+ create_encrypted_data(key_manager_state, key_store, pm_card)+ })+ .await+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt payment method data")?;- let mut migration_status = migration::RecordMigrationStatusBuilder::new();+ let pm_update = storage::PaymentMethodUpdate::NetworkTokenDataUpdate {+ network_token_requestor_reference_id: Some(network_token_requestor_ref_id),+ network_token_locker_id: Some(token_pm_resp.payment_method_id),+ network_token_payment_method_data: pm_network_token_data_encrypted+ .map(Into::into),+ };+ let db = &*self.state.store;+ let existing_pm = db+ .find_payment_method(+ &self.state.into(),+ key_store,+ &pm_id,+ self.merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(format!(+ "Failed to fetch payment method for existing pm_id: {:?} in db",+ pm_id+ ))?;- let resp = match card_number_validation_result {- Ok(card_number) => {- let payment_method_create_request =- api::PaymentMethodCreate::get_payment_method_create_from_payment_method_migrate(- card_number,- &req,- );+ db.update_payment_method(+ &self.state.into(),+ key_store,+ existing_pm,+ pm_update,+ self.merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(format!(+ "Failed to update payment method for existing pm_id: {:?} in db",+ pm_id+ ))?;- logger::debug!("Storing the card in locker and migrating the payment method");- get_client_secret_or_add_payment_method_for_migration(- &state,- payment_method_create_request,- merchant_context,- &mut migration_status,- )- .await?- }- Err(card_validation_error) => {- logger::debug!("Card number to be migrated is invalid, skip saving in locker {card_validation_error}");- skip_locker_call_and_migrate_payment_method(- &state,- &req,- merchant_id.to_owned(),- merchant_context,- card_bin_details.clone(),- should_require_connector_mandate_details,- &mut migration_status,- )- .await?+ logger::debug!("Network token added to locker and payment method updated");+ Ok(true)+ }+ Err(err) => {+ logger::debug!("Network token added to locker failed {:?}", err);+ Ok(false)+ }}- };- let payment_method_response = match resp {- services::ApplicationResponse::Json(response) => response,- _ => Err(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to fetch the payment method response")?,- };+ }- let pm_id = payment_method_response.payment_method_id.clone();+ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+ ))]+ #[allow(clippy::too_many_arguments)]+ async fn insert_payment_method(+ &self,+ resp: &api::PaymentMethodResponse,+ req: &api::PaymentMethodCreate,+ key_store: &domain::MerchantKeyStore,+ merchant_id: &id_type::MerchantId,+ customer_id: &id_type::CustomerId,+ pm_metadata: Option<serde_json::Value>,+ customer_acceptance: Option<serde_json::Value>,+ locker_id: Option<String>,+ connector_mandate_details: Option<serde_json::Value>,+ network_transaction_id: Option<String>,+ payment_method_billing_address: crypto::OptionalEncryptableValue,+ network_token_requestor_reference_id: Option<String>,+ network_token_locker_id: Option<String>,+ network_token_payment_method_data: crypto::OptionalEncryptableValue,+ ) -> errors::RouterResult<domain::PaymentMethod> {+ let pm_card_details = resp+ .card+ .clone()+ .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())));+ let key_manager_state = self.state.into();+ let pm_data_encrypted: crypto::OptionalEncryptableValue = pm_card_details+ .clone()+ .async_map(|pm_card| create_encrypted_data(&key_manager_state, key_store, pm_card))+ .await+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt payment method data")?;- let network_token = req.network_token.clone();+ self.create_payment_method(+ req,+ customer_id,+ &resp.payment_method_id,+ locker_id,+ merchant_id,+ pm_metadata,+ customer_acceptance,+ pm_data_encrypted,+ connector_mandate_details,+ None,+ network_transaction_id,+ payment_method_billing_address,+ resp.card.clone().and_then(|card| {+ card.card_network+ .map(|card_network| card_network.to_string())+ }),+ network_token_requestor_reference_id,+ network_token_locker_id,+ network_token_payment_method_data,+ )+ .await+ }- let network_token_migrated = match network_token {- Some(nt_detail) => {- logger::debug!("Network token migration");- let network_token_requestor_ref_id = nt_detail.network_token_requestor_ref_id.clone();- let network_token_data = &nt_detail.network_token_data;+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]+ #[allow(clippy::too_many_arguments)]+ async fn insert_payment_method(+ &self,+ resp: &api::PaymentMethodResponse,+ req: &api::PaymentMethodCreate,+ key_store: &domain::MerchantKeyStore,+ merchant_id: &id_type::MerchantId,+ customer_id: &id_type::CustomerId,+ pm_metadata: Option<serde_json::Value>,+ customer_acceptance: Option<serde_json::Value>,+ locker_id: Option<String>,+ connector_mandate_details: Option<serde_json::Value>,+ network_transaction_id: Option<String>,+ payment_method_billing_address: Option<Encryption>,+ ) -> errors::RouterResult<domain::PaymentMethod> {+ todo!()+ }- Some(- save_network_token_and_update_payment_method(- &state,- &req,- merchant_context,- network_token_data,- network_token_requestor_ref_id,- pm_id,- )- .await- .map_err(|err| logger::error!(?err, "Failed to save network token"))+ #[cfg(feature = "payouts")]+ async fn add_bank_to_locker(+ &self,+ req: api::PaymentMethodCreate,+ key_store: &domain::MerchantKeyStore,+ bank: &api::BankPayout,+ customer_id: &id_type::CustomerId,+ ) -> errors::CustomResult<+ (+ api::PaymentMethodResponse,+ Option<payment_methods::DataDuplicationCheck>,+ ),+ errors::VaultError,+ > {+ let key = key_store.key.get_inner().peek();+ let payout_method_data = api::PayoutMethodData::Bank(bank.clone());+ let key_manager_state: KeyManagerState = self.state.into();+ let enc_data = async {+ serde_json::to_value(payout_method_data.to_owned())+ .map_err(|err| {+ logger::error!("Error while encoding payout method data: {err:?}");+ errors::VaultError::SavePaymentMethodFailed+ })+ .change_context(errors::VaultError::SavePaymentMethodFailed)+ .attach_printable("Unable to encode payout method data").ok()- .unwrap_or_default(),- )- }- None => {- logger::debug!("Network token data is not available");- None- }- };- migration_status.network_token_migrated(network_token_migrated);- let migrate_status = migration_status.build();-- Ok(services::ApplicationResponse::Json(- api::PaymentMethodMigrateResponse {- payment_method_response,- card_migrated: migrate_status.card_migrated,- network_token_migrated: migrate_status.network_token_migrated,- connector_mandate_details_migrated: migrate_status.connector_mandate_details_migrated,- network_transaction_id_migrated: migrate_status.network_transaction_migrated,- },- ))-}+ .map(|v| {+ let secret: Secret<String> = Secret::new(v.to_string());+ secret+ })+ .async_lift(|inner| async {+ domain::types::crypto_operation(+ &key_manager_state,+ type_name!(payment_method::PaymentMethod),+ domain::types::CryptoOperation::EncryptOptional(inner),+ Identifier::Merchant(key_store.merchant_id.clone()),+ key,+ )+ .await+ .and_then(|val| val.try_into_optionaloperation())+ })+ .await+ }+ .await+ .change_context(errors::VaultError::SavePaymentMethodFailed)+ .attach_printable("Failed to encrypt payout method data")?+ .map(Encryption::from)+ .map(|e| e.into_inner())+ .map_or(Err(errors::VaultError::SavePaymentMethodFailed), |e| {+ Ok(hex::encode(e.peek()))+ })?;-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]-pub async fn migrate_payment_method(- _state: routes::SessionState,- _req: api::PaymentMethodMigrate,- _merchant_id: &id_type::MerchantId,- _merchant_context: &domain::MerchantContext,-) -> errors::RouterResponse<api::PaymentMethodMigrateResponse> {- todo!()-}+ let payload =+ payment_methods::StoreLockerReq::LockerGeneric(payment_methods::StoreGenericReq {+ merchant_id: self+ .merchant_context+ .get_merchant_account()+ .get_id()+ .to_owned(),+ merchant_customer_id: customer_id.to_owned(),+ enc_data,+ ttl: self.state.conf.locker.ttl_for_storage_in_secs,+ });+ let store_resp = add_card_to_hs_locker(+ self.state,+ &payload,+ customer_id,+ api_enums::LockerChoice::HyperswitchCardVault,+ )+ .await?;+ let payment_method_resp = payment_methods::mk_add_bank_response_hs(+ bank.clone(),+ store_resp.card_reference,+ req,+ self.merchant_context.get_merchant_account().get_id(),+ );+ Ok((payment_method_resp, store_resp.duplication_check))+ }-#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2")-))]-pub async fn populate_bin_details_for_masked_card(- card_details: &api_models::payment_methods::MigrateCardDetail,- db: &dyn db::StorageInterface,-) -> errors::CustomResult<api::CardDetailFromLocker, errors::ApiErrorResponse> {- migration::validate_card_expiry(&card_details.card_exp_month, &card_details.card_exp_year)?;- let card_number = card_details.card_number.clone();+ /// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method+ async fn add_card_to_locker(+ &self,+ req: api::PaymentMethodCreate,+ card: &api::CardDetail,+ customer_id: &id_type::CustomerId,+ card_reference: Option<&str>,+ ) -> errors::CustomResult<+ (+ api::PaymentMethodResponse,+ Option<payment_methods::DataDuplicationCheck>,+ ),+ errors::VaultError,+ > {+ metrics::STORED_TO_LOCKER.add(1, &[]);+ let add_card_to_hs_resp = Box::pin(common_utils::metrics::utils::record_operation_time(+ async {+ self.add_card_hs(+ req.clone(),+ card,+ customer_id,+ api_enums::LockerChoice::HyperswitchCardVault,+ card_reference,+ )+ .await+ .inspect_err(|_| {+ metrics::CARD_LOCKER_FAILURES.add(+ 1,+ router_env::metric_attributes!(("locker", "rust"), ("operation", "add")),+ );+ })+ },+ &metrics::CARD_ADD_TIME,+ router_env::metric_attributes!(("locker", "rust")),+ ))+ .await?;- let (card_isin, _last4_digits) = get_card_bin_and_last4_digits_for_masked_card(- card_number.peek(),- )- .change_context(errors::ApiErrorResponse::InvalidRequestData {- message: "Invalid card number".to_string(),- })?;-- let card_bin_details = if card_details.card_issuer.is_some()- && card_details.card_network.is_some()- && card_details.card_type.is_some()- && card_details.card_issuing_country.is_some()- {- api_models::payment_methods::CardDetailFromLocker::foreign_try_from((card_details, None))?- } else {- let card_info = db- .get_card_info(&card_isin)- .await- .map_err(|error| services::logger::error!(card_info_error=?error))- .ok()- .flatten();-- api_models::payment_methods::CardDetailFromLocker::foreign_try_from((- card_details,- card_info,- ))?- };- Ok(card_bin_details)-}+ logger::debug!("card added to hyperswitch-card-vault");+ Ok(add_card_to_hs_resp)+ }-#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2")-))]-impl- ForeignTryFrom<(- &api_models::payment_methods::MigrateCardDetail,- Option<diesel_models::CardInfo>,- )> for api_models::payment_methods::CardDetailFromLocker-{- type Error = error_stack::Report<errors::ApiErrorResponse>;- fn foreign_try_from(- (card_details, card_info): (- &api_models::payment_methods::MigrateCardDetail,- Option<diesel_models::CardInfo>,- ),- ) -> Result<Self, Self::Error> {- let (card_isin, last4_digits) =- get_card_bin_and_last4_digits_for_masked_card(card_details.card_number.peek())- .change_context(errors::ApiErrorResponse::InvalidRequestData {- message: "Invalid card number".to_string(),- })?;- if let Some(card_bin_info) = card_info {- Ok(Self {- scheme: card_details- .card_network- .clone()- .or(card_bin_info.card_network.clone())- .map(|card_network| card_network.to_string()),- last4_digits: Some(last4_digits.clone()),- issuer_country: card_details- .card_issuing_country- .clone()- .or(card_bin_info.card_issuing_country),- card_number: None,- expiry_month: Some(card_details.card_exp_month.clone()),- expiry_year: Some(card_details.card_exp_year.clone()),- card_token: None,- card_fingerprint: None,- card_holder_name: card_details.card_holder_name.clone(),- nick_name: card_details.nick_name.clone(),- card_isin: Some(card_isin.clone()),- card_issuer: card_details- .card_issuer- .clone()- .or(card_bin_info.card_issuer),- card_network: card_details- .card_network- .clone()- .or(card_bin_info.card_network),- card_type: card_details.card_type.clone().or(card_bin_info.card_type),- saved_to_locker: false,- })- } else {- Ok(Self {- scheme: card_details- .card_network- .clone()- .map(|card_network| card_network.to_string()),- last4_digits: Some(last4_digits.clone()),- issuer_country: card_details.card_issuing_country.clone(),- card_number: None,- expiry_month: Some(card_details.card_exp_month.clone()),- expiry_year: Some(card_details.card_exp_year.clone()),- card_token: None,- card_fingerprint: None,- card_holder_name: card_details.card_holder_name.clone(),- nick_name: card_details.nick_name.clone(),- card_isin: Some(card_isin.clone()),- card_issuer: card_details.card_issuer.clone(),- card_network: card_details.card_network.clone(),- card_type: card_details.card_type.clone(),- saved_to_locker: false,- })- }+ async fn delete_card_from_locker(+ &self,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ card_reference: &str,+ ) -> errors::RouterResult<payment_methods::DeleteCardResp> {+ metrics::DELETE_FROM_LOCKER.add(1, &[]);++ common_utils::metrics::utils::record_operation_time(+ async move {+ delete_card_from_hs_locker(self.state, customer_id, merchant_id, card_reference)+ .await+ .inspect_err(|_| {+ metrics::CARD_LOCKER_FAILURES.add(+ 1,+ router_env::metric_attributes!(+ ("locker", "rust"),+ ("operation", "delete")+ ),+ );+ })+ },+ &metrics::CARD_DELETE_TIME,+ &[],+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed while deleting card from locker")}-}-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]-impl- ForeignTryFrom<(- &api_models::payment_methods::MigrateCardDetail,- Option<diesel_models::CardInfo>,- )> for api_models::payment_methods::CardDetailFromLocker-{- type Error = error_stack::Report<errors::ApiErrorResponse>;- fn foreign_try_from(- (card_details, card_info): (- &api_models::payment_methods::MigrateCardDetail,- Option<diesel_models::CardInfo>,+ #[instrument(skip_all)]+ async fn add_card_hs(+ &self,+ req: api::PaymentMethodCreate,+ card: &api::CardDetail,+ customer_id: &id_type::CustomerId,+ locker_choice: api_enums::LockerChoice,+ card_reference: Option<&str>,+ ) -> errors::CustomResult<+ (+ api::PaymentMethodResponse,+ Option<payment_methods::DataDuplicationCheck>,),- ) -> Result<Self, Self::Error> {- let (card_isin, last4_digits) =- get_card_bin_and_last4_digits_for_masked_card(card_details.card_number.peek())- .change_context(errors::ApiErrorResponse::InvalidRequestData {- message: "Invalid card number".to_string(),- })?;- if let Some(card_bin_info) = card_info {- Ok(Self {- last4_digits: Some(last4_digits.clone()),- issuer_country: card_details- .card_issuing_country- .as_ref()- .map(|c| api_enums::CountryAlpha2::from_str(c))- .transpose()- .ok()- .flatten()- .or(card_bin_info- .card_issuing_country- .as_ref()- .map(|c| api_enums::CountryAlpha2::from_str(c))- .transpose()- .ok()- .flatten()),- card_number: None,- expiry_month: Some(card_details.card_exp_month.clone()),- expiry_year: Some(card_details.card_exp_year.clone()),- card_fingerprint: None,- card_holder_name: card_details.card_holder_name.clone(),- nick_name: card_details.nick_name.clone(),- card_isin: Some(card_isin.clone()),- card_issuer: card_details- .card_issuer- .clone()- .or(card_bin_info.card_issuer),- card_network: card_details- .card_network- .clone()- .or(card_bin_info.card_network),- card_type: card_details.card_type.clone().or(card_bin_info.card_type),- saved_to_locker: false,- })- } else {- Ok(Self {- last4_digits: Some(last4_digits.clone()),- issuer_country: card_details- .card_issuing_country- .as_ref()- .map(|c| api_enums::CountryAlpha2::from_str(c))- .transpose()- .ok()- .flatten(),- card_number: None,- expiry_month: Some(card_details.card_exp_month.clone()),- expiry_year: Some(card_details.card_exp_year.clone()),- card_fingerprint: None,- card_holder_name: card_details.card_holder_name.clone(),- nick_name: card_details.nick_name.clone(),- card_isin: Some(card_isin.clone()),- card_issuer: card_details.card_issuer.clone(),- card_network: card_details.card_network.clone(),- card_type: card_details.card_type.clone(),- saved_to_locker: false,- })- }- }-}+ errors::VaultError,+ > {+ let payload = payment_methods::StoreLockerReq::LockerCard(payment_methods::StoreCardReq {+ merchant_id: self+ .merchant_context+ .get_merchant_account()+ .get_id()+ .to_owned(),+ merchant_customer_id: customer_id.to_owned(),+ requestor_card_reference: card_reference.map(str::to_string),+ card: Card {+ card_number: card.card_number.to_owned(),+ name_on_card: card.card_holder_name.to_owned(),+ card_exp_month: card.card_exp_month.to_owned(),+ card_exp_year: card.card_exp_year.to_owned(),+ card_brand: card.card_network.as_ref().map(ToString::to_string),+ card_isin: None,+ nick_name: card.nick_name.as_ref().map(Secret::peek).cloned(),+ },+ ttl: self.state.conf.locker.ttl_for_storage_in_secs,+ });-#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2"),- not(feature = "customer_v2")-))]-#[allow(clippy::too_many_arguments)]-pub async fn skip_locker_call_and_migrate_payment_method(- state: &routes::SessionState,- req: &api::PaymentMethodMigrate,- merchant_id: id_type::MerchantId,- merchant_context: &domain::MerchantContext,- card: api_models::payment_methods::CardDetailFromLocker,- should_require_connector_mandate_details: bool,- migration_status: &mut migration::RecordMigrationStatusBuilder,-) -> errors::RouterResponse<api::PaymentMethodResponse> {- let db = &*state.store;- let customer_id = req.customer_id.clone().get_required_value("customer_id")?;+ let store_card_payload =+ add_card_to_hs_locker(self.state, &payload, customer_id, locker_choice).await?;- // In this case, since we do not have valid card details, recurring payments can only be done through connector mandate details.- //if network token data is present, then connector mandate details are not mandatory+ let payment_method_resp = payment_methods::mk_add_card_response_hs(+ card.clone(),+ store_card_payload.card_reference,+ req,+ self.merchant_context.get_merchant_account().get_id(),+ );+ Ok((payment_method_resp, store_card_payload.duplication_check))+ }- let connector_mandate_details = if should_require_connector_mandate_details {- let connector_mandate_details_req = req- .connector_mandate_details+ #[cfg(all(+ any(feature = "v2", feature = "v1"),+ not(feature = "payment_methods_v2")+ ))]+ async fn get_card_details_with_locker_fallback(+ &self,+ pm: &domain::PaymentMethod,+ ) -> errors::RouterResult<Option<api::CardDetailFromLocker>> {+ let card_decrypted = pm+ .payment_method_data.clone()- .get_required_value("connector mandate details")?;+ .map(|x| x.into_inner().expose())+ .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())+ .and_then(|pmd| match pmd {+ PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),+ _ => None,+ });- Some(- serde_json::to_value(&connector_mandate_details_req)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse connector mandate details")?,- )- } else {- req.connector_mandate_details+ Ok(if let Some(mut crd) = card_decrypted {+ crd.scheme.clone_from(&pm.scheme);+ Some(crd)+ } else {+ logger::debug!(+ "Getting card details from locker as it is not found in payment methods table"+ );+ Some(get_card_details_from_locker(self.state, pm).await?)+ })+ }++ #[cfg(all(+ any(feature = "v2", feature = "v1"),+ not(feature = "payment_methods_v2")+ ))]+ async fn get_card_details_without_locker_fallback(+ &self,+ pm: &domain::PaymentMethod,+ ) -> errors::RouterResult<api::CardDetailFromLocker> {+ let card_decrypted = pm+ .payment_method_data.clone()- .map(|connector_mandate_details_req| {- serde_json::to_value(&connector_mandate_details_req)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse connector mandate details")- })- .transpose()?- };- let key_manager_state = &state.into();- let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req- .billing- .clone()- .async_map(|billing| {- create_encrypted_data(+ .map(|x| x.into_inner().expose())+ .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())+ .and_then(|pmd| match pmd {+ PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),+ _ => None,+ });++ Ok(if let Some(mut crd) = card_decrypted {+ crd.scheme.clone_from(&pm.scheme);+ crd+ } else {+ logger::debug!(+ "Getting card details from locker as it is not found in payment methods table"+ );+ get_card_details_from_locker(self.state, pm).await?+ })+ }++ #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]+ async fn set_default_payment_method(+ &self,+ merchant_id: &id_type::MerchantId,+ customer_id: &id_type::CustomerId,+ payment_method_id: String,+ ) -> errors::RouterResponse<api_models::payment_methods::CustomerDefaultPaymentMethodResponse>+ {+ let db = &*self.state.store;+ let key_manager_state = &self.state.into();+ // check for the customer+ // TODO: customer need not be checked again here, this function can take an optional customer and check for existence of customer based on the optional value+ let customer = db+ .find_customer_by_customer_id_merchant_id(key_manager_state,- merchant_context.get_merchant_key_store(),- billing,+ customer_id,+ merchant_id,+ self.merchant_context.get_merchant_key_store(),+ self.merchant_context.get_merchant_account().storage_scheme,)- })- .await- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt Payment method billing address")?;+ .await+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;+ // check for the presence of payment_method+ let payment_method = db+ .find_payment_method(+ &(self.state.into()),+ self.merchant_context.get_merchant_key_store(),+ &payment_method_id,+ self.merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;+ let pm = payment_method+ .get_payment_method_type()+ .get_required_value("payment_method")?;- let customer = db- .find_customer_by_customer_id_merchant_id(- &state.into(),- &customer_id,- &merchant_id,- merchant_context.get_merchant_key_store(),- merchant_context.get_merchant_account().storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;+ utils::when(+ &payment_method.customer_id != customer_id+ || payment_method.merchant_id != *merchant_id,+ || {+ Err(errors::ApiErrorResponse::PreconditionFailed {+ message: "The payment_method_id is not valid".to_string(),+ })+ },+ )?;- let payment_method_card_details =- PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()));+ utils::when(+ Some(payment_method_id.clone()) == customer.default_payment_method_id,+ || {+ Err(errors::ApiErrorResponse::PreconditionFailed {+ message: "Payment Method is already set as default".to_string(),+ })+ },+ )?;- let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = Some(- create_encrypted_data(- key_manager_state,- merchant_context.get_merchant_key_store(),- payment_method_card_details,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt Payment method card details")?,- );+ let customer_id = customer.customer_id.clone();- let payment_method_metadata: Option<serde_json::Value> =- req.metadata.as_ref().map(|data| data.peek()).cloned();+ let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {+ default_payment_method_id: Some(Some(payment_method_id.to_owned())),+ };+ // update the db with the default payment method id- let network_transaction_id = req.network_transaction_id.clone();+ let updated_customer_details = db+ .update_customer_by_customer_id_merchant_id(+ key_manager_state,+ customer_id.to_owned(),+ merchant_id.to_owned(),+ customer,+ customer_update,+ self.merchant_context.get_merchant_key_store(),+ self.merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to update the default payment method id for the customer")?;- let payment_method_id = generate_id(consts::ID_LENGTH, "pm");+ let resp = api_models::payment_methods::CustomerDefaultPaymentMethodResponse {+ default_payment_method_id: updated_customer_details.default_payment_method_id,+ customer_id,+ payment_method_type: payment_method.get_payment_method_subtype(),+ payment_method: pm,+ };- let current_time = common_utils::date_time::now();+ Ok(services::ApplicationResponse::Json(resp))+ }- let response = db- .insert_payment_method(- &state.into(),- merchant_context.get_merchant_key_store(),- domain::PaymentMethod {- customer_id: customer_id.to_owned(),- merchant_id: merchant_id.to_owned(),- payment_method_id: payment_method_id.to_string(),- locker_id: None,- payment_method: req.payment_method,- payment_method_type: req.payment_method_type,- payment_method_issuer: req.payment_method_issuer.clone(),- scheme: req.card_network.clone().or(card.scheme.clone()),- metadata: payment_method_metadata.map(Secret::new),- payment_method_data: payment_method_data_encrypted,- connector_mandate_details: connector_mandate_details.clone(),- customer_acceptance: None,- client_secret: None,- status: enums::PaymentMethodStatus::Active,- network_transaction_id: network_transaction_id.clone(),- payment_method_issuer_code: None,- accepted_currency: None,- token: None,- cardholder_name: None,- issuer_name: None,- issuer_country: None,- payer_country: None,- is_stored: None,- swift_code: None,- direct_debit_token: None,- created_at: current_time,- last_modified: current_time,- last_used_at: current_time,- payment_method_billing_address,- updated_by: None,- version: common_types::consts::API_VERSION,- network_token_requestor_reference_id: None,- network_token_locker_id: None,- network_token_payment_method_data: None,- },- merchant_context.get_merchant_account().storage_scheme,+ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+ ))]+ async fn add_payment_method_status_update_task(+ &self,+ payment_method: &domain::PaymentMethod,+ prev_status: common_enums::PaymentMethodStatus,+ curr_status: common_enums::PaymentMethodStatus,+ merchant_id: &id_type::MerchantId,+ ) -> Result<(), sch_errors::ProcessTrackerError> {+ add_payment_method_status_update_task(+ &*self.state.store,+ payment_method,+ prev_status,+ curr_status,+ merchant_id,).await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to add payment method in db")?;-- logger::debug!("Payment method inserted in db");-- migration_status.network_transaction_id_migrated(- network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)),- );-- migration_status.connector_mandate_details_migrated(- connector_mandate_details- .clone()- .and_then(|val| if val == json!({}) { None } else { Some(true) })- .or_else(|| {- req.connector_mandate_details.clone().and_then(|val| {- val.payments- .and_then(|payin_val| (!payin_val.0.is_empty()).then_some(false))- })- }),- );+ }- if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {- let _ = set_default_payment_method(- state,- &merchant_id,- merchant_context.get_merchant_key_store().clone(),- &customer_id,- payment_method_id.to_owned(),- merchant_context.get_merchant_account().storage_scheme,+ #[cfg(feature = "v1")]+ async fn validate_merchant_connector_ids_in_connector_mandate_details(+ &self,+ key_store: &domain::MerchantKeyStore,+ connector_mandate_details: &api_models::payment_methods::CommonMandateReference,+ merchant_id: &id_type::MerchantId,+ card_network: Option<common_enums::CardNetwork>,+ ) -> errors::RouterResult<()> {+ helpers::validate_merchant_connector_ids_in_connector_mandate_details(+ self.state,+ key_store,+ connector_mandate_details,+ merchant_id,+ card_network,).await- .map_err(|error| logger::error!(?error, "Failed to set the payment method as default"));}- Ok(services::api::ApplicationResponse::Json(- api::PaymentMethodResponse::foreign_from((Some(card), response)),- ))-}--#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2"),- not(feature = "customer_v2")-))]-#[allow(clippy::too_many_arguments)]-pub async fn save_network_token_and_update_payment_method(- state: &routes::SessionState,- req: &api::PaymentMethodMigrate,- merchant_context: &domain::MerchantContext,- network_token_data: &api_models::payment_methods::MigrateNetworkTokenData,- network_token_requestor_ref_id: String,- pm_id: String,-) -> errors::RouterResult<bool> {- let payment_method_create_request =- api::PaymentMethodCreate::get_payment_method_create_from_payment_method_migrate(- network_token_data.network_token_number.clone(),- req,- );- let customer_id = req.customer_id.clone().get_required_value("customer_id")?;-- let network_token_details = api::CardDetail {- card_number: network_token_data.network_token_number.clone(),- card_exp_month: network_token_data.network_token_exp_month.clone(),- card_exp_year: network_token_data.network_token_exp_year.clone(),- card_holder_name: network_token_data.card_holder_name.clone(),- nick_name: network_token_data.nick_name.clone(),- card_issuing_country: network_token_data.card_issuing_country.clone(),- card_network: network_token_data.card_network.clone(),- card_issuer: network_token_data.card_issuer.clone(),- card_type: network_token_data.card_type.clone(),- };- logger::debug!(- "Adding network token to locker for customer_id: {:?}",- customer_id- );+ #[cfg(all(+ any(feature = "v2", feature = "v1"),+ not(feature = "payment_methods_v2")+ ))]+ #[instrument(skip_all)]+ async fn retrieve_payment_method(+ &self,+ pm: api::PaymentMethodId,+ ) -> errors::RouterResponse<api::PaymentMethodResponse> {+ let db = self.state.store.as_ref();+ let pm = db+ .find_payment_method(+ &self.state.into(),+ self.merchant_context.get_merchant_key_store(),+ &pm.payment_method_id,+ self.merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;- let token_resp = Box::pin(add_card_to_locker(- state,- payment_method_create_request.clone(),- &network_token_details,- &customer_id,- merchant_context,- None,- ))- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Add Network Token failed");- let key_manager_state = &state.into();-- match token_resp {- Ok(resp) => {- logger::debug!("Network token added to locker");- let (token_pm_resp, _duplication_check) = resp;- let pm_token_details = token_pm_resp- .card- .as_ref()- .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())));- let pm_network_token_data_encrypted = pm_token_details- .async_map(|pm_card| {- create_encrypted_data(- key_manager_state,- merchant_context.get_merchant_key_store(),- pm_card,- )- })- .await- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt payment method data")?;-- let pm_update = storage::PaymentMethodUpdate::NetworkTokenDataUpdate {- network_token_requestor_reference_id: Some(network_token_requestor_ref_id),- network_token_locker_id: Some(token_pm_resp.payment_method_id),- network_token_payment_method_data: pm_network_token_data_encrypted.map(Into::into),- };- let db = &*state.store;- let existing_pm = db- .find_payment_method(- &state.into(),- merchant_context.get_merchant_key_store(),- &pm_id,- merchant_context.get_merchant_account().storage_scheme,+ let card = if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) {+ let card_detail = if self.state.conf.locker.locker_enabled {+ let card = get_card_from_locker(+ self.state,+ &pm.customer_id,+ &pm.merchant_id,+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),).await.change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(format!(- "Failed to fetch payment method for existing pm_id: {:?} in db",- pm_id- ))?;+ .attach_printable("Error getting card from card vault")?;+ payment_methods::get_card_detail(&pm, card)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed while getting card details from locker")?+ } else {+ self.get_card_details_without_locker_fallback(&pm).await?+ };+ Some(card_detail)+ } else {+ None+ };+ Ok(services::ApplicationResponse::Json(+ api::PaymentMethodResponse {+ merchant_id: pm.merchant_id.clone(),+ customer_id: Some(pm.customer_id.clone()),+ payment_method_id: pm.payment_method_id.clone(),+ payment_method: pm.get_payment_method_type(),+ payment_method_type: pm.get_payment_method_subtype(),+ #[cfg(feature = "payouts")]+ bank_transfer: None,+ card,+ metadata: pm.metadata,+ created: Some(pm.created_at),+ recurring_enabled: false,+ installment_payment_enabled: false,+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),+ last_used_at: Some(pm.last_used_at),+ client_secret: pm.client_secret,+ },+ ))+ }- db.update_payment_method(- &state.into(),- merchant_context.get_merchant_key_store(),- existing_pm,- pm_update,- merchant_context.get_merchant_account().storage_scheme,+ #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]+ #[instrument(skip_all)]+ async fn delete_payment_method(+ &self,+ pm_id: api::PaymentMethodId,+ ) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> {+ let db = self.state.store.as_ref();+ let key_manager_state = &(self.state.into());+ let key = db+ .find_payment_method(+ key_manager_state,+ self.merchant_context.get_merchant_key_store(),+ pm_id.payment_method_id.as_str(),+ self.merchant_context.get_merchant_account().storage_scheme,).await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(format!(- "Failed to update payment method for existing pm_id: {:?} in db",- pm_id- ))?;-- logger::debug!("Network token added to locker and payment method updated");- Ok(true)- }- Err(err) => {- logger::debug!("Network token added to locker failed {:?}", err);- Ok(false)- }- }-}--// need to discuss regarding the migration APIs for v2-#[cfg(all(- feature = "v2",- feature = "payment_methods_v2",- feature = "customer_v2"-))]-pub async fn skip_locker_call_and_migrate_payment_method(- _state: routes::SessionState,- _req: &api::PaymentMethodMigrate,- _merchant_id: id_type::MerchantId,- _merchant_context: &domain::MerchantContext,- _card: api_models::payment_methods::CardDetailFromLocker,-) -> errors::RouterResponse<api::PaymentMethodResponse> {- todo!()-}--pub fn get_card_bin_and_last4_digits_for_masked_card(- masked_card_number: &str,-) -> Result<(String, String), cards::CardNumberValidationErr> {- let last4_digits = masked_card_number- .chars()- .rev()- .take(4)- .collect::<String>()- .chars()- .rev()- .collect::<String>();-- let card_isin = masked_card_number.chars().take(6).collect::<String>();-- cards::validate::validate_card_number_chars(&card_isin)- .and_then(|_| cards::validate::validate_card_number_chars(&last4_digits))?;-- Ok((card_isin, last4_digits))-}--#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2")-))]-#[instrument(skip_all)]-pub async fn get_client_secret_or_add_payment_method(- state: &routes::SessionState,- req: api::PaymentMethodCreate,- merchant_context: &domain::MerchantContext,-) -> errors::RouterResponse<api::PaymentMethodResponse> {- let merchant_id = merchant_context.get_merchant_account().get_id();- let customer_id = req.customer_id.clone().get_required_value("customer_id")?;+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;- #[cfg(not(feature = "payouts"))]- let condition = req.card.is_some();- #[cfg(feature = "payouts")]- let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();- let key_manager_state = state.into();- let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req- .billing- .clone()- .async_map(|billing| {- create_encrypted_data(- &key_manager_state,- merchant_context.get_merchant_key_store(),- billing,+ let customer = db+ .find_customer_by_customer_id_merchant_id(+ key_manager_state,+ &key.customer_id,+ self.merchant_context.get_merchant_account().get_id(),+ self.merchant_context.get_merchant_key_store(),+ self.merchant_context.get_merchant_account().storage_scheme,)- })- .await- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt Payment method billing address")?;+ .await+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Customer not found for the payment method")?;++ if key.get_payment_method_type() == Some(enums::PaymentMethod::Card) {+ let response = self+ .delete_card_from_locker(+ &key.customer_id,+ &key.merchant_id,+ key.locker_id.as_ref().unwrap_or(&key.payment_method_id),+ )+ .await?;- let connector_mandate_details = req- .connector_mandate_details- .clone()- .map(serde_json::to_value)- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)?;+ if let Some(network_token_ref_id) = key.network_token_requestor_reference_id {+ let resp =+ network_tokenization::delete_network_token_from_locker_and_token_service(+ self.state,+ &key.customer_id,+ &key.merchant_id,+ key.payment_method_id.clone(),+ key.network_token_locker_id,+ network_token_ref_id,+ self.merchant_context,+ )+ .await?;- if condition {- Box::pin(add_payment_method(state, req, merchant_context)).await- } else {- let payment_method_id = generate_id(consts::ID_LENGTH, "pm");+ if resp.status == "Ok" {+ logger::info!("Token From locker deleted Successfully!");+ } else {+ logger::error!("Error: Deleting Token From Locker!\n{:#?}", resp);+ }+ }- let res = create_payment_method(- state,- &req,- &customer_id,- payment_method_id.as_str(),- None,- merchant_id,- None,- None,- None,- merchant_context.get_merchant_key_store(),- connector_mandate_details,- Some(enums::PaymentMethodStatus::AwaitingData),- None,- merchant_context.get_merchant_account().storage_scheme,- payment_method_billing_address,- None,- None,- None,- None,+ if response.status == "Ok" {+ logger::info!("Card From locker deleted Successfully!");+ } else {+ logger::error!("Error: Deleting Card From Locker!\n{:#?}", response);+ Err(errors::ApiErrorResponse::InternalServerError)?+ }+ }++ db.delete_payment_method_by_merchant_id_payment_method_id(+ &(self.state.into()),+ self.merchant_context.get_merchant_key_store(),+ self.merchant_context.get_merchant_account().get_id(),+ pm_id.payment_method_id.as_str(),)- .await?;+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;- if res.status == enums::PaymentMethodStatus::AwaitingData {- add_payment_method_status_update_task(- &*state.store,- &res,- enums::PaymentMethodStatus::AwaitingData,- enums::PaymentMethodStatus::Inactive,- merchant_id,+ if customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id) {+ let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {+ default_payment_method_id: Some(None),+ };+ db.update_customer_by_customer_id_merchant_id(+ key_manager_state,+ key.customer_id,+ key.merchant_id,+ customer,+ customer_update,+ self.merchant_context.get_merchant_key_store(),+ self.merchant_context.get_merchant_account().storage_scheme,).await.change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "Failed to add payment method status update task in process tracker",- )?;- }+ .attach_printable("Failed to update the default payment method id for the customer")?;+ };- Ok(services::api::ApplicationResponse::Json(- api::PaymentMethodResponse::foreign_from((None, res)),+ Ok(services::ApplicationResponse::Json(+ api::PaymentMethodDeleteResponse {+ payment_method_id: key.payment_method_id.clone(),+ deleted: true,+ },))}-}-#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2")-))]-#[instrument(skip_all)]-pub async fn get_client_secret_or_add_payment_method_for_migration(- state: &routes::SessionState,- req: api::PaymentMethodCreate,- merchant_context: &domain::MerchantContext,- migration_status: &mut migration::RecordMigrationStatusBuilder,-) -> errors::RouterResponse<api::PaymentMethodResponse> {- let merchant_id = merchant_context.get_merchant_account().get_id();- let customer_id = req.customer_id.clone().get_required_value("customer_id")?;+ #[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2")+ ))]+ #[instrument(skip_all)]+ async fn add_payment_method(+ &self,+ req: &api::PaymentMethodCreate,+ ) -> errors::RouterResponse<api::PaymentMethodResponse> {+ req.validate()?;+ let db = &*self.state.store;+ let merchant_id = self.merchant_context.get_merchant_account().get_id();+ let customer_id = req.customer_id.clone().get_required_value("customer_id")?;+ let payment_method = req.payment_method.get_required_value("payment_method")?;+ let key_manager_state = self.state.into();+ let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req+ .billing+ .clone()+ .async_map(|billing| {+ create_encrypted_data(+ &key_manager_state,+ self.merchant_context.get_merchant_key_store(),+ billing,+ )+ })+ .await+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt Payment method billing address")?;- #[cfg(not(feature = "payouts"))]- let condition = req.card.is_some();- #[cfg(feature = "payouts")]- let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();- let key_manager_state = state.into();+ let connector_mandate_details = req+ .connector_mandate_details+ .clone()+ .map(serde_json::to_value)+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)?;+ let response = match payment_method {+ #[cfg(feature = "payouts")]+ api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() {+ Some(bank) => self+ .add_bank_to_locker(+ req.clone(),+ self.merchant_context.get_merchant_key_store(),+ &bank,+ &customer_id,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Add PaymentMethod Failed"),+ _ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)),+ },+ api_enums::PaymentMethod::Card => match req.card.clone() {+ Some(card) => {+ let mut card_details = card;+ card_details = helpers::populate_bin_details_for_payment_method_create(+ card_details.clone(),+ db.get_payment_methods_store(),+ )+ .await;+ helpers::validate_card_expiry(+ &card_details.card_exp_month,+ &card_details.card_exp_year,+ )?;+ Box::pin(self.add_card_to_locker(+ req.clone(),+ &card_details,+ &customer_id,+ None,+ ))+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Add Card Failed")+ }+ _ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)),+ },+ _ => Ok(self.store_default_payment_method(req, &customer_id, merchant_id)),+ };- let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req- .billing- .clone()- .async_map(|billing| {- create_encrypted_data(- &key_manager_state,- merchant_context.get_merchant_key_store(),- billing,- )- })- .await- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt Payment method billing address")?;+ let (mut resp, duplication_check) = response?;- let connector_mandate_details = req- .connector_mandate_details- .clone()- .map(serde_json::to_value)- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)?;+ match duplication_check {+ Some(duplication_check) => match duplication_check {+ payment_methods::DataDuplicationCheck::Duplicated => {+ let existing_pm = self+ .get_or_insert_payment_method(+ req.clone(),+ &mut resp,+ &customer_id,+ self.merchant_context.get_merchant_key_store(),+ )+ .await?;- if condition {- Box::pin(save_migration_payment_method(- state,- req,- merchant_context,- migration_status,- ))- .await- } else {- let payment_method_id = generate_id(consts::ID_LENGTH, "pm");+ resp.client_secret = existing_pm.client_secret;+ }+ payment_methods::DataDuplicationCheck::MetaDataChanged => {+ if let Some(card) = req.card.clone() {+ let existing_pm = self+ .get_or_insert_payment_method(+ req.clone(),+ &mut resp,+ &customer_id,+ self.merchant_context.get_merchant_key_store(),+ )+ .await?;- let res = create_payment_method(- state,- &req,- &customer_id,- payment_method_id.as_str(),- None,- merchant_id,- None,- None,- None,- merchant_context.get_merchant_key_store(),- connector_mandate_details.clone(),- Some(enums::PaymentMethodStatus::AwaitingData),- None,- merchant_context.get_merchant_account().storage_scheme,- payment_method_billing_address,- None,- None,- None,- None,- )- .await?;- migration_status.connector_mandate_details_migrated(- connector_mandate_details- .clone()- .and_then(|val| (val != json!({})).then_some(true))- .or_else(|| {- req.connector_mandate_details- .clone()- .and_then(|val| (!val.0.is_empty()).then_some(false))- }),- );- //card is not migrated in this case- migration_status.card_migrated(false);-- if res.status == enums::PaymentMethodStatus::AwaitingData {- add_payment_method_status_update_task(- &*state.store,- &res,- enums::PaymentMethodStatus::AwaitingData,- enums::PaymentMethodStatus::Inactive,- merchant_id,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "Failed to add payment method status update task in process tracker",- )?;- }-- Ok(services::api::ApplicationResponse::Json(- api::PaymentMethodResponse::foreign_from((None, res)),- ))- }-}--#[instrument(skip_all)]-pub fn authenticate_pm_client_secret_and_check_expiry(- req_client_secret: &String,- payment_method: &domain::PaymentMethod,-) -> errors::CustomResult<bool, errors::ApiErrorResponse> {- let stored_client_secret = payment_method- .client_secret- .clone()- .get_required_value("client_secret")- .change_context(errors::ApiErrorResponse::MissingRequiredField {- field_name: "client_secret",- })- .attach_printable("client secret not found in db")?;-- if req_client_secret != &stored_client_secret {- Err((errors::ApiErrorResponse::ClientSecretInvalid).into())- } else {- let current_timestamp = common_utils::date_time::now();- let session_expiry = payment_method- .created_at- .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));-- let expired = current_timestamp > session_expiry;+ let client_secret = existing_pm.client_secret.clone();- Ok(expired)- }-}--#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2"),- not(feature = "customer_v2")-))]-#[instrument(skip_all)]-pub async fn add_payment_method_data(- state: routes::SessionState,- req: api::PaymentMethodCreate,- merchant_context: domain::MerchantContext,- pm_id: String,-) -> errors::RouterResponse<api::PaymentMethodResponse> {- let db = &*state.store;-- let pmd = req- .payment_method_data- .clone()- .get_required_value("payment_method_data")?;- req.payment_method.get_required_value("payment_method")?;- let client_secret = req- .client_secret- .clone()- .get_required_value("client_secret")?;- let payment_method = db- .find_payment_method(- &((&state).into()),- merchant_context.get_merchant_key_store(),- pm_id.as_str(),- merchant_context.get_merchant_account().storage_scheme,- )- .await- .change_context(errors::ApiErrorResponse::PaymentMethodNotFound)- .attach_printable("Unable to find payment method")?;-- if payment_method.status != enums::PaymentMethodStatus::AwaitingData {- return Err((errors::ApiErrorResponse::ClientSecretExpired).into());- }-- let customer_id = payment_method.customer_id.clone();-- let customer = db- .find_customer_by_customer_id_merchant_id(- &(&state).into(),- &customer_id,- merchant_context.get_merchant_account().get_id(),- merchant_context.get_merchant_key_store(),- merchant_context.get_merchant_account().storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;-- let client_secret_expired =- authenticate_pm_client_secret_and_check_expiry(&client_secret, &payment_method)?;-- if client_secret_expired {- return Err((errors::ApiErrorResponse::ClientSecretExpired).into());- };- let key_manager_state = (&state).into();- match pmd {- api_models::payment_methods::PaymentMethodCreateData::Card(card) => {- helpers::validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?;- let resp = Box::pin(add_card_to_locker(- &state,- req.clone(),- &card,- &customer_id,- &merchant_context,- None,- ))- .await- .change_context(errors::ApiErrorResponse::InternalServerError);-- match resp {- Ok((mut pm_resp, duplication_check)) => {- if duplication_check.is_some() {- let pm_update = storage::PaymentMethodUpdate::StatusUpdate {- status: Some(enums::PaymentMethodStatus::Inactive),- };-- db.update_payment_method(- &((&state).into()),- merchant_context.get_merchant_key_store(),- payment_method,- pm_update,- merchant_context.get_merchant_account().storage_scheme,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to add payment method in db")?;-- get_or_insert_payment_method(- &state,- req.clone(),- &mut pm_resp,- &merchant_context,+ self.delete_card_from_locker(&customer_id,- )- .await?;-- return Ok(services::ApplicationResponse::Json(pm_resp));- } else {- let locker_id = pm_resp.payment_method_id.clone();- pm_resp.payment_method_id.clone_from(&pm_id);- pm_resp.client_secret = Some(client_secret.clone());-- let card_isin = card.card_number.get_card_isin();-- let card_info = db- .get_card_info(card_isin.as_str())- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to get card info")?;-- let updated_card = CardDetailsPaymentMethod {- issuer_country: card_info- .as_ref()- .and_then(|ci| ci.card_issuing_country.clone()),- last4_digits: Some(card.card_number.get_last4()),- expiry_month: Some(card.card_exp_month),- expiry_year: Some(card.card_exp_year),- nick_name: card.nick_name,- card_holder_name: card.card_holder_name,- card_network: card_info.as_ref().and_then(|ci| ci.card_network.clone()),- card_isin: Some(card_isin),- card_issuer: card_info.as_ref().and_then(|ci| ci.card_issuer.clone()),- card_type: card_info.as_ref().and_then(|ci| ci.card_type.clone()),- saved_to_locker: true,- };- let pm_data_encrypted: Encryptable<Secret<serde_json::Value>> =- create_encrypted_data(- &key_manager_state,- merchant_context.get_merchant_key_store(),- PaymentMethodsData::Card(updated_card),- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt payment method data")?;-- let pm_update = storage::PaymentMethodUpdate::AdditionalDataUpdate {- payment_method_data: Some(pm_data_encrypted.into()),- status: Some(enums::PaymentMethodStatus::Active),- locker_id: Some(locker_id),- network_token_requestor_reference_id: None,- payment_method: req.payment_method,- payment_method_issuer: req.payment_method_issuer,- payment_method_type: req.payment_method_type,- network_token_locker_id: None,- network_token_payment_method_data: None,- };-- db.update_payment_method(- &((&state).into()),- merchant_context.get_merchant_key_store(),- payment_method,- pm_update,- merchant_context.get_merchant_account().storage_scheme,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to add payment method in db")?;-- if customer.default_payment_method_id.is_none() {- let _ = set_default_payment_method(- &state,- merchant_context.get_merchant_account().get_id(),- merchant_context.get_merchant_key_store().clone(),- &customer_id,- pm_id,- merchant_context.get_merchant_account().storage_scheme,- )- .await- .map_err(|error| {- logger::error!(- ?error,- "Failed to set the payment method as default"- )- });- }-- return Ok(services::ApplicationResponse::Json(pm_resp));- }- }- Err(e) => {- let pm_update = storage::PaymentMethodUpdate::StatusUpdate {- status: Some(enums::PaymentMethodStatus::Inactive),- };-- db.update_payment_method(- &((&state).into()),- merchant_context.get_merchant_key_store(),- payment_method,- pm_update,- merchant_context.get_merchant_account().storage_scheme,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to update payment method in db")?;-- return Err(e.attach_printable("Failed to add card to locker"));- }- }- }- }-}--#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2")-))]-#[instrument(skip_all)]-pub async fn add_payment_method(- state: &routes::SessionState,- req: api::PaymentMethodCreate,- merchant_context: &domain::MerchantContext,-) -> errors::RouterResponse<api::PaymentMethodResponse> {- req.validate()?;- let db = &*state.store;- let merchant_id = merchant_context.get_merchant_account().get_id();- let customer_id = req.customer_id.clone().get_required_value("customer_id")?;- let payment_method = req.payment_method.get_required_value("payment_method")?;- let key_manager_state = state.into();- let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req- .billing- .clone()- .async_map(|billing| {- create_encrypted_data(- &key_manager_state,- merchant_context.get_merchant_key_store(),- billing,- )- })- .await- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt Payment method billing address")?;-- let connector_mandate_details = req- .connector_mandate_details- .clone()- .map(serde_json::to_value)- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)?;-- let response = match payment_method {- #[cfg(feature = "payouts")]- api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() {- Some(bank) => {- add_bank_to_locker(state, req.clone(), merchant_context, &bank, &customer_id)- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Add PaymentMethod Failed")- }- _ => Ok(store_default_payment_method(- &req,- &customer_id,- merchant_id,- )),- },- api_enums::PaymentMethod::Card => match req.card.clone() {- Some(card) => {- let mut card_details = card;- card_details = helpers::populate_bin_details_for_payment_method_create(- card_details.clone(),- db,- )- .await;- helpers::validate_card_expiry(- &card_details.card_exp_month,- &card_details.card_exp_year,- )?;- Box::pin(add_card_to_locker(- state,- req.clone(),- &card_details,- &customer_id,- merchant_context,- None,- ))- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Add Card Failed")- }- _ => Ok(store_default_payment_method(- &req,- &customer_id,- merchant_id,- )),- },- _ => Ok(store_default_payment_method(- &req,- &customer_id,- merchant_id,- )),- };-- let (mut resp, duplication_check) = response?;-- match duplication_check {- Some(duplication_check) => match duplication_check {- payment_methods::DataDuplicationCheck::Duplicated => {- let existing_pm = get_or_insert_payment_method(- state,- req.clone(),- &mut resp,- merchant_context,- &customer_id,- )- .await?;-- resp.client_secret = existing_pm.client_secret;- }- payment_methods::DataDuplicationCheck::MetaDataChanged => {- if let Some(card) = req.card.clone() {- let existing_pm = get_or_insert_payment_method(- state,- req.clone(),- &mut resp,- merchant_context,- &customer_id,- )- .await?;-- let client_secret = existing_pm.client_secret.clone();-- delete_card_from_locker(- state,- &customer_id,- merchant_id,- existing_pm- .locker_id- .as_ref()- .unwrap_or(&existing_pm.payment_method_id),- )- .await?;-- let add_card_resp = add_card_hs(- state,- req.clone(),- &card,- &customer_id,- merchant_context,- api::enums::LockerChoice::HyperswitchCardVault,- Some(- existing_pm- .locker_id- .as_ref()- .unwrap_or(&existing_pm.payment_method_id),- ),- )- .await;-- if let Err(err) = add_card_resp {- logger::error!(vault_err=?err);- db.delete_payment_method_by_merchant_id_payment_method_id(- &(state.into()),- merchant_context.get_merchant_key_store(),merchant_id,- &resp.payment_method_id,+ existing_pm+ .locker_id+ .as_ref()+ .unwrap_or(&existing_pm.payment_method_id),)- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;+ .await?;- Err(report!(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed while updating card metadata changes"))?- };+ let add_card_resp = self+ .add_card_hs(+ req.clone(),+ &card,+ &customer_id,+ api::enums::LockerChoice::HyperswitchCardVault,+ Some(+ existing_pm+ .locker_id+ .as_ref()+ .unwrap_or(&existing_pm.payment_method_id),+ ),+ )+ .await;++ if let Err(err) = add_card_resp {+ logger::error!(vault_err=?err);+ db.delete_payment_method_by_merchant_id_payment_method_id(+ &(self.state.into()),+ self.merchant_context.get_merchant_key_store(),+ merchant_id,+ &resp.payment_method_id,+ )+ .await+ .to_not_found_response(+ errors::ApiErrorResponse::PaymentMethodNotFound,+ )?;- let existing_pm_data =- get_card_details_without_locker_fallback(&existing_pm, state).await?;-- let updated_card = Some(api::CardDetailFromLocker {- scheme: existing_pm.scheme.clone(),- last4_digits: Some(card.card_number.get_last4()),- issuer_country: card- .card_issuing_country- .or(existing_pm_data.issuer_country),- card_isin: Some(card.card_number.get_card_isin()),- card_number: Some(card.card_number),- expiry_month: Some(card.card_exp_month),- expiry_year: Some(card.card_exp_year),- card_token: None,- card_fingerprint: None,- card_holder_name: card- .card_holder_name- .or(existing_pm_data.card_holder_name),- nick_name: card.nick_name.or(existing_pm_data.nick_name),- card_network: card.card_network.or(existing_pm_data.card_network),- card_issuer: card.card_issuer.or(existing_pm_data.card_issuer),- card_type: card.card_type.or(existing_pm_data.card_type),- saved_to_locker: true,- });+ Err(report!(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed while updating card metadata changes"))?+ };- let updated_pmd = updated_card.as_ref().map(|card| {- PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))- });- let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> =- updated_pmd- .async_map(|updated_pmd| {- create_encrypted_data(- &key_manager_state,- merchant_context.get_merchant_key_store(),- updated_pmd,- )- })- .await- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt payment method data")?;+ let existing_pm_data = self+ .get_card_details_without_locker_fallback(&existing_pm)+ .await?;- let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {- payment_method_data: pm_data_encrypted.map(Into::into),- };+ let updated_card = Some(api::CardDetailFromLocker {+ scheme: existing_pm.scheme.clone(),+ last4_digits: Some(card.card_number.get_last4()),+ issuer_country: card+ .card_issuing_country+ .or(existing_pm_data.issuer_country),+ card_isin: Some(card.card_number.get_card_isin()),+ card_number: Some(card.card_number),+ expiry_month: Some(card.card_exp_month),+ expiry_year: Some(card.card_exp_year),+ card_token: None,+ card_fingerprint: None,+ card_holder_name: card+ .card_holder_name+ .or(existing_pm_data.card_holder_name),+ nick_name: card.nick_name.or(existing_pm_data.nick_name),+ card_network: card.card_network.or(existing_pm_data.card_network),+ card_issuer: card.card_issuer.or(existing_pm_data.card_issuer),+ card_type: card.card_type.or(existing_pm_data.card_type),+ saved_to_locker: true,+ });- db.update_payment_method(- &(state.into()),- merchant_context.get_merchant_key_store(),- existing_pm,- pm_update,- merchant_context.get_merchant_account().storage_scheme,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to add payment method in db")?;+ let updated_pmd = updated_card.as_ref().map(|card| {+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))+ });+ let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> =+ updated_pmd+ .async_map(|updated_pmd| {+ create_encrypted_data(+ &key_manager_state,+ self.merchant_context.get_merchant_key_store(),+ updated_pmd,+ )+ })+ .await+ .transpose()+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt payment method data")?;++ let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {+ payment_method_data: pm_data_encrypted.map(Into::into),+ };++ db.update_payment_method(+ &(self.state.into()),+ self.merchant_context.get_merchant_key_store(),+ existing_pm,+ pm_update,+ self.merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to add payment method in db")?;- resp.client_secret = client_secret;+ resp.client_secret = client_secret;+ }}- }- },- None => {- let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());+ },+ None => {+ let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());- let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card)- || resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer)- {- Some(resp.payment_method_id)- } else {- None- };- resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");- let pm = insert_payment_method(- state,- &resp,- &req,- merchant_context.get_merchant_key_store(),- merchant_id,- &customer_id,- pm_metadata.cloned(),- None,- locker_id,- connector_mandate_details,- req.network_transaction_id.clone(),- merchant_context.get_merchant_account().storage_scheme,- payment_method_billing_address,- None,- None,- None,- )- .await?;+ let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card)+ || resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer)+ {+ Some(resp.payment_method_id)+ } else {+ None+ };+ resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");+ let pm = self+ .insert_payment_method(+ &resp,+ req,+ self.merchant_context.get_merchant_key_store(),+ merchant_id,+ &customer_id,+ pm_metadata.cloned(),+ None,+ locker_id,+ connector_mandate_details,+ req.network_transaction_id.clone(),+ payment_method_billing_address,+ None,+ None,+ None,+ )+ .await?;- resp.client_secret = pm.client_secret;+ resp.client_secret = pm.client_secret;+ }}- }- Ok(services::ApplicationResponse::Json(resp))+ Ok(services::ApplicationResponse::Json(resp))+ }}#[cfg(all(@@ -1725,17 +1356,21 @@ pub async fn add_payment_method(not(feature = "payment_methods_v2")))]#[instrument(skip_all)]-pub async fn save_migration_payment_method(+pub async fn get_client_secret_or_add_payment_method(state: &routes::SessionState,req: api::PaymentMethodCreate,merchant_context: &domain::MerchantContext,- migration_status: &mut migration::RecordMigrationStatusBuilder,) -> errors::RouterResponse<api::PaymentMethodResponse> {- req.validate()?;- let db = &*state.store;let merchant_id = merchant_context.get_merchant_account().get_id();let customer_id = req.customer_id.clone().get_required_value("customer_id")?;- let payment_method = req.payment_method.get_required_value("payment_method")?;+ let cards = PmCards {+ state,+ merchant_context,+ };+ #[cfg(not(feature = "payouts"))]+ let condition = req.card.is_some();+ #[cfg(feature = "payouts")]+ let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();let key_manager_state = state.into();let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req.billing@@ -1759,326 +1394,279 @@ pub async fn save_migration_payment_method(.transpose().change_context(errors::ApiErrorResponse::InternalServerError)?;- let network_transaction_id = req.network_transaction_id.clone();+ if condition {+ Box::pin(cards.add_payment_method(&req)).await+ } else {+ let payment_method_id = generate_id(consts::ID_LENGTH, "pm");- let response = match payment_method {- #[cfg(feature = "payouts")]- api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() {- Some(bank) => {- add_bank_to_locker(state, req.clone(), merchant_context, &bank, &customer_id)- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Add PaymentMethod Failed")- }- _ => Ok(store_default_payment_method(+ let res = cards+ .create_payment_method(&req,&customer_id,+ payment_method_id.as_str(),+ None,merchant_id,- )),- },- api_enums::PaymentMethod::Card => match req.card.clone() {- Some(card) => {- let mut card_details = card;- card_details = helpers::populate_bin_details_for_payment_method_create(- card_details.clone(),- db,- )- .await;- migration::validate_card_expiry(- &card_details.card_exp_month,- &card_details.card_exp_year,- )?;- Box::pin(add_card_to_locker(- state,- req.clone(),- &card_details,- &customer_id,- merchant_context,- None,- ))- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Add Card Failed")- }- _ => Ok(store_default_payment_method(- &req,- &customer_id,+ None,+ None,+ None,+ connector_mandate_details,+ Some(enums::PaymentMethodStatus::AwaitingData),+ None,+ payment_method_billing_address,+ None,+ None,+ None,+ None,+ )+ .await?;++ if res.status == enums::PaymentMethodStatus::AwaitingData {+ add_payment_method_status_update_task(+ &*state.store,+ &res,+ enums::PaymentMethodStatus::AwaitingData,+ enums::PaymentMethodStatus::Inactive,merchant_id,- )),- },- _ => Ok(store_default_payment_method(- &req,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to add payment method status update task in process tracker",+ )?;+ }++ Ok(services::api::ApplicationResponse::Json(+ api::PaymentMethodResponse::foreign_from((None, res)),+ ))+ }+}++#[instrument(skip_all)]+pub fn authenticate_pm_client_secret_and_check_expiry(+ req_client_secret: &String,+ payment_method: &domain::PaymentMethod,+) -> errors::CustomResult<bool, errors::ApiErrorResponse> {+ let stored_client_secret = payment_method+ .client_secret+ .clone()+ .get_required_value("client_secret")+ .change_context(errors::ApiErrorResponse::MissingRequiredField {+ field_name: "client_secret",+ })+ .attach_printable("client secret not found in db")?;++ if req_client_secret != &stored_client_secret {+ Err((errors::ApiErrorResponse::ClientSecretInvalid).into())+ } else {+ let current_timestamp = common_utils::date_time::now();+ let session_expiry = payment_method+ .created_at+ .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));++ let expired = current_timestamp > session_expiry;++ Ok(expired)+ }+}++#[cfg(all(+ any(feature = "v1", feature = "v2"),+ not(feature = "payment_methods_v2"),+ not(feature = "customer_v2")+))]+#[instrument(skip_all)]+pub async fn add_payment_method_data(+ state: routes::SessionState,+ req: api::PaymentMethodCreate,+ merchant_context: domain::MerchantContext,+ pm_id: String,+) -> errors::RouterResponse<api::PaymentMethodResponse> {+ let db = &*state.store;+ let cards = PmCards {+ state: &state,+ merchant_context: &merchant_context,+ };++ let pmd = req+ .payment_method_data+ .clone()+ .get_required_value("payment_method_data")?;+ req.payment_method.get_required_value("payment_method")?;+ let client_secret = req+ .client_secret+ .clone()+ .get_required_value("client_secret")?;+ let payment_method = db+ .find_payment_method(+ &((&state).into()),+ merchant_context.get_merchant_key_store(),+ pm_id.as_str(),+ merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::PaymentMethodNotFound)+ .attach_printable("Unable to find payment method")?;++ if payment_method.status != enums::PaymentMethodStatus::AwaitingData {+ return Err((errors::ApiErrorResponse::ClientSecretExpired).into());+ }++ let customer_id = payment_method.customer_id.clone();++ let customer = db+ .find_customer_by_customer_id_merchant_id(+ &(&state).into(),&customer_id,- merchant_id,- )),+ merchant_context.get_merchant_account().get_id(),+ merchant_context.get_merchant_key_store(),+ merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;++ let client_secret_expired =+ authenticate_pm_client_secret_and_check_expiry(&client_secret, &payment_method)?;++ if client_secret_expired {+ return Err((errors::ApiErrorResponse::ClientSecretExpired).into());};+ let key_manager_state = (&state).into();+ match pmd {+ api_models::payment_methods::PaymentMethodCreateData::Card(card) => {+ helpers::validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?;+ let resp = Box::pin(cards.add_card_to_locker(req.clone(), &card, &customer_id, None))+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError);- let (mut resp, duplication_check) = response?;+ match resp {+ Ok((mut pm_resp, duplication_check)) => {+ if duplication_check.is_some() {+ let pm_update = storage::PaymentMethodUpdate::StatusUpdate {+ status: Some(enums::PaymentMethodStatus::Inactive),+ };- migration_status.card_migrated(true);- match duplication_check {- Some(duplication_check) => match duplication_check {- payment_methods::DataDuplicationCheck::Duplicated => {- let existing_pm = get_or_insert_payment_method(- state,- req.clone(),- &mut resp,- merchant_context,- &customer_id,- )- .await?;+ db.update_payment_method(+ &((&state).into()),+ merchant_context.get_merchant_key_store(),+ payment_method,+ pm_update,+ merchant_context.get_merchant_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to add payment method in db")?;++ cards+ .get_or_insert_payment_method(+ req.clone(),+ &mut pm_resp,+ &customer_id,+ merchant_context.get_merchant_key_store(),+ )+ .await?;- resp.client_secret = existing_pm.client_secret;- }- payment_methods::DataDuplicationCheck::MetaDataChanged => {- if let Some(card) = req.card.clone() {- let existing_pm = get_or_insert_payment_method(- state,- req.clone(),- &mut resp,- merchant_context,- &customer_id,- )- .await?;+ return Ok(services::ApplicationResponse::Json(pm_resp));+ } else {+ let locker_id = pm_resp.payment_method_id.clone();+ pm_resp.payment_method_id.clone_from(&pm_id);+ pm_resp.client_secret = Some(client_secret.clone());- let client_secret = existing_pm.client_secret.clone();+ let card_isin = card.card_number.get_card_isin();- delete_card_from_locker(- state,- &customer_id,- merchant_id,- existing_pm- .locker_id- .as_ref()- .unwrap_or(&existing_pm.payment_method_id),- )- .await?;+ let card_info = db+ .get_card_info(card_isin.as_str())+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to get card info")?;- let add_card_resp = add_card_hs(- state,- req.clone(),- &card,- &customer_id,- merchant_context,- api::enums::LockerChoice::HyperswitchCardVault,- Some(- existing_pm- .locker_id+ let updated_card = CardDetailsPaymentMethod {+ issuer_country: card_info.as_ref()- .unwrap_or(&existing_pm.payment_method_id),- ),- )- .await;+ .and_then(|ci| ci.card_issuing_country.clone()),+ last4_digits: Some(card.card_number.get_last4()),+ expiry_month: Some(card.card_exp_month),+ expiry_year: Some(card.card_exp_year),+ nick_name: card.nick_name,+ card_holder_name: card.card_holder_name,+ card_network: card_info.as_ref().and_then(|ci| ci.card_network.clone()),+ card_isin: Some(card_isin),+ card_issuer: card_info.as_ref().and_then(|ci| ci.card_issuer.clone()),+ card_type: card_info.as_ref().and_then(|ci| ci.card_type.clone()),+ saved_to_locker: true,+ };+ let pm_data_encrypted: Encryptable<Secret<serde_json::Value>> =+ create_encrypted_data(+ &key_manager_state,+ merchant_context.get_merchant_key_store(),+ PaymentMethodsData::Card(updated_card),+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to encrypt payment method data")?;++ let pm_update = storage::PaymentMethodUpdate::AdditionalDataUpdate {+ payment_method_data: Some(pm_data_encrypted.into()),+ status: Some(enums::PaymentMethodStatus::Active),+ locker_id: Some(locker_id),+ network_token_requestor_reference_id: None,+ payment_method: req.payment_method,+ payment_method_issuer: req.payment_method_issuer,+ payment_method_type: req.payment_method_type,+ network_token_locker_id: None,+ network_token_payment_method_data: None,+ };- if let Err(err) = add_card_resp {- logger::error!(vault_err=?err);- db.delete_payment_method_by_merchant_id_payment_method_id(- &(state.into()),+ db.update_payment_method(+ &((&state).into()),merchant_context.get_merchant_key_store(),- merchant_id,- &resp.payment_method_id,+ payment_method,+ pm_update,+ merchant_context.get_merchant_account().storage_scheme,).await- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;-- Err(report!(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed while updating card metadata changes"))?- };-- let existing_pm_data =- get_card_details_without_locker_fallback(&existing_pm, state).await?;-- let updated_card = Some(api::CardDetailFromLocker {- scheme: existing_pm.scheme.clone(),- last4_digits: Some(card.card_number.get_last4()),- issuer_country: card- .card_issuing_country- .or(existing_pm_data.issuer_country),- card_isin: Some(card.card_number.get_card_isin()),- card_number: Some(card.card_number),- expiry_month: Some(card.card_exp_month),- expiry_year: Some(card.card_exp_year),- card_token: None,- card_fingerprint: None,- card_holder_name: card- .card_holder_name- .or(existing_pm_data.card_holder_name),- nick_name: card.nick_name.or(existing_pm_data.nick_name),- card_network: card.card_network.or(existing_pm_data.card_network),- card_issuer: card.card_issuer.or(existing_pm_data.card_issuer),- card_type: card.card_type.or(existing_pm_data.card_type),- saved_to_locker: true,- });+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to add payment method in db")?;- let updated_pmd = updated_card.as_ref().map(|card| {- PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))- });- let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> =- updated_pmd- .async_map(|updated_pmd| {- create_encrypted_data(- &key_manager_state,- merchant_context.get_merchant_key_store(),- updated_pmd,+ if customer.default_payment_method_id.is_none() {+ let _ = cards+ .set_default_payment_method(+ merchant_context.get_merchant_account().get_id(),+ &customer_id,+ pm_id,)- })- .await- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt payment method data")?;+ .await+ .map_err(|error| {+ logger::error!(+ ?error,+ "Failed to set the payment method as default"+ )+ });+ }- let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {- payment_method_data: pm_data_encrypted.map(Into::into),+ return Ok(services::ApplicationResponse::Json(pm_resp));+ }+ }+ Err(e) => {+ let pm_update = storage::PaymentMethodUpdate::StatusUpdate {+ status: Some(enums::PaymentMethodStatus::Inactive),};db.update_payment_method(- &(state.into()),+ &((&state).into()),merchant_context.get_merchant_key_store(),- existing_pm,+ payment_method,pm_update,merchant_context.get_merchant_account().storage_scheme,).await.change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to add payment method in db")?;+ .attach_printable("Failed to update payment method in db")?;- resp.client_secret = client_secret;+ return Err(e.attach_printable("Failed to add card to locker"));}}- },- None => {- let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());-- let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card)- || resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer)- {- Some(resp.payment_method_id)- } else {- None- };- resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");- let pm = insert_payment_method(- state,- &resp,- &req,- merchant_context.get_merchant_key_store(),- merchant_id,- &customer_id,- pm_metadata.cloned(),- None,- locker_id,- connector_mandate_details.clone(),- network_transaction_id.clone(),- merchant_context.get_merchant_account().storage_scheme,- payment_method_billing_address,- None,- None,- None,- )- .await?;-- resp.client_secret = pm.client_secret;}}-- migration_status.card_migrated(true);- migration_status.network_transaction_id_migrated(- network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)),- );-- migration_status.connector_mandate_details_migrated(- connector_mandate_details- .and_then(|val| if val == json!({}) { None } else { Some(true) })- .or_else(|| {- req.connector_mandate_details- .and_then(|val| (!val.0.is_empty()).then_some(false))- }),- );-- Ok(services::ApplicationResponse::Json(resp))-}--#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2")-))]-#[allow(clippy::too_many_arguments)]-pub async fn insert_payment_method(- state: &routes::SessionState,- resp: &api::PaymentMethodResponse,- req: &api::PaymentMethodCreate,- key_store: &domain::MerchantKeyStore,- merchant_id: &id_type::MerchantId,- customer_id: &id_type::CustomerId,- pm_metadata: Option<serde_json::Value>,- customer_acceptance: Option<serde_json::Value>,- locker_id: Option<String>,- connector_mandate_details: Option<serde_json::Value>,- network_transaction_id: Option<String>,- storage_scheme: MerchantStorageScheme,- payment_method_billing_address: crypto::OptionalEncryptableValue,- network_token_requestor_reference_id: Option<String>,- network_token_locker_id: Option<String>,- network_token_payment_method_data: crypto::OptionalEncryptableValue,-) -> errors::RouterResult<domain::PaymentMethod> {- let pm_card_details = resp- .card- .clone()- .map(|card| PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone())));- let key_manager_state = state.into();- let pm_data_encrypted: crypto::OptionalEncryptableValue = pm_card_details- .clone()- .async_map(|pm_card| create_encrypted_data(&key_manager_state, key_store, pm_card))- .await- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Unable to encrypt payment method data")?;-- create_payment_method(- state,- req,- customer_id,- &resp.payment_method_id,- locker_id,- merchant_id,- pm_metadata,- customer_acceptance,- pm_data_encrypted,- key_store,- connector_mandate_details,- None,- network_transaction_id,- storage_scheme,- payment_method_billing_address,- resp.card.clone().and_then(|card| {- card.card_network- .map(|card_network| card_network.to_string())- }),- network_token_requestor_reference_id,- network_token_locker_id,- network_token_payment_method_data,- )- .await-}--#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]-#[allow(clippy::too_many_arguments)]-pub async fn insert_payment_method(- state: &routes::SessionState,- resp: &api::PaymentMethodResponse,- req: &api::PaymentMethodCreate,- key_store: &domain::MerchantKeyStore,- merchant_id: &id_type::MerchantId,- customer_id: &id_type::CustomerId,- pm_metadata: Option<serde_json::Value>,- customer_acceptance: Option<serde_json::Value>,- locker_id: Option<String>,- connector_mandate_details: Option<serde_json::Value>,- network_transaction_id: Option<String>,- storage_scheme: MerchantStorageScheme,- payment_method_billing_address: Option<Encryption>,-) -> errors::RouterResult<domain::PaymentMethod> {- todo!()}#[cfg(all(@@ -2201,23 +1789,24 @@ pub async fn update_customer_payment_method(network_transaction_id: None,};new_pm.validate()?;-+ let cards = PmCards {+ state: &state,+ merchant_context: &merchant_context,+ };// Delete old payment method from locker- delete_card_from_locker(- &state,- &pm.customer_id,- &pm.merchant_id,- pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),- )- .await?;+ cards+ .delete_card_from_locker(+ &pm.customer_id,+ &pm.merchant_id,+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),+ )+ .await?;// Add the updated payment method data to locker- let (mut add_card_resp, _) = Box::pin(add_card_to_locker(- &state,+ let (mut add_card_resp, _) = Box::pin(cards.add_card_to_locker(new_pm.clone(),&updated_card_details,&pm.customer_id,- &merchant_context,Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),)).await@@ -2339,170 +1928,42 @@ pub fn validate_payment_method_update(|| card_updation_obj.card_exp_year.map(|exp_year| exp_year.expose())- .is_some_and(|new_exp_year| {- existing_card_data- .expiry_year- .map(|exp_year| exp_year.expose())- != Some(new_exp_year)- })- || card_updation_obj- .card_holder_name- .map(|name| name.expose())- .is_some_and(|new_card_holder_name| {- existing_card_data- .card_holder_name- .map(|name| name.expose())- != Some(new_card_holder_name)- })- || card_updation_obj- .nick_name- .map(|nick_name| nick_name.expose())- .is_some_and(|new_nick_name| {- existing_card_data- .nick_name- .map(|nick_name| nick_name.expose())- != Some(new_nick_name)- })-}--#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]-pub fn validate_payment_method_update(- _card_updation_obj: CardDetailUpdate,- _existing_card_data: api::CardDetailFromLocker,-) -> bool {- todo!()-}--// Wrapper function to switch lockers--#[cfg(feature = "payouts")]-pub async fn add_bank_to_locker(- state: &routes::SessionState,- req: api::PaymentMethodCreate,- merchant_context: &domain::MerchantContext,- bank: &api::BankPayout,- customer_id: &id_type::CustomerId,-) -> errors::CustomResult<- (- api::PaymentMethodResponse,- Option<payment_methods::DataDuplicationCheck>,- ),- errors::VaultError,-> {- let key = merchant_context- .get_merchant_key_store()- .key- .get_inner()- .peek();- let payout_method_data = api::PayoutMethodData::Bank(bank.clone());- let key_manager_state: KeyManagerState = state.into();- let enc_data = async {- serde_json::to_value(payout_method_data.to_owned())- .map_err(|err| {- logger::error!("Error while encoding payout method data: {err:?}");- errors::VaultError::SavePaymentMethodFailed- })- .change_context(errors::VaultError::SavePaymentMethodFailed)- .attach_printable("Unable to encode payout method data")- .ok()- .map(|v| {- let secret: Secret<String> = Secret::new(v.to_string());- secret- })- .async_lift(|inner| async {- domain::types::crypto_operation(- &key_manager_state,- type_name!(payment_method::PaymentMethod),- domain::types::CryptoOperation::EncryptOptional(inner),- Identifier::Merchant(- merchant_context- .get_merchant_key_store()- .merchant_id- .clone(),- ),- key,- )- .await- .and_then(|val| val.try_into_optionaloperation())- })- .await- }- .await- .change_context(errors::VaultError::SavePaymentMethodFailed)- .attach_printable("Failed to encrypt payout method data")?- .map(Encryption::from)- .map(|e| e.into_inner())- .map_or(Err(errors::VaultError::SavePaymentMethodFailed), |e| {- Ok(hex::encode(e.peek()))- })?;-- let payload =- payment_methods::StoreLockerReq::LockerGeneric(payment_methods::StoreGenericReq {- merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),- merchant_customer_id: customer_id.to_owned(),- enc_data,- ttl: state.conf.locker.ttl_for_storage_in_secs,- });- let store_resp = add_card_to_hs_locker(- state,- &payload,- customer_id,- api_enums::LockerChoice::HyperswitchCardVault,- )- .await?;- let payment_method_resp = payment_methods::mk_add_bank_response_hs(- bank.clone(),- store_resp.card_reference,- req,- merchant_context.get_merchant_account().get_id(),- );- Ok((payment_method_resp, store_resp.duplication_check))-}--/// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method-pub async fn add_card_to_locker(- state: &routes::SessionState,- req: api::PaymentMethodCreate,- card: &api::CardDetail,- customer_id: &id_type::CustomerId,- merchant_context: &domain::MerchantContext,- card_reference: Option<&str>,-) -> errors::CustomResult<- (- api::PaymentMethodResponse,- Option<payment_methods::DataDuplicationCheck>,- ),- errors::VaultError,-> {- metrics::STORED_TO_LOCKER.add(1, &[]);- let add_card_to_hs_resp = Box::pin(common_utils::metrics::utils::record_operation_time(- async {- add_card_hs(- state,- req.clone(),- card,- customer_id,- merchant_context,- api_enums::LockerChoice::HyperswitchCardVault,- card_reference,- )- .await- .inspect_err(|_| {- metrics::CARD_LOCKER_FAILURES.add(- 1,- router_env::metric_attributes!(("locker", "rust"), ("operation", "add")),- );+ .is_some_and(|new_exp_year| {+ existing_card_data+ .expiry_year+ .map(|exp_year| exp_year.expose())+ != Some(new_exp_year)})- },- &metrics::CARD_ADD_TIME,- router_env::metric_attributes!(("locker", "rust")),- ))- .await?;+ || card_updation_obj+ .card_holder_name+ .map(|name| name.expose())+ .is_some_and(|new_card_holder_name| {+ existing_card_data+ .card_holder_name+ .map(|name| name.expose())+ != Some(new_card_holder_name)+ })+ || card_updation_obj+ .nick_name+ .map(|nick_name| nick_name.expose())+ .is_some_and(|new_nick_name| {+ existing_card_data+ .nick_name+ .map(|nick_name| nick_name.expose())+ != Some(new_nick_name)+ })+}- logger::debug!("card added to hyperswitch-card-vault");- Ok(add_card_to_hs_resp)+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]+pub fn validate_payment_method_update(+ _card_updation_obj: CardDetailUpdate,+ _existing_card_data: api::CardDetailFromLocker,+) -> bool {+ todo!()}+// Wrapper function to switch lockers+pub async fn get_card_from_locker(state: &routes::SessionState,customer_id: &id_type::CustomerId,@@ -2539,33 +2000,6 @@ pub async fn get_card_from_locker(Ok(get_card_from_rs_locker_resp)}-pub async fn delete_card_from_locker(- state: &routes::SessionState,- customer_id: &id_type::CustomerId,- merchant_id: &id_type::MerchantId,- card_reference: &str,-) -> errors::RouterResult<payment_methods::DeleteCardResp> {- metrics::DELETE_FROM_LOCKER.add(1, &[]);-- common_utils::metrics::utils::record_operation_time(- async move {- delete_card_from_hs_locker(state, customer_id, merchant_id, card_reference)- .await- .inspect_err(|_| {- metrics::CARD_LOCKER_FAILURES.add(- 1,- router_env::metric_attributes!(("locker", "rust"), ("operation", "delete")),- );- })- },- &metrics::CARD_DELETE_TIME,- &[],- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed while deleting card from locker")-}-#[cfg(all(feature = "v2", feature = "customer_v2"))]pub async fn delete_card_by_locker_id(state: &routes::SessionState,@@ -2575,50 +2009,6 @@ pub async fn delete_card_by_locker_id(todo!()}-#[instrument(skip_all)]-pub async fn add_card_hs(- state: &routes::SessionState,- req: api::PaymentMethodCreate,- card: &api::CardDetail,- customer_id: &id_type::CustomerId,- merchant_context: &domain::MerchantContext,- locker_choice: api_enums::LockerChoice,- card_reference: Option<&str>,-) -> errors::CustomResult<- (- api::PaymentMethodResponse,- Option<payment_methods::DataDuplicationCheck>,- ),- errors::VaultError,-> {- let payload = payment_methods::StoreLockerReq::LockerCard(payment_methods::StoreCardReq {- merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),- merchant_customer_id: customer_id.to_owned(),- requestor_card_reference: card_reference.map(str::to_string),- card: Card {- card_number: card.card_number.to_owned(),- name_on_card: card.card_holder_name.to_owned(),- card_exp_month: card.card_exp_month.to_owned(),- card_exp_year: card.card_exp_year.to_owned(),- card_brand: card.card_network.as_ref().map(ToString::to_string),- card_isin: None,- nick_name: card.nick_name.as_ref().map(Secret::peek).cloned(),- },- ttl: state.conf.locker.ttl_for_storage_in_secs,- });-- let store_card_payload =- add_card_to_hs_locker(state, &payload, customer_id, locker_choice).await?;-- let payment_method_resp = payment_methods::mk_add_card_response_hs(- card.clone(),- store_card_payload.card_reference,- req,- merchant_context.get_merchant_account().get_id(),- );- Ok((payment_method_resp, store_card_payload.duplication_check))-}-#[instrument(skip_all)]pub async fn decode_and_decrypt_locker_data(state: &routes::SessionState,@@ -4905,6 +4295,7 @@ pub async fn list_customer_payment_method(&pm,Some(parent_payment_method_token.clone()),true,+ &merchant_context,).await?;@@ -5061,10 +4452,15 @@ pub async fn get_pm_list_context(#[cfg(feature = "payouts")] parent_payment_method_token: Option<String>,#[cfg(not(feature = "payouts"))] _parent_payment_method_token: Option<String>,is_payment_associated: bool,+ merchant_context: &domain::MerchantContext,) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> {+ let cards = PmCards {+ state,+ merchant_context,+ };let payment_method_retrieval_context = match payment_method {enums::PaymentMethod::Card => {- let card_details = get_card_details_with_locker_fallback(pm, state).await?;+ let card_details = cards.get_card_details_with_locker_fallback(pm).await?;card_details.as_ref().map(|card| PaymentMethodListContext {card_details: Some(card.clone()),@@ -5290,64 +4686,6 @@ where.attach_printable("unable to parse generic data value")}-#[cfg(all(- any(feature = "v2", feature = "v1"),- not(feature = "payment_methods_v2")-))]-pub async fn get_card_details_with_locker_fallback(- pm: &domain::PaymentMethod,- state: &routes::SessionState,-) -> errors::RouterResult<Option<api::CardDetailFromLocker>> {- let card_decrypted = pm- .payment_method_data- .clone()- .map(|x| x.into_inner().expose())- .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())- .and_then(|pmd| match pmd {- PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),- _ => None,- });-- Ok(if let Some(mut crd) = card_decrypted {- crd.scheme.clone_from(&pm.scheme);- Some(crd)- } else {- logger::debug!(- "Getting card details from locker as it is not found in payment methods table"- );- Some(get_card_details_from_locker(state, pm).await?)- })-}--#[cfg(all(- any(feature = "v2", feature = "v1"),- not(feature = "payment_methods_v2")-))]-pub async fn get_card_details_without_locker_fallback(- pm: &domain::PaymentMethod,- state: &routes::SessionState,-) -> errors::RouterResult<api::CardDetailFromLocker> {- let card_decrypted = pm- .payment_method_data- .clone()- .map(|x| x.into_inner().expose())- .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())- .and_then(|pmd| match pmd {- PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),- _ => None,- });-- Ok(if let Some(mut crd) = card_decrypted {- crd.scheme.clone_from(&pm.scheme);- crd- } else {- logger::debug!(- "Getting card details from locker as it is not found in payment methods table"- );- get_card_details_from_locker(state, pm).await?- })-}-#[cfg(all(any(feature = "v2", feature = "v1"),not(feature = "payment_methods_v2")@@ -5494,92 +4832,6 @@ pub async fn get_bank_account_connector_details(}}-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]-pub async fn set_default_payment_method(- state: &routes::SessionState,- merchant_id: &id_type::MerchantId,- key_store: domain::MerchantKeyStore,- customer_id: &id_type::CustomerId,- payment_method_id: String,- storage_scheme: MerchantStorageScheme,-) -> errors::RouterResponse<api_models::payment_methods::CustomerDefaultPaymentMethodResponse> {- let db = &*state.store;- let key_manager_state = &state.into();- // check for the customer- // TODO: customer need not be checked again here, this function can take an optional customer and check for existence of customer based on the optional value- let customer = db- .find_customer_by_customer_id_merchant_id(- key_manager_state,- customer_id,- merchant_id,- &key_store,- storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;- // check for the presence of payment_method- let payment_method = db- .find_payment_method(- &(state.into()),- &key_store,- &payment_method_id,- storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;- let pm = payment_method- .get_payment_method_type()- .get_required_value("payment_method")?;-- utils::when(- &payment_method.customer_id != customer_id || payment_method.merchant_id != *merchant_id,- || {- Err(errors::ApiErrorResponse::PreconditionFailed {- message: "The payment_method_id is not valid".to_string(),- })- },- )?;-- utils::when(- Some(payment_method_id.clone()) == customer.default_payment_method_id,- || {- Err(errors::ApiErrorResponse::PreconditionFailed {- message: "Payment Method is already set as default".to_string(),- })- },- )?;-- let customer_id = customer.customer_id.clone();-- let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {- default_payment_method_id: Some(Some(payment_method_id.to_owned())),- };- // update the db with the default payment method id-- let updated_customer_details = db- .update_customer_by_customer_id_merchant_id(- key_manager_state,- customer_id.to_owned(),- merchant_id.to_owned(),- customer,- customer_update,- &key_store,- storage_scheme,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to update the default payment method id for the customer")?;-- let resp = api_models::payment_methods::CustomerDefaultPaymentMethodResponse {- default_payment_method_id: updated_customer_details.default_payment_method_id,- customer_id,- payment_method_type: payment_method.get_payment_method_subtype(),- payment_method: pm,- };-- Ok(services::ApplicationResponse::Json(resp))-}-pub async fn update_last_used_at(payment_method: &domain::PaymentMethod,state: &routes::SessionState,@@ -5749,170 +5001,6 @@ impl TempLockerCardSupport {}}-#[cfg(all(- any(feature = "v2", feature = "v1"),- not(feature = "payment_methods_v2")-))]-#[instrument(skip_all)]-pub async fn retrieve_payment_method(- state: routes::SessionState,- pm: api::PaymentMethodId,- merchant_context: domain::MerchantContext,-) -> errors::RouterResponse<api::PaymentMethodResponse> {- let db = state.store.as_ref();- let pm = db- .find_payment_method(- &((&state).into()),- merchant_context.get_merchant_key_store(),- &pm.payment_method_id,- merchant_context.get_merchant_account().storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;-- let card = if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) {- let card_detail = if state.conf.locker.locker_enabled {- let card = get_card_from_locker(- &state,- &pm.customer_id,- &pm.merchant_id,- pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Error getting card from card vault")?;- payment_methods::get_card_detail(&pm, card)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed while getting card details from locker")?- } else {- get_card_details_without_locker_fallback(&pm, &state).await?- };- Some(card_detail)- } else {- None- };- Ok(services::ApplicationResponse::Json(- api::PaymentMethodResponse {- merchant_id: pm.merchant_id.clone(),- customer_id: Some(pm.customer_id.clone()),- payment_method_id: pm.payment_method_id.clone(),- payment_method: pm.get_payment_method_type(),- payment_method_type: pm.get_payment_method_subtype(),- #[cfg(feature = "payouts")]- bank_transfer: None,- card,- metadata: pm.metadata,- created: Some(pm.created_at),- recurring_enabled: false,- installment_payment_enabled: false,- payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),- last_used_at: Some(pm.last_used_at),- client_secret: pm.client_secret,- },- ))-}--#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]-#[instrument(skip_all)]-pub async fn delete_payment_method(- state: routes::SessionState,- merchant_context: domain::MerchantContext,- pm_id: api::PaymentMethodId,-) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> {- let db = state.store.as_ref();- let key_manager_state = &(&state).into();- let key = db- .find_payment_method(- &((&state).into()),- merchant_context.get_merchant_key_store(),- pm_id.payment_method_id.as_str(),- merchant_context.get_merchant_account().storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;-- let customer = db- .find_customer_by_customer_id_merchant_id(- key_manager_state,- &key.customer_id,- merchant_context.get_merchant_account().get_id(),- merchant_context.get_merchant_key_store(),- merchant_context.get_merchant_account().storage_scheme,- )- .await- .to_not_found_response(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Customer not found for the payment method")?;-- if key.get_payment_method_type() == Some(enums::PaymentMethod::Card) {- let response = delete_card_from_locker(- &state,- &key.customer_id,- &key.merchant_id,- key.locker_id.as_ref().unwrap_or(&key.payment_method_id),- )- .await?;-- if let Some(network_token_ref_id) = key.network_token_requestor_reference_id {- let resp = network_tokenization::delete_network_token_from_locker_and_token_service(- &state,- &key.customer_id,- &key.merchant_id,- key.payment_method_id.clone(),- key.network_token_locker_id,- network_token_ref_id,- )- .await?;-- if resp.status == "Ok" {- logger::info!("Token From locker deleted Successfully!");- } else {- logger::error!("Error: Deleting Token From Locker!\n{:#?}", resp);- }- }-- if response.status == "Ok" {- logger::info!("Card From locker deleted Successfully!");- } else {- logger::error!("Error: Deleting Card From Locker!\n{:#?}", response);- Err(errors::ApiErrorResponse::InternalServerError)?- }- }-- db.delete_payment_method_by_merchant_id_payment_method_id(- &((&state).into()),- merchant_context.get_merchant_key_store(),- merchant_context.get_merchant_account().get_id(),- pm_id.payment_method_id.as_str(),- )- .await- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;-- if customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id) {- let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {- default_payment_method_id: Some(None),- };- db.update_customer_by_customer_id_merchant_id(- key_manager_state,- key.customer_id,- key.merchant_id,- customer,- customer_update,- merchant_context.get_merchant_key_store(),- merchant_context.get_merchant_account().storage_scheme,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to update the default payment method id for the customer")?;- };-- Ok(services::ApplicationResponse::Json(- api::PaymentMethodDeleteResponse {- payment_method_id: key.payment_method_id.clone(),- deleted: true,- },- ))-}-pub async fn create_encrypted_data<T>(key_manager_state: &KeyManagerState,key_store: &domain::MerchantKeyStore,diff --git a/crates/router/src/core/payment_methods/network_tokenization.rs b/crates/router/src/core/payment_methods/network_tokenization.rsindex 3c3c7afd31..0a259d6c51 100644--- a/crates/router/src/core/payment_methods/network_tokenization.rs+++ b/crates/router/src/core/payment_methods/network_tokenization.rs@@ -3,6 +3,7 @@ use std::fmt::Debug;#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]use std::str::FromStr;+use ::payment_methods::controller::PaymentMethodsController;use api_models::payment_methods as api_payment_methods;#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]use cards::{CardNumber, NetworkToken};@@ -820,10 +821,14 @@ pub async fn delete_network_token_from_locker_and_token_service(payment_method_id: String,network_token_locker_id: Option<String>,network_token_requestor_reference_id: String,+ merchant_context: &domain::MerchantContext,) -> errors::RouterResult<DeleteCardResp> {//deleting network token from locker- let resp = payment_methods::cards::delete_card_from_locker(+ let resp = payment_methods::cards::PmCards {state,+ merchant_context,+ }+ .delete_card_from_locker(customer_id,merchant_id,network_token_locker_iddiff --git a/crates/router/src/core/payment_methods/tokenize.rs b/crates/router/src/core/payment_methods/tokenize.rsindex 21e2ed4fee..cc27e813b5 100644--- a/crates/router/src/core/payment_methods/tokenize.rs+++ b/crates/router/src/core/payment_methods/tokenize.rs@@ -11,7 +11,6 @@ use hyperswitch_domain_models::router_request_types as domain_request_types;use masking::{ExposeInterface, Secret};use router_env::logger;-use super::migration;use crate::{core::payment_methods::{cards::{add_card_to_hs_locker, create_encrypted_data, tokenize_card_flow},diff --git a/crates/router/src/core/payment_methods/tokenize/card_executor.rs b/crates/router/src/core/payment_methods/tokenize/card_executor.rsindex eb9d3d6b6c..b714bdb9a6 100644--- a/crates/router/src/core/payment_methods/tokenize/card_executor.rs+++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs@@ -1,5 +1,6 @@use std::str::FromStr;+use ::payment_methods::{controller::PaymentMethodsController, core::migration};use api_models::{enums as api_enums, payment_methods as payment_methods_api};use common_utils::{consts,@@ -15,12 +16,12 @@ use masking::{ExposeInterface, PeekInterface, SwitchStrategy};use router_env::logger;use super::{- migration, CardNetworkTokenizeExecutor, NetworkTokenizationBuilder, NetworkTokenizationProcess,+ CardNetworkTokenizeExecutor, NetworkTokenizationBuilder, NetworkTokenizationProcess,NetworkTokenizationResponse, State, StoreLockerResponse, TransitionTo,};use crate::{core::payment_methods::{- cards::{add_card_to_hs_locker, create_payment_method},+ cards::{add_card_to_hs_locker, PmCards},transformers as pm_transformers,},errors::{self, RouterResult},@@ -563,8 +564,14 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> {connector_mandate_details: None,network_transaction_id: None,};- create_payment_method(- self.state,+ PmCards {+ state: self.state,+ merchant_context: &domain::MerchantContext::NormalMerchant(Box::new(domain::Context(+ self.merchant_account.clone(),+ self.key_store.clone(),+ ))),+ }+ .create_payment_method(&payment_method_create,customer_id,&payment_method_id,@@ -573,11 +580,9 @@ impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> {None,None,Some(enc_pm_data),- self.key_store,None,None,None,- self.merchant_account.storage_scheme,None,None,network_token_details.1.clone(),diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rsindex 56a3173285..e60de6b782 100644--- a/crates/router/src/core/payment_methods/transformers.rs+++ b/crates/router/src/core/payment_methods/transformers.rs@@ -1,3 +1,4 @@+pub use ::payment_methods::controller::{DataDuplicationCheck, DeleteCardResp};use api_models::{enums as api_enums, payment_methods::Card};use common_utils::{ext_traits::{Encode, StringExt},@@ -73,13 +74,6 @@ pub struct StoreCardRespPayload {pub duplication_check: Option<DataDuplicationCheck>,}-#[derive(Debug, Deserialize, Serialize, PartialEq)]-#[serde(rename_all = "snake_case")]-pub enum DataDuplicationCheck {- Duplicated,- MetaDataChanged,-}-#[derive(Debug, Deserialize, Serialize)]pub struct CardReqBody {pub merchant_id: id_type::MerchantId,@@ -109,13 +103,6 @@ pub struct RetrieveCardRespPayload {pub enc_card_data: Option<Secret<String>>,}-#[derive(Debug, Deserialize, Serialize)]-pub struct DeleteCardResp {- pub status: String,- pub error_message: Option<String>,- pub error_code: Option<String>,-}-#[derive(Debug, Deserialize, Serialize)]#[serde(rename_all = "camelCase")]pub struct AddCardRequest {diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex b57564233e..ca3b5d9a2d 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -1,5 +1,9 @@use std::{borrow::Cow, collections::HashSet, net::IpAddr, str::FromStr};+pub use ::payment_methods::helpers::{+ populate_bin_details_for_payment_method_create,+ validate_payment_method_type_against_payment_method,+};#[cfg(feature = "v2")]use api_models::ephemeral_key::ClientSecretResponse;use api_models::{@@ -2953,166 +2957,6 @@ pub(crate) fn validate_payment_method_fields_present(Ok(())}-pub fn validate_payment_method_type_against_payment_method(- payment_method: api_enums::PaymentMethod,- payment_method_type: api_enums::PaymentMethodType,-) -> bool {- match payment_method {- #[cfg(feature = "v1")]- api_enums::PaymentMethod::Card => matches!(- payment_method_type,- api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit- ),- #[cfg(feature = "v2")]- api_enums::PaymentMethod::Card => matches!(- payment_method_type,- api_enums::PaymentMethodType::Credit- | api_enums::PaymentMethodType::Debit- | api_enums::PaymentMethodType::Card- ),- api_enums::PaymentMethod::PayLater => matches!(- payment_method_type,- api_enums::PaymentMethodType::Affirm- | api_enums::PaymentMethodType::Alma- | api_enums::PaymentMethodType::AfterpayClearpay- | api_enums::PaymentMethodType::Klarna- | api_enums::PaymentMethodType::PayBright- | api_enums::PaymentMethodType::Atome- | api_enums::PaymentMethodType::Walley- ),- api_enums::PaymentMethod::Wallet => matches!(- payment_method_type,- api_enums::PaymentMethodType::AmazonPay- | api_enums::PaymentMethodType::ApplePay- | api_enums::PaymentMethodType::GooglePay- | api_enums::PaymentMethodType::Paypal- | api_enums::PaymentMethodType::AliPay- | api_enums::PaymentMethodType::AliPayHk- | api_enums::PaymentMethodType::Dana- | api_enums::PaymentMethodType::MbWay- | api_enums::PaymentMethodType::MobilePay- | api_enums::PaymentMethodType::SamsungPay- | api_enums::PaymentMethodType::Twint- | api_enums::PaymentMethodType::Vipps- | api_enums::PaymentMethodType::TouchNGo- | api_enums::PaymentMethodType::Swish- | api_enums::PaymentMethodType::WeChatPay- | api_enums::PaymentMethodType::GoPay- | api_enums::PaymentMethodType::Gcash- | api_enums::PaymentMethodType::Momo- | api_enums::PaymentMethodType::KakaoPay- | api_enums::PaymentMethodType::Cashapp- | api_enums::PaymentMethodType::Mifinity- | api_enums::PaymentMethodType::Paze- ),- api_enums::PaymentMethod::BankRedirect => matches!(- payment_method_type,- api_enums::PaymentMethodType::Giropay- | api_enums::PaymentMethodType::Ideal- | api_enums::PaymentMethodType::Sofort- | api_enums::PaymentMethodType::Eft- | api_enums::PaymentMethodType::Eps- | api_enums::PaymentMethodType::BancontactCard- | api_enums::PaymentMethodType::Blik- | api_enums::PaymentMethodType::LocalBankRedirect- | api_enums::PaymentMethodType::OnlineBankingThailand- | api_enums::PaymentMethodType::OnlineBankingCzechRepublic- | api_enums::PaymentMethodType::OnlineBankingFinland- | api_enums::PaymentMethodType::OnlineBankingFpx- | api_enums::PaymentMethodType::OnlineBankingPoland- | api_enums::PaymentMethodType::OnlineBankingSlovakia- | api_enums::PaymentMethodType::Przelewy24- | api_enums::PaymentMethodType::Trustly- | api_enums::PaymentMethodType::Bizum- | api_enums::PaymentMethodType::Interac- | api_enums::PaymentMethodType::OpenBankingUk- | api_enums::PaymentMethodType::OpenBankingPIS- ),- api_enums::PaymentMethod::BankTransfer => matches!(- payment_method_type,- api_enums::PaymentMethodType::Ach- | api_enums::PaymentMethodType::SepaBankTransfer- | api_enums::PaymentMethodType::Bacs- | api_enums::PaymentMethodType::Multibanco- | api_enums::PaymentMethodType::Pix- | api_enums::PaymentMethodType::Pse- | api_enums::PaymentMethodType::PermataBankTransfer- | api_enums::PaymentMethodType::BcaBankTransfer- | api_enums::PaymentMethodType::BniVa- | api_enums::PaymentMethodType::BriVa- | api_enums::PaymentMethodType::CimbVa- | api_enums::PaymentMethodType::DanamonVa- | api_enums::PaymentMethodType::MandiriVa- | api_enums::PaymentMethodType::LocalBankTransfer- | api_enums::PaymentMethodType::InstantBankTransfer- ),- api_enums::PaymentMethod::BankDebit => matches!(- payment_method_type,- api_enums::PaymentMethodType::Ach- | api_enums::PaymentMethodType::Sepa- | api_enums::PaymentMethodType::Bacs- | api_enums::PaymentMethodType::Becs- ),- api_enums::PaymentMethod::Crypto => matches!(- payment_method_type,- api_enums::PaymentMethodType::CryptoCurrency- ),- api_enums::PaymentMethod::Reward => matches!(- payment_method_type,- api_enums::PaymentMethodType::Evoucher | api_enums::PaymentMethodType::ClassicReward- ),- api_enums::PaymentMethod::RealTimePayment => matches!(- payment_method_type,- api_enums::PaymentMethodType::Fps- | api_enums::PaymentMethodType::DuitNow- | api_enums::PaymentMethodType::PromptPay- | api_enums::PaymentMethodType::VietQr- ),- api_enums::PaymentMethod::Upi => matches!(- payment_method_type,- api_enums::PaymentMethodType::UpiCollect | api_enums::PaymentMethodType::UpiIntent- ),- api_enums::PaymentMethod::Voucher => matches!(- payment_method_type,- api_enums::PaymentMethodType::Boleto- | api_enums::PaymentMethodType::Efecty- | api_enums::PaymentMethodType::PagoEfectivo- | api_enums::PaymentMethodType::RedCompra- | api_enums::PaymentMethodType::RedPagos- | api_enums::PaymentMethodType::Indomaret- | api_enums::PaymentMethodType::Alfamart- | api_enums::PaymentMethodType::Oxxo- | api_enums::PaymentMethodType::SevenEleven- | api_enums::PaymentMethodType::Lawson- | api_enums::PaymentMethodType::MiniStop- | api_enums::PaymentMethodType::FamilyMart- | api_enums::PaymentMethodType::Seicomart- | api_enums::PaymentMethodType::PayEasy- ),- api_enums::PaymentMethod::GiftCard => {- matches!(- payment_method_type,- api_enums::PaymentMethodType::Givex | api_enums::PaymentMethodType::PaySafeCard- )- }- api_enums::PaymentMethod::CardRedirect => matches!(- payment_method_type,- api_enums::PaymentMethodType::Knet- | api_enums::PaymentMethodType::Benefit- | api_enums::PaymentMethodType::MomoAtm- | api_enums::PaymentMethodType::CardRedirect- ),- api_enums::PaymentMethod::OpenBanking => matches!(- payment_method_type,- api_enums::PaymentMethodType::OpenBankingPIS- ),- api_enums::PaymentMethod::MobilePayment => matches!(- payment_method_type,- api_enums::PaymentMethodType::DirectCarrierBilling- ),- }-}-pub fn check_force_psync_precondition(status: storage_enums::AttemptStatus) -> bool {!matches!(status,@@ -5130,75 +4974,6 @@ pub async fn get_additional_payment_data(}}-#[cfg(all(- any(feature = "v1", feature = "v2"),- not(feature = "payment_methods_v2")-))]-pub async fn populate_bin_details_for_payment_method_create(- card_details: api_models::payment_methods::CardDetail,- db: &dyn StorageInterface,-) -> api_models::payment_methods::CardDetail {- let card_isin: Option<_> = Some(card_details.card_number.get_card_isin());- if card_details.card_issuer.is_some()- && card_details.card_network.is_some()- && card_details.card_type.is_some()- && card_details.card_issuing_country.is_some()- {- api::CardDetail {- card_issuer: card_details.card_issuer.to_owned(),- card_network: card_details.card_network.clone(),- card_type: card_details.card_type.to_owned(),- card_issuing_country: card_details.card_issuing_country.to_owned(),- card_exp_month: card_details.card_exp_month.clone(),- card_exp_year: card_details.card_exp_year.clone(),- card_holder_name: card_details.card_holder_name.clone(),- card_number: card_details.card_number.clone(),- nick_name: card_details.nick_name.clone(),- }- } else {- let card_info = card_isin- .clone()- .async_and_then(|card_isin| async move {- db.get_card_info(&card_isin)- .await- .map_err(|error| services::logger::error!(card_info_error=?error))- .ok()- })- .await- .flatten()- .map(|card_info| api::CardDetail {- card_issuer: card_info.card_issuer,- card_network: card_info.card_network.clone(),- card_type: card_info.card_type,- card_issuing_country: card_info.card_issuing_country,- card_exp_month: card_details.card_exp_month.clone(),- card_exp_year: card_details.card_exp_year.clone(),- card_holder_name: card_details.card_holder_name.clone(),- card_number: card_details.card_number.clone(),- nick_name: card_details.nick_name.clone(),- });- card_info.unwrap_or_else(|| api::CardDetail {- card_issuer: None,- card_network: None,- card_type: None,- card_issuing_country: None,- card_exp_month: card_details.card_exp_month.clone(),- card_exp_year: card_details.card_exp_year.clone(),- card_holder_name: card_details.card_holder_name.clone(),- card_number: card_details.card_number.clone(),- nick_name: card_details.nick_name.clone(),- })- }-}--#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]-pub async fn populate_bin_details_for_payment_method_create(- _card_details: api_models::payment_methods::CardDetail,- _db: &dyn StorageInterface,-) -> api_models::payment_methods::CardDetail {- todo!()-}-#[cfg(feature = "v1")]pub fn validate_customer_access(payment_intent: &PaymentIntent,diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rsindex 40cd4c8161..2500852363 100644--- a/crates/router/src/core/payments/tokenization.rs+++ b/crates/router/src/core/payments/tokenization.rs@@ -1,5 +1,6 @@use std::collections::HashMap;+use ::payment_methods::controller::PaymentMethodsController;#[cfg(all(any(feature = "v1", feature = "v2"),not(feature = "payment_methods_v2")@@ -28,7 +29,11 @@ use crate::{core::{errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt},mandate,- payment_methods::{self, cards::create_encrypted_data, network_tokenization},+ payment_methods::{+ self,+ cards::{create_encrypted_data, PmCards},+ network_tokenization,+ },payments,},logger,@@ -92,6 +97,10 @@ whereFData: mandate::MandateBehaviour + Clone,{let mut pm_status = None;+ let cards = PmCards {+ state,+ merchant_context,+ };match save_payment_method_data.response {Ok(responses) => {let db = &*state.store;@@ -400,31 +409,30 @@ whereif err.current_context().is_db_not_found() {let pm_metadata =create_payment_method_metadata(None, connector_token)?;- payment_methods::cards::create_payment_method(- state,- &payment_method_create_request,- &customer_id,- &resp.payment_method_id,- locker_id,- merchant_id,- pm_metadata,- customer_acceptance,- pm_data_encrypted,- merchant_context.get_merchant_key_store(),- None,- pm_status,- network_transaction_id,- merchant_context.get_merchant_account().storage_scheme,- encrypted_payment_method_billing_address,- resp.card.and_then(|card| {- card.card_network- .map(|card_network| card_network.to_string())- }),- network_token_requestor_ref_id,- network_token_locker_id,- pm_network_token_data_encrypted,- )- .await+ cards+ .create_payment_method(+ &payment_method_create_request,+ &customer_id,+ &resp.payment_method_id,+ locker_id,+ merchant_id,+ pm_metadata,+ customer_acceptance,+ pm_data_encrypted,+ None,+ pm_status,+ network_transaction_id,+ encrypted_payment_method_billing_address,+ resp.card.and_then(|card| {+ card.card_network.map(|card_network| {+ card_network.to_string()+ })+ }),+ network_token_requestor_ref_id,+ network_token_locker_id,+ pm_network_token_data_encrypted,+ )+ .await} else {Err(err).change_context(@@ -520,34 +528,30 @@ where}Err(err) => {if err.current_context().is_db_not_found() {- payment_methods::cards::create_payment_method(- state,- &payment_method_create_request,- &customer_id,- &resp.payment_method_id,- locker_id,- merchant_id,- resp.metadata.clone().map(|val| val.expose()),- customer_acceptance,- pm_data_encrypted,- merchant_context.get_merchant_key_store(),- None,- pm_status,- network_transaction_id,- merchant_context- .get_merchant_account()- .storage_scheme,- encrypted_payment_method_billing_address,- resp.card.and_then(|card| {- card.card_network.map(|card_network| {- card_network.to_string()- })- }),- network_token_requestor_ref_id,- network_token_locker_id,- pm_network_token_data_encrypted,- )- .await+ cards+ .create_payment_method(+ &payment_method_create_request,+ &customer_id,+ &resp.payment_method_id,+ locker_id,+ merchant_id,+ resp.metadata.clone().map(|val| val.expose()),+ customer_acceptance,+ pm_data_encrypted,+ None,+ pm_status,+ network_transaction_id,+ encrypted_payment_method_billing_address,+ resp.card.and_then(|card| {+ card.card_network.map(|card_network| {+ card_network.to_string()+ })+ }),+ network_token_requestor_ref_id,+ network_token_locker_id,+ pm_network_token_data_encrypted,+ )+ .await} else {Err(err).change_context(@@ -560,32 +564,31 @@ where}}?;- payment_methods::cards::delete_card_from_locker(- state,- &customer_id,- merchant_id,- existing_pm- .locker_id- .as_ref()- .unwrap_or(&existing_pm.payment_method_id),- )- .await?;-- let add_card_resp = payment_methods::cards::add_card_hs(- state,- payment_method_create_request,- &card,- &customer_id,- merchant_context,- api::enums::LockerChoice::HyperswitchCardVault,- Some(+ cards+ .delete_card_from_locker(+ &customer_id,+ merchant_id,existing_pm.locker_id.as_ref().unwrap_or(&existing_pm.payment_method_id),- ),- )- .await;+ )+ .await?;++ let add_card_resp = cards+ .add_card_hs(+ payment_method_create_request,+ &card,+ &customer_id,+ api::enums::LockerChoice::HyperswitchCardVault,+ Some(+ existing_pm+ .locker_id+ .as_ref()+ .unwrap_or(&existing_pm.payment_method_id),+ ),+ )+ .await;if let Err(err) = add_card_resp {logger::error!(vault_err=?err);@@ -606,8 +609,9 @@ where))?};- let existing_pm_data = payment_methods::cards::get_card_details_without_locker_fallback(&existing_pm,state)- .await?;+ let existing_pm_data = cards+ .get_card_details_without_locker_fallback(&existing_pm)+ .await?;// scheme should be updated in case of co-badged cardslet card_scheme = card@@ -745,31 +749,29 @@ where});resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");- payment_methods::cards::create_payment_method(- state,- &payment_method_create_request,- &customer_id,- &resp.payment_method_id,- locker_id,- merchant_id,- pm_metadata,- customer_acceptance,- pm_data_encrypted,- merchant_context.get_merchant_key_store(),- None,- pm_status,- network_transaction_id,- merchant_context.get_merchant_account().storage_scheme,- encrypted_payment_method_billing_address,- resp.card.and_then(|card| {- card.card_network- .map(|card_network| card_network.to_string())- }),- network_token_requestor_ref_id,- network_token_locker_id,- pm_network_token_data_encrypted,- )- .await?;+ cards+ .create_payment_method(+ &payment_method_create_request,+ &customer_id,+ &resp.payment_method_id,+ locker_id,+ merchant_id,+ pm_metadata,+ customer_acceptance,+ pm_data_encrypted,+ None,+ pm_status,+ network_transaction_id,+ encrypted_payment_method_billing_address,+ resp.card.and_then(|card| {+ card.card_network+ .map(|card_network| card_network.to_string())+ }),+ network_token_requestor_ref_id,+ network_token_locker_id,+ pm_network_token_data_encrypted,+ )+ .await?;};}}@@ -960,14 +962,13 @@ pub async fn save_in_locker(.clone().get_required_value("customer_id")?;match payment_method_request.card.clone() {- Some(card) => Box::pin(payment_methods::cards::add_card_to_locker(- state,- payment_method_request,- &card,- &customer_id,- merchant_context,- None,- ))+ Some(card) => Box::pin(+ PmCards {+ state,+ merchant_context,+ }+ .add_card_to_locker(payment_method_request, &card, &customer_id, None),+ ).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Add Card Failed"),@@ -1073,14 +1074,18 @@ pub async fn save_network_token_in_locker(card_type: None,};- let (res, dc) = Box::pin(payment_methods::cards::add_card_to_locker(- state,- payment_method_request,- &network_token_data,- &customer_id,- merchant_context,- None,- ))+ let (res, dc) = Box::pin(+ PmCards {+ state,+ merchant_context,+ }+ .add_card_to_locker(+ payment_method_request,+ &network_token_data,+ &customer_id,+ None,+ ),+ ).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Add Network Token Failed")?;diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rsindex 0320e04ecd..010331090d 100644--- a/crates/router/src/core/payouts/helpers.rs+++ b/crates/router/src/core/payouts/helpers.rs@@ -1,3 +1,4 @@+use ::payment_methods::controller::PaymentMethodsController;use api_models::{enums, payment_methods::Card, payouts};use common_utils::{crypto::Encryptable,@@ -559,8 +560,11 @@ pub async fn save_payout_data_to_locker(if should_insert_in_pm_table {let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm");payout_data.payment_method = Some(- cards::create_payment_method(+ cards::PmCards {state,+ merchant_context,+ }+ .create_payment_method(&new_payment_method,customer_id,&payment_method_id,@@ -569,11 +573,9 @@ pub async fn save_payout_data_to_locker(None,None,card_details_encrypted.clone(),- merchant_context.get_merchant_key_store(),connector_mandate_details,None,None,- merchant_context.get_merchant_account().storage_scheme,None,None,None,diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rsindex 21af91babd..9fbd50c3fc 100644--- a/crates/router/src/core/payouts/validator.rs+++ b/crates/router/src/core/payouts/validator.rs@@ -232,6 +232,7 @@ pub async fn validate_create_request(payment_method,None,false,+ merchant_context,).await?{diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rsindex a651962848..86769b393c 100644--- a/crates/router/src/core/webhooks/incoming.rs+++ b/crates/router/src/core/webhooks/incoming.rs@@ -1466,7 +1466,7 @@ async fn mandates_incoming_webhook_flow(&state,merchant_context.get_merchant_key_store().clone(),updated_mandate.clone(),- merchant_context.get_merchant_account().storage_scheme,+ merchant_context.get_merchant_account(),).await?,);diff --git a/crates/router/src/db.rs b/crates/router/src/db.rsindex 4120edb957..17938dbbe3 100644--- a/crates/router/src/db.rs+++ b/crates/router/src/db.rs@@ -8,7 +8,6 @@ pub mod blocklist_lookup;pub mod business_profile;pub mod callback_mapper;pub mod capture;-pub mod cards_info;pub mod configs;pub mod customers;pub mod dashboard_metadata;@@ -53,6 +52,7 @@ use hyperswitch_domain_models::payouts::{payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface,};use hyperswitch_domain_models::{+ cards_info::CardsInfoInterface,payment_methods::PaymentMethodInterface,payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface},};@@ -120,7 +120,7 @@ pub trait StorageInterface:+ PayoutsInterface<Error = StorageError>+ refund::RefundInterface+ reverse_lookup::ReverseLookupInterface- + cards_info::CardsInfoInterface+ + CardsInfoInterface<Error = StorageError>+ merchant_key_store::MerchantKeyStoreInterface+ MasterKeyInterface+ payment_link::PaymentLinkInterface@@ -142,7 +142,7 @@ pub trait StorageInterface:+ 'static{fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>;-+ fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface>;fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)>;}@@ -212,6 +212,9 @@ impl StorageInterface for Store {fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface> {Box::new(self.clone())}+ fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> {+ Box::new(self.clone())+ }fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)> {Box::new(self.clone())@@ -232,6 +235,9 @@ impl StorageInterface for MockDb {fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface> {Box::new(self.clone())}+ fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> {+ Box::new(self.clone())+ }fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)> {Box::new(self.clone())diff --git a/crates/router/src/db/cards_info.rs b/crates/router/src/db/cards_info.rsdeleted file mode 100644index 12e63cef62..0000000000--- a/crates/router/src/db/cards_info.rs+++ /dev/null@@ -1,87 +0,0 @@-use error_stack::report;-use router_env::{instrument, tracing};--use crate::{- connection,- core::errors::{self, CustomResult},- db::MockDb,- services::Store,- types::storage::cards_info::{CardInfo, UpdateCardInfo},-};--#[async_trait::async_trait]-pub trait CardsInfoInterface {- async fn get_card_info(- &self,- _card_iin: &str,- ) -> CustomResult<Option<CardInfo>, errors::StorageError>;- async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, errors::StorageError>;- async fn update_card_info(- &self,- card_iin: String,- data: UpdateCardInfo,- ) -> CustomResult<CardInfo, errors::StorageError>;-}--#[async_trait::async_trait]-impl CardsInfoInterface for Store {- #[instrument(skip_all)]- async fn get_card_info(- &self,- card_iin: &str,- ) -> CustomResult<Option<CardInfo>, errors::StorageError> {- let conn = connection::pg_connection_read(self).await?;- CardInfo::find_by_iin(&conn, card_iin)- .await- .map_err(|error| report!(errors::StorageError::from(error)))- }-- #[instrument(skip_all)]- async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, errors::StorageError> {- let conn = connection::pg_connection_write(self).await?;- data.insert(&conn)- .await- .map_err(|error| report!(errors::StorageError::from(error)))- }-- #[instrument(skip_all)]- async fn update_card_info(- &self,- card_iin: String,- data: UpdateCardInfo,- ) -> CustomResult<CardInfo, errors::StorageError> {- let conn = connection::pg_connection_write(self).await?;- CardInfo::update(&conn, card_iin, data)- .await- .map_err(|error| report!(errors::StorageError::from(error)))- }-}--#[async_trait::async_trait]-impl CardsInfoInterface for MockDb {- #[instrument(skip_all)]- async fn get_card_info(- &self,- card_iin: &str,- ) -> CustomResult<Option<CardInfo>, errors::StorageError> {- Ok(self- .cards_info- .lock()- .await- .iter()- .find(|ci| ci.card_iin == card_iin)- .cloned())- }-- async fn add_card_info(&self, _data: CardInfo) -> CustomResult<CardInfo, errors::StorageError> {- Err(errors::StorageError::MockDbError)?- }-- async fn update_card_info(- &self,- _card_iin: String,- _data: UpdateCardInfo,- ) -> CustomResult<CardInfo, errors::StorageError> {- Err(errors::StorageError::MockDbError)?- }-}diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 1ef8178580..8dbef1d30f 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -21,6 +21,7 @@ use hyperswitch_domain_models::payouts::{payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface,};use hyperswitch_domain_models::{+ cards_info::CardsInfoInterface,disputes,payment_methods::PaymentMethodInterface,payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface},@@ -61,7 +62,6 @@ use crate::{business_profile::ProfileInterface,callback_mapper::CallbackMapperInterface,capture::CaptureInterface,- cards_info::CardsInfoInterface,configs::ConfigInterface,customers::CustomerInterface,dispute::DisputeInterface,@@ -286,6 +286,7 @@ impl ApiKeyInterface for KafkaStore {#[async_trait::async_trait]impl CardsInfoInterface for KafkaStore {+ type Error = errors::StorageError;async fn get_card_info(&self,card_iin: &str,@@ -3297,6 +3298,10 @@ impl StorageInterface for KafkaStore {Box::new(self.clone())}+ fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface> {+ Box::new(self.clone())+ }+fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)> {Box::new(self.clone())}diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex d473936f34..2de8d5ebc6 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -1,3 +1,7 @@+use ::payment_methods::{+ controller::PaymentMethodsController,+ core::{migration, migration::payment_methods::migrate_payment_method},+};#[cfg(all(any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"),all(not(feature = "customer_v2"), not(feature = "payment_methods_v2"))@@ -31,10 +35,7 @@ use crate::{not(feature = "customer_v2")))]use crate::{- core::{- customers,- payment_methods::{migration, tokenize},- },+ core::{customers, payment_methods::tokenize},types::api::customers::CustomerRequest,};@@ -281,7 +282,6 @@ pub async fn migrate_payment_method_api(json_payload: web::Json<payment_methods::PaymentMethodMigrate>,) -> HttpResponse {let flow = Flow::PaymentMethodsMigrate;-Box::pin(api::server_wrap(flow,state,@@ -293,11 +293,15 @@ pub async fn migrate_payment_method_api(let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(merchant_account, key_store),));- Box::pin(cards::migrate_payment_method(- state,+ Box::pin(migrate_payment_method(+ &(&state).into(),req,&merchant_id,&merchant_context,+ &cards::PmCards {+ state: &state,+ merchant_context: &merchant_context,+ },)).await},@@ -373,12 +377,17 @@ pub async fn migrate_payment_methods().await.change_context(errors::ApiErrorResponse::InternalServerError)?;+ let controller = cards::PmCards {+ state: &state,+ merchant_context: &merchant_context,+ };Box::pin(migration::migrate_payment_methods(- state,+ &(&state).into(),req,&merchant_id,&merchant_context,merchant_connector_id,+ &controller,)).await}@@ -807,11 +816,16 @@ pub async fn payment_method_retrieve_api(state,&req,payload,- |state, auth: auth::AuthenticationData, pm, _| {+ |state, auth: auth::AuthenticationData, pm, _| async move {let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(auth.merchant_account, auth.key_store),));- cards::retrieve_payment_method(state, pm, merchant_context)+ cards::PmCards {+ state: &state,+ merchant_context: &merchant_context,+ }+ .retrieve_payment_method(pm)+ .await},&auth::HeaderAuth(auth::ApiKeyAuth {is_connected_allowed: false,@@ -887,11 +901,16 @@ pub async fn payment_method_delete_api(state,&req,pm,- |state, auth: auth::AuthenticationData, req, _| {+ |state, auth: auth::AuthenticationData, req, _| async move {let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(auth.merchant_account, auth.key_store),));- cards::delete_payment_method(state, merchant_context, req)+ cards::PmCards {+ state: &state,+ merchant_context: &merchant_context,+ }+ .delete_payment_method(req)+ .await},&*ephemeral_auth,api_locking::LockAction::NotApplicable,@@ -963,13 +982,17 @@ pub async fn default_payment_method_set_api(&req,payload,|state, auth: auth::AuthenticationData, default_payment_method, _| async move {- cards::set_default_payment_method(- &state,- auth.merchant_account.get_id(),- auth.key_store,+ let merchant_id = auth.merchant_account.get_id();+ cards::PmCards {+ state: &state,+ merchant_context: &domain::MerchantContext::NormalMerchant(Box::new(+ domain::Context(auth.merchant_account.clone(), auth.key_store),+ )),+ }+ .set_default_payment_method(+ merchant_id,customer_id,default_payment_method.payment_method_id,- auth.merchant_account.storage_scheme,).await},diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rsindex 949eac3974..1ad9731bc1 100644--- a/crates/router/src/types/api/mandates.rs+++ b/crates/router/src/types/api/mandates.rs@@ -1,3 +1,4 @@+use ::payment_methods::controller::PaymentMethodsController;use api_models::mandates;pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse};use common_utils::ext_traits::OptionExt;@@ -28,7 +29,7 @@ pub(crate) trait MandateResponseExt: Sized {state: &SessionState,key_store: domain::MerchantKeyStore,mandate: storage::Mandate,- storage_scheme: storage_enums::MerchantStorageScheme,+ merchant_account: &domain::MerchantAccount,) -> RouterResult<Self>;}@@ -42,7 +43,7 @@ impl MandateResponseExt for MandateResponse {state: &SessionState,key_store: domain::MerchantKeyStore,mandate: storage::Mandate,- storage_scheme: storage_enums::MerchantStorageScheme,+ merchant_account: &domain::MerchantAccount,) -> RouterResult<Self> {let db = &*state.store;let payment_method = db@@ -50,7 +51,7 @@ impl MandateResponseExt for MandateResponse {&(state.into()),&key_store,&mandate.payment_method_id,- storage_scheme,+ merchant_account.storage_scheme,).await.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;@@ -79,10 +80,14 @@ impl MandateResponseExt for MandateResponse {.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed while getting card details")?} else {- payment_methods::cards::get_card_details_without_locker_fallback(- &payment_method,+ let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(+ domain::Context(merchant_account.clone(), key_store),+ ));+ payment_methods::cards::PmCards {state,- )+ merchant_context: &merchant_context,+ }+ .get_card_details_without_locker_fallback(&payment_method).await?};@@ -123,7 +128,7 @@ impl MandateResponseExt for MandateResponse {state: &SessionState,key_store: domain::MerchantKeyStore,mandate: storage::Mandate,- storage_scheme: storage_enums::MerchantStorageScheme,+ merchant_account: &domain::MerchantAccount,) -> RouterResult<Self> {todo!()}diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rsindex bb12365906..42eb6f68e2 100644--- a/crates/router/src/types/domain/types.rs+++ b/crates/router/src/types/domain/types.rs@@ -1,10 +1,13 @@+use ::payment_methods::state as pm_state;use common_utils::types::keymanager::KeyManagerState;pub use hyperswitch_domain_models::type_encryption::{crypto_operation, AsyncLift, CryptoOperation, Lift, OptionalEncryptableJsonType,};-impl From<&crate::SessionState> for KeyManagerState {- fn from(state: &crate::SessionState) -> Self {+use crate::routes::app;++impl From<&app::SessionState> for KeyManagerState {+ fn from(state: &app::SessionState) -> Self {let conf = state.conf.key_manager.get_inner();Self {global_tenant_id: state.conf.multitenancy.global_tenant.tenant_id.clone(),@@ -21,3 +24,13 @@ impl From<&crate::SessionState> for KeyManagerState {}}}++impl From<&app::SessionState> for pm_state::PaymentMethodsState {+ fn from(state: &app::SessionState) -> Self {+ Self {+ store: state.store.get_payment_methods_store(),+ key_store: None,+ key_manager_state: state.into(),+ }+ }+}diff --git a/crates/router/src/utils/ext_traits.rs b/crates/router/src/utils/ext_traits.rsindex 33fdb4c9b2..aa73426c85 100644--- a/crates/router/src/utils/ext_traits.rs+++ b/crates/router/src/utils/ext_traits.rs@@ -1,85 +1,6 @@-use common_utils::ext_traits::ValueExt;-use error_stack::{Report, ResultExt};+pub use hyperswitch_domain_models::ext_traits::OptionExt;-use crate::{- core::errors::{self, ApiErrorResponse, CustomResult, RouterResult},- utils::when,-};--pub trait OptionExt<T> {- fn check_value_present(&self, field_name: &'static str) -> RouterResult<()>;-- fn get_required_value(self, field_name: &'static str) -> RouterResult<T>;-- fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>- where- T: AsRef<str>,- E: std::str::FromStr,- // Requirement for converting the `Err` variant of `FromStr` to `Report<Err>`- <E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static;-- fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>- where- T: ValueExt,- U: serde::de::DeserializeOwned;-- fn update_value(&mut self, value: Option<T>);-}--impl<T> OptionExt<T> for Option<T> {- fn check_value_present(&self, field_name: &'static str) -> RouterResult<()> {- when(self.is_none(), || {- Err(- Report::new(ApiErrorResponse::MissingRequiredField { field_name })- .attach_printable(format!("Missing required field {field_name}")),- )- })- }-- // This will allow the error message that was generated in this function to point to the call site- #[track_caller]- fn get_required_value(self, field_name: &'static str) -> RouterResult<T> {- match self {- Some(v) => Ok(v),- None => Err(- Report::new(ApiErrorResponse::MissingRequiredField { field_name })- .attach_printable(format!("Missing required field {field_name}")),- ),- }- }-- fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>- where- T: AsRef<str>,- E: std::str::FromStr,- <E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,- {- let value = self- .get_required_value(enum_name)- .change_context(errors::ParsingError::UnknownError)?;-- E::from_str(value.as_ref())- .change_context(errors::ParsingError::UnknownError)- .attach_printable_lazy(|| format!("Invalid {{ {enum_name} }} "))- }-- fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>- where- T: ValueExt,- U: serde::de::DeserializeOwned,- {- let value = self- .get_required_value(type_name)- .change_context(errors::ParsingError::UnknownError)?;- value.parse_value(type_name)- }-- fn update_value(&mut self, value: Self) {- if let Some(a) = value {- *self = Some(a)- }- }-}+use crate::core::errors::{self, CustomResult};pub trait ValidateCall<T, F> {fn validate_opt(self, func: F) -> CustomResult<(), errors::ValidationError>;diff --git a/crates/storage_impl/src/cards_info.rs b/crates/storage_impl/src/cards_info.rsnew file mode 100644index 0000000000..99e4053be2--- /dev/null+++ b/crates/storage_impl/src/cards_info.rs@@ -0,0 +1,101 @@+pub use diesel_models::{CardInfo, UpdateCardInfo};+use error_stack::report;+use hyperswitch_domain_models::cards_info::CardsInfoInterface;+use router_env::{instrument, tracing};++use crate::{+ errors::StorageError,+ kv_router_store::KVRouterStore,+ redis::kv_store::KvStorePartition,+ utils::{pg_connection_read, pg_connection_write},+ CustomResult, DatabaseStore, MockDb, RouterStore,+};++impl KvStorePartition for CardInfo {}++#[async_trait::async_trait]+impl<T: DatabaseStore> CardsInfoInterface for RouterStore<T> {+ type Error = StorageError;+ #[instrument(skip_all)]+ async fn get_card_info(&self, card_iin: &str) -> CustomResult<Option<CardInfo>, StorageError> {+ let conn = pg_connection_read(self).await?;+ CardInfo::find_by_iin(&conn, card_iin)+ .await+ .map_err(|error| report!(StorageError::from(error)))+ }+ #[instrument(skip_all)]+ async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, StorageError> {+ let conn = pg_connection_write(self).await?;+ data.insert(&conn)+ .await+ .map_err(|error| report!(StorageError::from(error)))+ }+ #[instrument(skip_all)]+ async fn update_card_info(+ &self,+ card_iin: String,+ data: UpdateCardInfo,+ ) -> CustomResult<CardInfo, StorageError> {+ let conn = pg_connection_write(self).await?;+ CardInfo::update(&conn, card_iin, data)+ .await+ .map_err(|error| report!(StorageError::from(error)))+ }+}++#[async_trait::async_trait]+impl<T: DatabaseStore> CardsInfoInterface for KVRouterStore<T> {+ type Error = StorageError;+ #[instrument(skip_all)]+ async fn get_card_info(&self, card_iin: &str) -> CustomResult<Option<CardInfo>, StorageError> {+ let conn = pg_connection_read(self).await?;+ CardInfo::find_by_iin(&conn, card_iin)+ .await+ .map_err(|error| report!(StorageError::from(error)))+ }+ #[instrument(skip_all)]+ async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, StorageError> {+ let conn = pg_connection_write(self).await?;+ data.insert(&conn)+ .await+ .map_err(|error| report!(StorageError::from(error)))+ }+ #[instrument(skip_all)]+ async fn update_card_info(+ &self,+ card_iin: String,+ data: UpdateCardInfo,+ ) -> CustomResult<CardInfo, StorageError> {+ let conn = pg_connection_write(self).await?;+ CardInfo::update(&conn, card_iin, data)+ .await+ .map_err(|error| report!(StorageError::from(error)))+ }+}++#[async_trait::async_trait]+impl CardsInfoInterface for MockDb {+ type Error = StorageError;+ #[instrument(skip_all)]+ async fn get_card_info(&self, card_iin: &str) -> CustomResult<Option<CardInfo>, StorageError> {+ Ok(self+ .cards_info+ .lock()+ .await+ .iter()+ .find(|ci| ci.card_iin == card_iin)+ .cloned())+ }++ async fn add_card_info(&self, _data: CardInfo) -> CustomResult<CardInfo, StorageError> {+ Err(StorageError::MockDbError)?+ }++ async fn update_card_info(+ &self,+ _card_iin: String,+ _data: UpdateCardInfo,+ ) -> CustomResult<CardInfo, StorageError> {+ Err(StorageError::MockDbError)?+ }+}diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rsindex 26e3792f54..6cc5f035a7 100644--- a/crates/storage_impl/src/lib.rs+++ b/crates/storage_impl/src/lib.rs@@ -10,6 +10,7 @@ use masking::StrongSecret;use redis::{kv_store::RedisConnInterface, pub_sub::PubSubInterface, RedisStore};mod address;pub mod callback_mapper;+pub mod cards_info;pub mod config;pub mod connection;pub mod customers;diff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rsindex 89e7d32b85..afb08146aa 100644--- a/crates/storage_impl/src/payment_method.rs+++ b/crates/storage_impl/src/payment_method.rs@@ -1,4 +1,4 @@-use diesel_models::payment_method::PaymentMethod;+pub use diesel_models::payment_method::PaymentMethod;use crate::redis::kv_store::KvStorePartition;