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(storage_impl): Move Conversion impl for customer, payment_methods to storage_impl crate (#11807)
Anurag Thakur29fafe4d9d51
diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rsindex e4f3b69a57..93780a4979 100644--- a/crates/hyperswitch_domain_models/src/customer.rs+++ b/crates/hyperswitch_domain_models/src/customer.rs@@ -1,47 +1,41 @@use common_enums::enums::MerchantStorageScheme;#[cfg(feature = "v2")]use common_enums::DeleteStatus;+#[cfg(feature = "v1")]+use common_utils::date_time;+#[cfg(feature = "v1")]+use common_utils::ext_traits::ValueExt;use common_utils::{crypto::{self, Encryptable, OptionalEncryptableValue},- date_time,encryption::Encryption,- errors::{CustomResult, ValidationError},- ext_traits::ValueExt,+ errors::CustomResult,id_type, pii,- types::{- keymanager::{self, KeyManagerState, ToEncryptable},- CreatedBy, Description,- },+ types::{keymanager::ToEncryptable, CreatedBy, Description},};-use diesel_models::{- customers as storage_types, customers::CustomerUpdateInternal, query::customers as query,-};-use error_stack::ResultExt;-use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret, SwitchStrategy};+use diesel_models::query::customers as query;+#[cfg(feature = "v1")]+use hyperswitch_masking::ExposeInterface;+use hyperswitch_masking::Secret;use router_env::{instrument, tracing};use rustc_hash::FxHashMap;+#[cfg(feature = "v1")]use serde_json::Value;use time::PrimitiveDateTime;#[cfg(feature = "v2")]use crate::merchant_connector_account::MerchantConnectorAccountTypeDetails;-use crate::{- behaviour,- merchant_key_store::MerchantKeyStore,- platform,- type_encryption::{self as types, AsyncLift},-};+use crate::{merchant_key_store::MerchantKeyStore, platform};#[cfg(feature = "v1")]#[derive(Clone, Debug)]-struct CustomerIdentifiers {+pub struct CustomerIdentifiers {customer_id: id_type::CustomerId,id: Option<id_type::GlobalCustomerId>,}#[cfg(feature = "v1")]impl CustomerIdentifiers {- fn new(customer_id: id_type::CustomerId, id: Option<id_type::GlobalCustomerId>) -> Self {+ pub fn new(customer_id: id_type::CustomerId, id: Option<id_type::GlobalCustomerId>) -> Self {Self { customer_id, id }}}@@ -49,7 +43,7 @@ impl CustomerIdentifiers {#[cfg(feature = "v1")]#[derive(Clone, Debug, router_derive::ToEncryption)]pub struct Customer {- identifiers: CustomerIdentifiers,+ pub identifiers: CustomerIdentifiers,pub merchant_id: id_type::MerchantId,#[encrypt]pub name: Option<Encryptable<Secret<String>>>,@@ -126,33 +120,6 @@ pub struct CustomerWithoutEncrypted {pub last_modified_by: Option<CreatedBy>,}-#[cfg(feature = "v2")]-impl From<storage_types::Customer> for CustomerWithoutEncrypted {- fn from(customer: storage_types::Customer) -> Self {- Self {- merchant_id: customer.merchant_id,- phone_country_code: customer.phone_country_code,- description: customer.description,- created_at: customer.created_at,- metadata: customer.metadata,- connector_customer: customer.connector_customer,- modified_at: customer.modified_at,- default_payment_method_id: customer.default_payment_method_id,- updated_by: customer.updated_by,- merchant_reference_id: customer.merchant_reference_id,- id: customer.id,- version: customer.version,- status: customer.status,- created_by: customer- .created_by- .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),- last_modified_by: customer- .last_modified_by- .and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),- }- }-}-impl Customer {#[cfg(feature = "v1")]#[allow(clippy::too_many_arguments)]@@ -264,343 +231,6 @@ impl Customer {}}-#[cfg(feature = "v1")]-#[async_trait::async_trait]-impl behaviour::Conversion for Customer {- type DstType = diesel_models::customers::Customer;- type NewDstType = diesel_models::customers::CustomerNew;- async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {- Ok(diesel_models::customers::Customer {- customer_id: self.identifiers.customer_id.clone(),- merchant_id: self.merchant_id,- name: self.name.map(Encryption::from),- email: self.email.map(Encryption::from),- phone: self.phone.map(Encryption::from),- phone_country_code: self.phone_country_code,- description: self.description,- created_at: self.created_at,- metadata: self.metadata,- modified_at: self.modified_at,- connector_customer: self.connector_customer,- address_id: self.address_id,- default_payment_method_id: self.default_payment_method_id,- updated_by: self.updated_by,- version: self.version,- tax_registration_id: self.tax_registration_id.map(Encryption::from),- document_details: self.document_details.map(Encryption::from),- created_by: self.created_by.map(|created_by| created_by.to_string()),- last_modified_by: self- .last_modified_by- .map(|last_modified_by| last_modified_by.to_string()),- id: self.identifiers.id,- })- }-- async fn convert_back(- state: &KeyManagerState,- item: Self::DstType,- key: &Secret<Vec<u8>>,- _key_store_ref_id: keymanager::Identifier,- ) -> CustomResult<Self, ValidationError>- where- Self: Sized,- {- let decrypted = types::crypto_operation(- state,- common_utils::type_name!(Self::DstType),- types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable(- EncryptedCustomer {- name: item.name.clone(),- phone: item.phone.clone(),- email: item.email.clone(),- tax_registration_id: item.tax_registration_id.clone(),- },- )),- keymanager::Identifier::Merchant(item.merchant_id.clone()),- key.peek(),- )- .await- .and_then(|val| val.try_into_batchoperation())- .change_context(ValidationError::InvalidValue {- message: "Failed while decrypting customer data".to_string(),- })?;- let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context(- ValidationError::InvalidValue {- message: "Failed while decrypting customer data".to_string(),- },- )?;- let document_details = item- .document_details- .async_lift(|inner| async {- types::crypto_operation(- state,- common_utils::type_name!(Self),- types::CryptoOperation::DecryptOptional(inner),- keymanager::Identifier::Merchant(item.merchant_id.clone()),- key.peek(),- )- .await- .and_then(|val| val.try_into_optionaloperation())- })- .await- .change_context(ValidationError::InvalidValue {- message: "Failed to decrypt document details".to_string(),- })?;-- Ok(Self {- identifiers: CustomerIdentifiers::new(item.customer_id, item.id),- merchant_id: item.merchant_id,- name: encryptable_customer.name,- email: encryptable_customer.email.map(|email| {- let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(- email.clone().into_inner().switch_strategy(),- email.into_encrypted(),- );- encryptable- }),- phone: encryptable_customer.phone,- phone_country_code: item.phone_country_code,- description: item.description,- created_at: item.created_at,- metadata: item.metadata,- modified_at: item.modified_at,- connector_customer: item.connector_customer,- address_id: item.address_id,- default_payment_method_id: item.default_payment_method_id,- updated_by: item.updated_by,- version: item.version,- tax_registration_id: encryptable_customer.tax_registration_id,- document_details,- created_by: item- .created_by- .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),- last_modified_by: item- .last_modified_by- .and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),- })- }-- async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {- let now = date_time::now();- Ok(diesel_models::customers::CustomerNew {- id: self.identifiers.id,- customer_id: self.identifiers.customer_id,- merchant_id: self.merchant_id,- name: self.name.map(Encryption::from),- email: self.email.map(Encryption::from),- phone: self.phone.map(Encryption::from),- description: self.description,- phone_country_code: self.phone_country_code,- metadata: self.metadata,- created_at: now,- modified_at: now,- connector_customer: self.connector_customer,- address_id: self.address_id,- updated_by: self.updated_by,- version: self.version,- tax_registration_id: self.tax_registration_id.map(Encryption::from),- document_details: self.document_details.map(Encryption::from),- created_by: self- .created_by- .as_ref()- .map(|created_by| created_by.to_string()),- last_modified_by: self.created_by.map(|created_by| created_by.to_string()), // Same as created_by on creation- })- }-}--#[cfg(feature = "v2")]-#[async_trait::async_trait]-impl behaviour::Conversion for Customer {- type DstType = diesel_models::customers::Customer;- type NewDstType = diesel_models::customers::CustomerNew;- async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {- Ok(diesel_models::customers::Customer {- id: self.id.clone(),- customer_id: Some(self.id),- merchant_reference_id: self.merchant_reference_id,- merchant_id: self.merchant_id,- name: self.name.map(Encryption::from),- email: self.email.map(Encryption::from),- phone: self.phone.map(Encryption::from),- phone_country_code: self.phone_country_code,- description: self.description,- created_at: self.created_at,- metadata: self.metadata,- modified_at: self.modified_at,- connector_customer: self.connector_customer,- default_payment_method_id: self.default_payment_method_id,- updated_by: self.updated_by,- default_billing_address: self.default_billing_address.map(Encryption::from),- default_shipping_address: self.default_shipping_address.map(Encryption::from),- version: self.version,- status: self.status,- tax_registration_id: self.tax_registration_id.map(Encryption::from),- document_details: self.document_details.map(Encryption::from),- created_by: self.created_by.map(|created_by| created_by.to_string()),- last_modified_by: self- .last_modified_by- .map(|last_modified_by| last_modified_by.to_string()),- })- }-- async fn convert_back(- state: &KeyManagerState,- item: Self::DstType,- key: &Secret<Vec<u8>>,- _key_store_ref_id: keymanager::Identifier,- ) -> CustomResult<Self, ValidationError>- where- Self: Sized,- {- let decrypted = types::crypto_operation(- state,- common_utils::type_name!(Self::DstType),- types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable(- EncryptedCustomer {- name: item.name.clone(),- phone: item.phone.clone(),- email: item.email.clone(),- tax_registration_id: item.tax_registration_id.clone(),- },- )),- keymanager::Identifier::Merchant(item.merchant_id.clone()),- key.peek(),- )- .await- .and_then(|val| val.try_into_batchoperation())- .change_context(ValidationError::InvalidValue {- message: "Failed while decrypting customer data".to_string(),- })?;- let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context(- ValidationError::InvalidValue {- message: "Failed while decrypting customer data".to_string(),- },- )?;-- let default_billing_address = item- .default_billing_address- .async_lift(|inner| async {- types::crypto_operation(- state,- common_utils::type_name!(Self),- types::CryptoOperation::DecryptOptional(inner),- keymanager::Identifier::Merchant(item.merchant_id.clone()),- key.peek(),- )- .await- .and_then(|val| val.try_into_optionaloperation())- })- .await- .change_context(ValidationError::InvalidValue {- message: "Failed to decrypt default billing address".to_string(),- })?;-- let default_shipping_address = item- .default_shipping_address- .async_lift(|inner| async {- types::crypto_operation(- state,- common_utils::type_name!(Self),- types::CryptoOperation::DecryptOptional(inner),- keymanager::Identifier::Merchant(item.merchant_id.clone()),- key.peek(),- )- .await- .and_then(|val| val.try_into_optionaloperation())- })- .await- .change_context(ValidationError::InvalidValue {- message: "Failed to decrypt default shipping address".to_string(),- })?;-- let document_details = item- .document_details- .async_lift(|inner| async {- types::crypto_operation(- state,- common_utils::type_name!(Self),- types::CryptoOperation::DecryptOptional(inner),- keymanager::Identifier::Merchant(item.merchant_id.clone()),- key.peek(),- )- .await- .and_then(|val| val.try_into_optionaloperation())- })- .await- .change_context(ValidationError::InvalidValue {- message: "Failed to decrypt document details".to_string(),- })?;-- Ok(Self {- id: item.id,- merchant_reference_id: item.merchant_reference_id,- merchant_id: item.merchant_id,- name: encryptable_customer.name,- email: encryptable_customer.email.map(|email| {- let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(- email.clone().into_inner().switch_strategy(),- email.into_encrypted(),- );- encryptable- }),- phone: encryptable_customer.phone,- phone_country_code: item.phone_country_code,- description: item.description,- created_at: item.created_at,- metadata: item.metadata,- modified_at: item.modified_at,- connector_customer: item.connector_customer,- default_payment_method_id: item.default_payment_method_id,- updated_by: item.updated_by,- default_billing_address,- default_shipping_address,- version: item.version,- status: item.status,- tax_registration_id: encryptable_customer.tax_registration_id,- document_details,- created_by: item- .created_by- .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),- last_modified_by: item- .last_modified_by- .and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),- })- }-- async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {- let now = date_time::now();- Ok(diesel_models::customers::CustomerNew {- id: self.id.clone(),- merchant_reference_id: self.merchant_reference_id,- merchant_id: self.merchant_id,- name: self.name.map(Encryption::from),- email: self.email.map(Encryption::from),- phone: self.phone.map(Encryption::from),- description: self.description,- phone_country_code: self.phone_country_code,- metadata: self.metadata,- default_payment_method_id: None,- created_at: now,- modified_at: now,- connector_customer: self.connector_customer,- updated_by: self.updated_by,- default_billing_address: self.default_billing_address.map(Encryption::from),- default_shipping_address: self.default_shipping_address.map(Encryption::from),- version: common_types::consts::API_VERSION,- status: self.status,- tax_registration_id: self.tax_registration_id.map(Encryption::from),- document_details: self.document_details.map(Encryption::from),- created_by: self- .created_by- .as_ref()- .map(|created_by| created_by.to_string()),- last_modified_by: self.created_by.map(|created_by| created_by.to_string()), // Same as created_by on creation- customer_id: Some(self.id),- })- }-}-#[cfg(feature = "v2")]#[derive(Clone, Debug)]pub struct CustomerGeneralUpdate {@@ -634,92 +264,6 @@ pub enum CustomerUpdate {},}-#[cfg(feature = "v2")]-impl From<CustomerUpdate> for CustomerUpdateInternal {- fn from(customer_update: CustomerUpdate) -> Self {- match customer_update {- CustomerUpdate::Update(update) => {- let CustomerGeneralUpdate {- name,- email,- phone,- description,- phone_country_code,- metadata,- connector_customer,- default_billing_address,- default_shipping_address,- default_payment_method_id,- status,- tax_registration_id,- document_details,- last_modified_by,- } = *update;- Self {- name: name.map(Encryption::from),- email: email.map(Encryption::from),- phone: phone.map(Encryption::from),- description,- phone_country_code,- metadata,- connector_customer: *connector_customer,- modified_at: date_time::now(),- default_billing_address: default_billing_address.map(Encryption::from),- default_shipping_address: default_shipping_address.map(Encryption::from),- default_payment_method_id,- updated_by: None,- status,- tax_registration_id: tax_registration_id.map(Encryption::from),- document_details: document_details.map(Encryption::from),- last_modified_by,- }- }- CustomerUpdate::ConnectorCustomer {- connector_customer,- last_modified_by,- } => Self {- connector_customer,- name: None,- email: None,- phone: None,- description: None,- phone_country_code: None,- metadata: None,- modified_at: date_time::now(),- default_payment_method_id: None,- updated_by: None,- default_billing_address: None,- default_shipping_address: None,- status: None,- tax_registration_id: None,- document_details: None,- last_modified_by,- },- CustomerUpdate::UpdateDefaultPaymentMethod {- default_payment_method_id,- last_modified_by,- } => Self {- default_payment_method_id,- modified_at: date_time::now(),- name: None,- email: None,- phone: None,- description: None,- phone_country_code: None,- metadata: None,- connector_customer: None,- updated_by: None,- default_billing_address: None,- default_shipping_address: None,- status: None,- tax_registration_id: None,- document_details: None,- last_modified_by,- },- }- }-}-#[cfg(feature = "v1")]#[derive(Clone, Debug)]pub enum CustomerUpdate {@@ -746,80 +290,6 @@ pub enum CustomerUpdate {},}-#[cfg(feature = "v1")]-impl From<CustomerUpdate> for CustomerUpdateInternal {- fn from(customer_update: CustomerUpdate) -> Self {- match customer_update {- CustomerUpdate::Update {- name,- email,- phone,- description,- phone_country_code,- metadata,- connector_customer,- address_id,- tax_registration_id,- document_details,- last_modified_by,- } => Self {- name: name.map(Encryption::from),- email: email.map(Encryption::from),- phone: phone.map(Encryption::from),- description,- phone_country_code,- metadata: *metadata,- connector_customer: *connector_customer,- modified_at: date_time::now(),- address_id,- default_payment_method_id: None,- updated_by: None,- tax_registration_id: tax_registration_id.map(Encryption::from),- document_details: document_details.map(Encryption::from),- last_modified_by,- },- CustomerUpdate::ConnectorCustomer {- connector_customer,- last_modified_by,- } => Self {- connector_customer,- modified_at: date_time::now(),- name: None,- email: None,- phone: None,- description: None,- phone_country_code: None,- metadata: None,- default_payment_method_id: None,- updated_by: None,- address_id: None,- tax_registration_id: None,- document_details: None,- last_modified_by,- },- CustomerUpdate::UpdateDefaultPaymentMethod {- default_payment_method_id,- last_modified_by,- } => Self {- default_payment_method_id,- modified_at: date_time::now(),- name: None,- email: None,- phone: None,- description: None,- phone_country_code: None,- metadata: None,- connector_customer: None,- updated_by: None,- address_id: None,- tax_registration_id: None,- document_details: None,- last_modified_by,- },- }- }-}-pub struct CustomerListConstraints {pub limit: u16,pub offset: Option<u32>,@@ -839,13 +309,7 @@ impl From<CustomerListConstraints> for query::CustomerListConstraints {}#[async_trait::async_trait]-pub trait CustomerInterface-where- Customer: behaviour::Conversion<- DstType = storage_types::Customer,- NewDstType = storage_types::CustomerNew,- >,-{+pub trait CustomerInterface {type Error;#[cfg(feature = "v1")]async fn delete_customer_by_customer_id_merchant_id(@@ -888,7 +352,7 @@ where&self,customer_id: &id_type::CustomerId,merchant_id: &id_type::MerchantId,- ) -> CustomResult<storage_types::CustomerGlobalIdMigrationRow, Self::Error>;+ ) -> CustomResult<diesel_models::customers::CustomerGlobalIdMigrationRow, Self::Error>;#[cfg(feature = "v2")]async fn update_customer_global_id_for_migration(@@ -896,7 +360,7 @@ wherecustomer_id: &id_type::CustomerId,merchant_id: &id_type::MerchantId,new_id: id_type::GlobalCustomerId,- ) -> CustomResult<storage_types::CustomerGlobalIdMigrationRow, Self::Error>;+ ) -> CustomResult<diesel_models::customers::CustomerGlobalIdMigrationRow, Self::Error>;#[cfg(feature = "v1")]#[allow(clippy::too_many_arguments)]diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rsindex 52d47f2e00..2c7be8a756 100644--- a/crates/hyperswitch_domain_models/src/payment_methods.rs+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs@@ -1,25 +1,27 @@use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc};-#[cfg(feature = "v2")]-use api_models::payment_methods::PaymentMethodsData;-use api_models::{customers, payment_methods, payments};+#[cfg(feature = "v1")]+use api_models::payments;+use api_models::{customers, payment_methods};// specific imports because of using the macrouse common_enums::enums::MerchantStorageScheme;+#[cfg(feature = "v1")]+use common_utils::errors::ValidationError;#[cfg(feature = "v2")]use common_utils::{crypto::Encryptable, encryption::Encryption, types::keymanager::ToEncryptable};#[cfg(feature = "v1")]use common_utils::{crypto::Encryptable, encryption::Encryption, types::keymanager::ToEncryptable};use common_utils::{- errors::{CustomResult, ParsingError, ValidationError},- ext_traits::OptionExt,- id_type, pii, type_name,- types::{keymanager, CreatedBy},+ errors::{CustomResult, ParsingError},+ id_type, pii,+ types::CreatedBy,};pub use diesel_models::{enums as storage_enums, PaymentMethodUpdate as StoragePaymentMethodUpdate,};-use error_stack::ResultExt;-use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};+#[cfg(feature = "v1")]+use hyperswitch_masking::ExposeInterface;+use hyperswitch_masking::Secret;#[cfg(feature = "v1")]use router_env::logger;#[cfg(feature = "v1")]@@ -29,14 +31,14 @@ use rustc_hash::FxHashMap;use serde_json::Value;use time::PrimitiveDateTime;+#[cfg(feature = "v1")]+use crate::transformers::ForeignTryFrom;#[cfg(feature = "v2")]use crate::{address::Address, platform::Initiator};use crate::{mandates::{self, CommonMandateReference},merchant_key_store::MerchantKeyStore,payment_method_data as domain_payment_method_data,- transformers::ForeignTryFrom,- type_encryption::{crypto_operation, CryptoOperation},};#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]@@ -450,497 +452,6 @@ impl}}-#[cfg(feature = "v1")]-#[async_trait::async_trait]-impl super::behaviour::Conversion for PaymentMethod {- type DstType = diesel_models::payment_method::PaymentMethod;- type NewDstType = diesel_models::payment_method::PaymentMethodNew;- async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {- let (vault_type, external_vault_source) = self.vault_source_details.into();- // Note: caller must ensure customer_id is not null before calling convert as storage model requires it.- Ok(Self::DstType {- customer_id: self.customer_id.get_required_value("customer_id")?,- merchant_id: self.merchant_id,- payment_method_id: self.payment_method_id,- accepted_currency: self.accepted_currency,- scheme: self.scheme,- token: self.token,- cardholder_name: self.cardholder_name,- issuer_name: self.issuer_name,- issuer_country: self.issuer_country,- payer_country: self.payer_country,- is_stored: self.is_stored,- swift_code: self.swift_code,- direct_debit_token: self.direct_debit_token,- created_at: self.created_at,- last_modified: self.last_modified,- payment_method: self.payment_method,- payment_method_type: self.payment_method_type,- payment_method_issuer: self.payment_method_issuer,- payment_method_issuer_code: self.payment_method_issuer_code,- metadata: self.metadata,- payment_method_data: self.payment_method_data.map(|val| val.into()),- locker_id: self.locker_id,- last_used_at: self.last_used_at,- connector_mandate_details: self.connector_mandate_details,- customer_acceptance: self.customer_acceptance,- status: self.status,- network_transaction_id: self.network_transaction_id,- network_transaction_link_id: self.network_transaction_link_id,- client_secret: self.client_secret,- payment_method_billing_address: self- .payment_method_billing_address- .map(|val| val.into()),- updated_by: self.updated_by,- version: self.version,- network_token_requestor_reference_id: self.network_token_requestor_reference_id,- network_token_locker_id: self.network_token_locker_id,- network_token_payment_method_data: self- .network_token_payment_method_data- .map(|val| val.into()),- external_vault_source,- vault_type,- created_by: self.created_by.map(|created_by| created_by.to_string()),- last_modified_by: self- .last_modified_by- .map(|last_modified_by| last_modified_by.to_string()),- customer_details: self.customer_details.map(|val| val.into()),- locker_fingerprint_id: self.locker_fingerprint_id,- network_tokenization_data: self.network_tokenization_data.map(|val| val.into()),- connector_payment_method_details: self.connector_payment_method_details.clone(),- payment_method_type_v2: None,- payment_method_subtype: None,- id: None,- compatibility_updated_at: self.compatibility_updated_at,- auxiliary_fingerprint_id: None,- })- }-- async fn convert_back(- state: &keymanager::KeyManagerState,- item: Self::DstType,- key: &Secret<Vec<u8>>,- key_manager_identifier: keymanager::Identifier,- ) -> CustomResult<Self, ValidationError>- where- Self: Sized,- {- // Decrypt encrypted fields first- let data = async {- let decrypted_data = crypto_operation(- state,- type_name!(Self::DstType),- CryptoOperation::BatchDecrypt(EncryptedPaymentMethod::to_encryptable(- EncryptedPaymentMethod {- payment_method_data: item.payment_method_data,- payment_method_billing_address: item.payment_method_billing_address,- network_token_payment_method_data: item.network_token_payment_method_data,- customer_details: item.customer_details,- network_tokenization_data: item.network_tokenization_data,- },- )),- key_manager_identifier,- key.peek(),- )- .await- .and_then(|val| val.try_into_batchoperation())?;-- EncryptedPaymentMethod::from_encryptable(decrypted_data)- .change_context(common_utils::errors::CryptoError::DecodingFailed)- .attach_printable("Invalid batch operation data")- }- .await- .change_context(ValidationError::InvalidValue {- message: "Failed while decrypting payment method data".to_string(),- })?;-- let vault_source_details = PaymentMethodVaultSourceDetails::try_from((- item.vault_type,- item.external_vault_source,- ))?;- let payment_method_subtype =- item.payment_method_subtype- .and_then(|payment_method_subtype| {- if payment_method_subtype.eq_ignore_ascii_case("card") {- None- } else {- payment_method_subtype- .parse::<storage_enums::PaymentMethodType>()- .map_err(|error| {- logger::warn!(- ?error,- payment_method_subtype,- "Failed to parse payment_method_subtype compatibility field"- );- })- .ok()- }- });-- // Construct the domain type- // Storage always has customer_id, wrap in Some for domain- Ok(Self {- customer_id: Some(item.customer_id),- merchant_id: item.merchant_id,- payment_method_id: item.payment_method_id,- accepted_currency: item.accepted_currency,- scheme: item.scheme,- token: item.token,- cardholder_name: item.cardholder_name,- issuer_name: item.issuer_name,- issuer_country: item.issuer_country,- payer_country: item.payer_country,- is_stored: item.is_stored,- swift_code: item.swift_code,- direct_debit_token: item.direct_debit_token,- created_at: item.created_at,- last_modified: item.last_modified,- payment_method: item.payment_method.or(item.payment_method_type_v2),- payment_method_type: item.payment_method_type.or(payment_method_subtype),- payment_method_issuer: item.payment_method_issuer,- payment_method_issuer_code: item.payment_method_issuer_code,- metadata: item.metadata,- payment_method_data: data.payment_method_data,- locker_id: item.locker_id,- last_used_at: item.last_used_at,- connector_mandate_details: item.connector_mandate_details,- customer_acceptance: item.customer_acceptance,- status: item.status,- network_transaction_id: item.network_transaction_id,- network_transaction_link_id: item.network_transaction_link_id,- client_secret: item.client_secret,- payment_method_billing_address: data.payment_method_billing_address,- updated_by: item.updated_by,- version: item.version,- network_token_requestor_reference_id: item.network_token_requestor_reference_id,- network_token_locker_id: item.network_token_locker_id,- network_token_payment_method_data: data.network_token_payment_method_data,- vault_source_details,- created_by: item- .created_by- .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),- last_modified_by: item- .last_modified_by- .and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),- customer_details: data.customer_details,- locker_fingerprint_id: item.locker_fingerprint_id,- network_tokenization_data: data.network_tokenization_data,- storage_type: None,- compatibility_updated_at: item.compatibility_updated_at,- connector_payment_method_details: item.connector_payment_method_details,- })- }-- async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {- let (vault_type, external_vault_source) = self.vault_source_details.into();- // Note: caller must ensure customer_id is not null before calling convert as storage model requires it.- Ok(Self::NewDstType {- customer_id: self.customer_id.get_required_value("customer_id")?,- merchant_id: self.merchant_id,- payment_method_id: self.payment_method_id,- accepted_currency: self.accepted_currency,- scheme: self.scheme,- token: self.token,- cardholder_name: self.cardholder_name,- issuer_name: self.issuer_name,- issuer_country: self.issuer_country,- payer_country: self.payer_country,- is_stored: self.is_stored,- swift_code: self.swift_code,- direct_debit_token: self.direct_debit_token,- created_at: self.created_at,- last_modified: self.last_modified,- payment_method: self.payment_method,- payment_method_type: self.payment_method_type,- payment_method_issuer: self.payment_method_issuer,- payment_method_issuer_code: self.payment_method_issuer_code,- metadata: self.metadata,- payment_method_data: self.payment_method_data.map(|val| val.into()),- locker_id: self.locker_id,- last_used_at: self.last_used_at,- connector_mandate_details: self.connector_mandate_details,- customer_acceptance: self.customer_acceptance,- status: self.status,- network_transaction_id: self.network_transaction_id,- network_transaction_link_id: self.network_transaction_link_id,- client_secret: self.client_secret,- payment_method_billing_address: self- .payment_method_billing_address- .map(|val| val.into()),- updated_by: self.updated_by,- version: self.version,- network_token_requestor_reference_id: self.network_token_requestor_reference_id,- network_token_locker_id: self.network_token_locker_id,- network_token_payment_method_data: self- .network_token_payment_method_data- .map(|val| val.into()),- external_vault_source,- vault_type,- created_by: self.created_by.map(|created_by| created_by.to_string()),- last_modified_by: self- .last_modified_by- .map(|last_modified_by| last_modified_by.to_string()),- customer_details: self.customer_details.map(|val| val.into()),- locker_fingerprint_id: self.locker_fingerprint_id,- network_tokenization_data: self.network_tokenization_data.map(|val| val.into()),- connector_payment_method_details: self.connector_payment_method_details.clone(),- id: None,- compatibility_updated_at: self.compatibility_updated_at,- auxiliary_fingerprint_id: None,- })- }-}--#[cfg(feature = "v2")]-#[async_trait::async_trait]-impl super::behaviour::Conversion for PaymentMethod {- type DstType = diesel_models::payment_method::PaymentMethod;- type NewDstType = diesel_models::payment_method::PaymentMethodNew;- async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {- let payment_method_id = self.id.get_string_repr().to_owned();- Ok(Self::DstType {- customer_id: self.customer_id,- merchant_id: self.merchant_id,- id: self.id,- payment_method_id: Some(payment_method_id),- created_at: self.created_at,- last_modified: self.last_modified,- payment_method: None,- payment_method_type: None,- payment_method_type_v2: self.payment_method_type,- payment_method_subtype: self.payment_method_subtype,- payment_method_data: self.payment_method_data.map(|val| val.into()),- locker_id: self.locker_id.map(|id| id.get_string_repr().clone()),- last_used_at: self.last_used_at,- connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()),- customer_acceptance: self.customer_acceptance,- status: self.status,- network_transaction_id: self.network_transaction_id.map(Secret::new),- network_transaction_link_id: self.network_transaction_link_id.map(Secret::new),- client_secret: self.client_secret,- payment_method_billing_address: self- .payment_method_billing_address- .map(|val| val.into()),- updated_by: self.updated_by,- locker_fingerprint_id: self.locker_fingerprint_id,- version: self.version,- network_token_requestor_reference_id: self.network_token_requestor_reference_id,- network_token_locker_id: self.network_token_locker_id,- network_token_payment_method_data: self- .network_token_payment_method_data- .map(|val| val.into()),- external_vault_source: self.external_vault_source,- external_vault_token_data: self.external_vault_token_data.map(|val| val.into()),- vault_type: self.vault_type,- created_by: self.created_by.map(|created_by| created_by.to_string()),- last_modified_by: self- .last_modified_by- .map(|last_modified_by| last_modified_by.to_string()),- customer_details: self.customer_details.map(|val| val.into()),- network_tokenization_data: self.network_tokenization_data.map(|val| val.into()),- auxiliary_fingerprint_id: self.auxiliary_fingerprint_id,- compatibility_updated_at: self.compatibility_updated_at,- connector_payment_method_details: None,- })- }-- async fn convert_back(- state: &keymanager::KeyManagerState,- storage_model: Self::DstType,- key: &Secret<Vec<u8>>,- key_manager_identifier: keymanager::Identifier,- ) -> CustomResult<Self, ValidationError>- where- Self: Sized,- {- use common_utils::ext_traits::ValueExt;-- async {- let decrypted_data = crypto_operation(- state,- type_name!(Self::DstType),- CryptoOperation::BatchDecrypt(EncryptedPaymentMethod::to_encryptable(- EncryptedPaymentMethod {- payment_method_data: storage_model.payment_method_data,- payment_method_billing_address: storage_model- .payment_method_billing_address,- network_token_payment_method_data: storage_model- .network_token_payment_method_data,- external_vault_token_data: storage_model.external_vault_token_data,- customer_details: storage_model.customer_details,- network_tokenization_data: storage_model.network_tokenization_data,- },- )),- key_manager_identifier,- key.peek(),- )- .await- .and_then(|val| val.try_into_batchoperation())?;-- let data = EncryptedPaymentMethod::from_encryptable(decrypted_data)- .change_context(common_utils::errors::CryptoError::DecodingFailed)- .attach_printable("Invalid batch operation data")?;-- let payment_method_billing_address = data- .payment_method_billing_address- .map(|billing| {- billing.deserialize_inner_value(|value| value.parse_value("Address"))- })- .transpose()- .change_context(common_utils::errors::CryptoError::DecodingFailed)- .attach_printable("Error while deserializing Address")?;-- let payment_method_data = data- .payment_method_data- .map(|payment_method_data| {- payment_method_data- .deserialize_inner_value(|value| value.parse_value("Payment Method Data"))- })- .transpose()- .change_context(common_utils::errors::CryptoError::DecodingFailed)- .attach_printable("Error while deserializing Payment Method Data")?;-- let network_token_payment_method_data = data- .network_token_payment_method_data- .map(|network_token_payment_method_data| {- network_token_payment_method_data.deserialize_inner_value(|value| {- value.parse_value("Network token Payment Method Data")- })- })- .transpose()- .change_context(common_utils::errors::CryptoError::DecodingFailed)- .attach_printable("Error while deserializing Network token Payment Method Data")?;-- let customer_details = data- .customer_details- .map(|customer_details| {- customer_details.deserialize_inner_value(|value| {- value.parse_value("Payment Method Customer Details")- })- })- .transpose()- .change_context(common_utils::errors::CryptoError::DecodingFailed)- .attach_printable("Error while deserializing Payment Method Customer Details")?;-- let external_vault_token_data = data- .external_vault_token_data- .map(|external_vault_token_data| {- external_vault_token_data.deserialize_inner_value(|value| {- value.parse_value("External Vault Token Data")- })- })- .transpose()- .change_context(common_utils::errors::CryptoError::DecodingFailed)- .attach_printable("Error while deserializing External Vault Token Data")?;-- let network_tokenization_data = data- .network_tokenization_data- .map(|tokenization_data| {- tokenization_data.deserialize_inner_value(|value| {- value.parse_value("Network Tokenization Data")- })- })- .transpose()- .change_context(common_utils::errors::CryptoError::DecodingFailed)- .attach_printable("Error while deserializing Network Tokenization Data")?;-- Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {- customer_id: storage_model.customer_id,- merchant_id: storage_model.merchant_id,- id: storage_model.id,- created_at: storage_model.created_at,- last_modified: storage_model.last_modified,- payment_method_type: storage_model.payment_method_type_v2,- payment_method_subtype: storage_model.payment_method_subtype,- payment_method_data,- locker_id: storage_model.locker_id.map(VaultId::generate),- last_used_at: storage_model.last_used_at,- connector_mandate_details: storage_model.connector_mandate_details.map(From::from),- customer_acceptance: storage_model.customer_acceptance,- status: storage_model.status,- network_transaction_id: storage_model- .network_transaction_id- .map(ExposeInterface::expose),- network_transaction_link_id: storage_model- .network_transaction_link_id- .map(ExposeInterface::expose),- client_secret: storage_model.client_secret,- payment_method_billing_address,- updated_by: storage_model.updated_by,- locker_fingerprint_id: storage_model.locker_fingerprint_id,- version: storage_model.version,- network_token_requestor_reference_id: storage_model- .network_token_requestor_reference_id,- network_token_locker_id: storage_model.network_token_locker_id,- network_token_payment_method_data,- external_vault_source: storage_model.external_vault_source,- external_vault_token_data,- vault_type: storage_model.vault_type,- created_by: storage_model- .created_by- .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),- last_modified_by: storage_model- .last_modified_by- .and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),- customer_details,- network_tokenization_data,- auxiliary_fingerprint_id: storage_model.auxiliary_fingerprint_id,- compatibility_updated_at: storage_model.compatibility_updated_at,- })- }- .await- .change_context(ValidationError::InvalidValue {- message: "Failed while decrypting payment method data".to_string(),- })- }-- async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {- let payment_method_id = self.id.get_string_repr().to_owned();- Ok(Self::NewDstType {- customer_id: self.customer_id,- merchant_id: self.merchant_id,- id: self.id,- payment_method_id: Some(payment_method_id),- created_at: self.created_at,- last_modified: self.last_modified,- payment_method: None,- payment_method_type: None,- payment_method_type_v2: self.payment_method_type,- payment_method_subtype: self.payment_method_subtype,- payment_method_data: self.payment_method_data.map(|val| val.into()),- locker_id: self.locker_id.map(|id| id.get_string_repr().clone()),- last_used_at: self.last_used_at,- connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()),- customer_acceptance: self.customer_acceptance,- status: self.status,- network_transaction_id: self.network_transaction_id,- network_transaction_link_id: self.network_transaction_link_id,- client_secret: self.client_secret,- payment_method_billing_address: self- .payment_method_billing_address- .map(|val| val.into()),- updated_by: self.updated_by,- locker_fingerprint_id: self.locker_fingerprint_id,- version: self.version,- network_token_requestor_reference_id: self.network_token_requestor_reference_id,- network_token_locker_id: self.network_token_locker_id,- network_token_payment_method_data: self- .network_token_payment_method_data- .map(|val| val.into()),- external_vault_token_data: self.external_vault_token_data.map(|val| val.into()),- vault_type: self.vault_type,- created_by: self.created_by.map(|created_by| created_by.to_string()),- last_modified_by: self- .last_modified_by- .map(|last_modified_by| last_modified_by.to_string()),- customer_details: self.customer_details.map(|val| val.into()),- auxiliary_fingerprint_id: self.auxiliary_fingerprint_id,- compatibility_updated_at: self.compatibility_updated_at,- external_vault_source: self.external_vault_source,- })- }-}-#[cfg(feature = "v2")]#[derive(Clone, Debug, router_derive::ToEncryption)]pub struct PaymentMethodSession {@@ -961,109 +472,6 @@ pub struct PaymentMethodSession {pub keep_alive: bool,}-#[cfg(feature = "v2")]-#[async_trait::async_trait]-impl super::behaviour::Conversion for PaymentMethodSession {- type DstType = diesel_models::payment_methods_session::PaymentMethodSession;- type NewDstType = diesel_models::payment_methods_session::PaymentMethodSession;- async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {- Ok(Self::DstType {- id: self.id,- customer_id: self.customer_id,- billing: self.billing.map(|val| val.into()),- psp_tokenization: self.psp_tokenization,- network_tokenization: self.network_tokenization,- tokenization_data: self.tokenization_data,- expires_at: self.expires_at,- associated_payment_methods: self.associated_payment_methods,- associated_payment: self.associated_payment,- return_url: self.return_url,- associated_token_id: self.associated_token_id,- storage_type: self.storage_type,- keep_alive: self.keep_alive,- })- }-- async fn convert_back(- state: &keymanager::KeyManagerState,- storage_model: Self::DstType,- key: &Secret<Vec<u8>>,- key_manager_identifier: keymanager::Identifier,- ) -> CustomResult<Self, ValidationError>- where- Self: Sized,- {- use common_utils::ext_traits::ValueExt;-- async {- let decrypted_data = crypto_operation(- state,- type_name!(Self::DstType),- CryptoOperation::BatchDecrypt(EncryptedPaymentMethodSession::to_encryptable(- EncryptedPaymentMethodSession {- billing: storage_model.billing,- },- )),- key_manager_identifier,- key.peek(),- )- .await- .and_then(|val| val.try_into_batchoperation())?;-- let data = EncryptedPaymentMethodSession::from_encryptable(decrypted_data)- .change_context(common_utils::errors::CryptoError::DecodingFailed)- .attach_printable("Invalid batch operation data")?;-- let billing = data- .billing- .map(|billing| {- billing.deserialize_inner_value(|value| value.parse_value("Address"))- })- .transpose()- .change_context(common_utils::errors::CryptoError::DecodingFailed)- .attach_printable("Error while deserializing Address")?;-- Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {- id: storage_model.id,- customer_id: storage_model.customer_id,- billing,- psp_tokenization: storage_model.psp_tokenization,- network_tokenization: storage_model.network_tokenization,- tokenization_data: storage_model.tokenization_data,- expires_at: storage_model.expires_at,- associated_payment_methods: storage_model.associated_payment_methods,- associated_payment: storage_model.associated_payment,- return_url: storage_model.return_url,- associated_token_id: storage_model.associated_token_id,- storage_type: storage_model.storage_type,- keep_alive: storage_model.keep_alive,- })- }- .await- .change_context(ValidationError::InvalidValue {- message: "Failed while decrypting payment method data".to_string(),- })- }-- async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {- Ok(Self::NewDstType {- id: self.id,- customer_id: self.customer_id,- billing: self.billing.map(|val| val.into()),- psp_tokenization: self.psp_tokenization,- network_tokenization: self.network_tokenization,- tokenization_data: self.tokenization_data,- expires_at: self.expires_at,- associated_payment_methods: self.associated_payment_methods,- associated_payment: self.associated_payment,- return_url: self.return_url,- associated_token_id: self.associated_token_id,- storage_type: self.storage_type,- keep_alive: self.keep_alive,- })- }-}-#[cfg(feature = "v1")]#[derive(Clone, Debug)]pub struct VaultCardData {diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rsindex d0de125fce..cfbddcf433 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs@@ -1,3 +1,4 @@+#[cfg(feature = "v1")]use std::str::FromStr;#[cfg(feature = "v1")]@@ -15,24 +16,24 @@ use common_types::primitive_wrappers::{};#[cfg(feature = "v2")]use common_utils::ext_traits::Encode;+#[cfg(feature = "v1")]+use common_utils::types::{+ keymanager::{self, KeyManagerState},+ ConnectorTransactionIdTrait,+};use common_utils::{crypto::Encryptable,encryption::Encryption,errors::{CustomResult, ValidationError},ext_traits::{OptionExt, ValueExt},id_type, pii,- types::{- keymanager::{self, KeyManagerState, ToEncryptable},- ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy, MinorUnit,- },+ types::{keymanager::ToEncryptable, ConnectorTransactionId, CreatedBy, MinorUnit},};#[cfg(feature = "v1")]use diesel_models::{ConnectorMandateReferenceId, ErrorDetails as DieselErrorDetails, NetworkDetails,- PaymentAttemptUpdate as DieselPaymentAttemptUpdate,-};-use diesel_models::{PaymentAttempt as DieselPaymentAttempt, PaymentAttemptNew as DieselPaymentAttemptNew,+ PaymentAttemptUpdate as DieselPaymentAttemptUpdate,};#[cfg(feature = "v2")]use diesel_models::{@@ -60,17 +61,14 @@ use crate::{address::Address, consts, payment_method_data::PaymentMethodData, platform,router_response_types,};-use crate::{- behaviour, errors,- merchant_key_store::MerchantKeyStore,- type_encryption::{crypto_operation, CryptoOperation},- ForeignIDRef,-};#[cfg(feature = "v1")]use crate::{+ behaviour,mandates::{MandateDataType, MandateDetails, MandateTransactionType},router_request_types,+ type_encryption::{crypto_operation, CryptoOperation},};+use crate::{errors, merchant_key_store::MerchantKeyStore, ForeignIDRef};#[async_trait::async_trait]pub trait PaymentAttemptInterface {@@ -3301,504 +3299,6 @@ impl behaviour::Conversion for PaymentAttempt {}}-#[cfg(feature = "v2")]-#[async_trait::async_trait]-impl behaviour::Conversion for PaymentAttempt {- type DstType = DieselPaymentAttempt;- type NewDstType = DieselPaymentAttemptNew;-- async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {- use common_utils::encryption::Encryption;-- let card_network = self- .payment_method_data- .as_ref()- .and_then(|data| data.peek().as_object())- .and_then(|card| card.get("card"))- .and_then(|data| data.as_object())- .and_then(|card| card.get("card_network"))- .and_then(|network| network.as_str())- .map(|network| network.to_string());-- let Self {- payment_id,- merchant_id,- attempts_group_id,- status,- error,- amount_details,- authentication_type,- created_at,- modified_at,- last_synced,- cancellation_reason,- browser_info,- payment_token,- connector_metadata,- payment_experience,- payment_method_data,- routing_result,- preprocessing_step_id,- multiple_capture_count,- connector_response_reference_id,- updated_by,- redirection_data,- encoded_data,- merchant_connector_id,- external_three_ds_authentication_attempted,- external_threeds_authentication_type,- authentication_connector,- authentication_id,- fingerprint_id,- client_source,- client_version,- customer_acceptance,- profile_id,- organization_id,- payment_method_type,- connector_payment_id,- payment_method_subtype,- authentication_applied,- external_reference_id,- id,- payment_method_id,- payment_method_billing_address,- connector,- connector_token_details,- card_discovery,- charges,- feature_metadata,- processor_merchant_id,- created_by,- connector_request_reference_id,- network_transaction_id,- network_transaction_link_id,- authorized_amount,- external_surcharge_details,- applied_offer_details,- } = self;-- let AttemptAmountDetails {- net_amount,- tax_on_surcharge,- surcharge_amount,- order_tax_amount,- shipping_cost,- amount_capturable,- amount_to_capture,- amount_captured,- } = amount_details;-- let (connector_payment_id, connector_payment_data) = connector_payment_id- .map(ConnectorTransactionId::form_id_and_data)- .map(|(txn_id, txn_data)| (Some(txn_id), txn_data))- .unwrap_or((None, None));- let feature_metadata = feature_metadata.as_ref().map(From::from);-- Ok(DieselPaymentAttempt {- payment_id,- merchant_id,- id,- status,- error_message: error.as_ref().map(|details| details.message.clone()),- payment_method_id,- payment_method_type_v2: payment_method_type,- connector_payment_id,- authentication_type,- created_at,- modified_at,- last_synced,- cancellation_reason,- amount_to_capture,- browser_info,- error_code: error.as_ref().map(|details| details.code.clone()),- payment_token,- connector_metadata,- payment_experience,- payment_method_subtype,- payment_method_data,- preprocessing_step_id,- error_reason: error.as_ref().and_then(|details| details.reason.clone()),- multiple_capture_count,- connector_response_reference_id,- amount_capturable,- updated_by,- merchant_connector_id,- redirection_data: redirection_data.map(From::from),- encoded_data,- unified_code: error- .as_ref()- .and_then(|details| details.unified_code.clone()),- unified_message: error- .as_ref()- .and_then(|details| details.unified_message.clone()),- net_amount,- external_three_ds_authentication_attempted,- external_threeds_authentication_type,- authentication_connector,- authentication_id,- fingerprint_id,- client_source,- client_version,- customer_acceptance,- profile_id,- organization_id,- card_network,- order_tax_amount,- shipping_cost,- routing_result,- authentication_applied,- external_reference_id,- connector,- surcharge_amount,- tax_on_surcharge,- payment_method_billing_address: payment_method_billing_address.map(Encryption::from),- connector_payment_data,- connector_token_details,- card_discovery,- request_extended_authorization: None,- extended_authorization_applied: None,- extended_authorization_last_applied_at: None,- capture_before: None,- charges,- feature_metadata,- network_advice_code: error- .as_ref()- .and_then(|details| details.network_advice_code.clone()),- network_decline_code: error- .as_ref()- .and_then(|details| details.network_decline_code.clone()),- network_error_message: error- .as_ref()- .and_then(|details| details.network_error_message.clone()),- processor_merchant_id: Some(processor_merchant_id),- created_by: created_by.map(|created_by| created_by.to_string()),- connector_request_reference_id,- network_transaction_id,- network_transaction_link_id,- is_overcapture_enabled: None,- network_details: None,- attempts_group_id,- is_stored_credential: None,- authorized_amount,- tokenization: None,- amount_captured,- encrypted_payment_method_data: None,- error_details: None,- retry_type: None,- installment_data: None,- external_surcharge_details: None,- applied_offer_details,- sender_payment_instrument_id: None,- })- }-- async fn convert_back(- state: &KeyManagerState,- storage_model: Self::DstType,- key: &Secret<Vec<u8>>,- key_manager_identifier: keymanager::Identifier,- ) -> CustomResult<Self, ValidationError>- where- Self: Sized,- {- async {- let connector_payment_id = storage_model- .get_optional_connector_transaction_id()- .cloned();-- let decrypted_data = crypto_operation(- state,- common_utils::type_name!(Self::DstType),- CryptoOperation::BatchDecrypt(EncryptedPaymentAttempt::to_encryptable(- EncryptedPaymentAttempt {- payment_method_billing_address: storage_model- .payment_method_billing_address,- },- )),- key_manager_identifier,- key.peek(),- )- .await- .and_then(|val| val.try_into_batchoperation())?;-- let decrypted_data = EncryptedPaymentAttempt::from_encryptable(decrypted_data)- .change_context(common_utils::errors::CryptoError::DecodingFailed)- .attach_printable("Invalid batch operation data")?;-- let payment_method_billing_address = decrypted_data- .payment_method_billing_address- .map(|billing| {- billing.deserialize_inner_value(|value| value.parse_value("Address"))- })- .transpose()- .change_context(common_utils::errors::CryptoError::DecodingFailed)- .attach_printable("Error while deserializing Address")?;-- let amount_details = AttemptAmountDetails {- net_amount: storage_model.net_amount,- tax_on_surcharge: storage_model.tax_on_surcharge,- surcharge_amount: storage_model.surcharge_amount,- order_tax_amount: storage_model.order_tax_amount,- shipping_cost: storage_model.shipping_cost,- amount_capturable: storage_model.amount_capturable,- amount_to_capture: storage_model.amount_to_capture,- amount_captured: storage_model.amount_captured,- };-- let error = storage_model- .error_code- .zip(storage_model.error_message)- .map(|(error_code, error_message)| ErrorDetails {- code: error_code,- message: error_message,- reason: storage_model.error_reason,- unified_code: storage_model.unified_code,- unified_message: storage_model.unified_message,- network_advice_code: storage_model.network_advice_code,- network_decline_code: storage_model.network_decline_code,- network_error_message: storage_model.network_error_message,- });-- Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {- payment_id: storage_model.payment_id,- merchant_id: storage_model.merchant_id.clone(),- attempts_group_id: storage_model.attempts_group_id,- id: storage_model.id,- status: storage_model.status,- amount_details,- error,- payment_method_id: storage_model.payment_method_id,- payment_method_type: storage_model.payment_method_type_v2,- connector_payment_id,- authentication_type: storage_model.authentication_type,- created_at: storage_model.created_at,- modified_at: storage_model.modified_at,- last_synced: storage_model.last_synced,- cancellation_reason: storage_model.cancellation_reason,- browser_info: storage_model.browser_info,- payment_token: storage_model.payment_token,- connector_metadata: storage_model.connector_metadata,- payment_experience: storage_model.payment_experience,- payment_method_data: storage_model.payment_method_data,- routing_result: storage_model.routing_result,- preprocessing_step_id: storage_model.preprocessing_step_id,- multiple_capture_count: storage_model.multiple_capture_count,- connector_response_reference_id: storage_model.connector_response_reference_id,- updated_by: storage_model.updated_by,- redirection_data: storage_model.redirection_data.map(From::from),- encoded_data: storage_model.encoded_data,- merchant_connector_id: storage_model.merchant_connector_id,- external_three_ds_authentication_attempted: storage_model- .external_three_ds_authentication_attempted,- external_threeds_authentication_type: storage_model- .external_threeds_authentication_type,- authentication_connector: storage_model.authentication_connector,- authentication_id: storage_model.authentication_id,- fingerprint_id: storage_model.fingerprint_id,- charges: storage_model.charges,- client_source: storage_model.client_source,- client_version: storage_model.client_version,- customer_acceptance: storage_model.customer_acceptance,- profile_id: storage_model.profile_id,- organization_id: storage_model.organization_id,- payment_method_subtype: storage_model.payment_method_subtype,- authentication_applied: storage_model.authentication_applied,- external_reference_id: storage_model.external_reference_id,- external_surcharge_details: storage_model.external_surcharge_details,- applied_offer_details: storage_model.applied_offer_details,- connector: storage_model.connector,- payment_method_billing_address,- connector_token_details: storage_model.connector_token_details,- card_discovery: storage_model.card_discovery,- feature_metadata: storage_model.feature_metadata.map(From::from),- processor_merchant_id: storage_model- .processor_merchant_id- .unwrap_or(storage_model.merchant_id),- created_by: storage_model- .created_by- .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),- connector_request_reference_id: storage_model.connector_request_reference_id,- network_transaction_id: storage_model.network_transaction_id,- network_transaction_link_id: storage_model.network_transaction_link_id,- authorized_amount: storage_model.authorized_amount,- })- }- .await- .change_context(ValidationError::InvalidValue {- message: "Failed while decrypting payment attempt".to_string(),- })- }-- async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {- use common_utils::encryption::Encryption;- let Self {- payment_id,- merchant_id,- attempts_group_id,- status,- error,- amount_details,- authentication_type,- created_at,- modified_at,- last_synced,- cancellation_reason,- browser_info,- payment_token,- connector_metadata,- payment_experience,- payment_method_data,- routing_result: _,- preprocessing_step_id,- multiple_capture_count,- connector_response_reference_id,- updated_by,- redirection_data,- encoded_data,- merchant_connector_id,- external_three_ds_authentication_attempted,- external_threeds_authentication_type,- authentication_connector,- authentication_id,- fingerprint_id,- client_source,- client_version,- customer_acceptance,- profile_id,- organization_id,- payment_method_type,- connector_payment_id,- payment_method_subtype,- authentication_applied: _,- external_reference_id: _,- id,- payment_method_id,- payment_method_billing_address,- connector,- connector_token_details,- card_discovery,- charges,- feature_metadata,- processor_merchant_id,- created_by,- connector_request_reference_id,- network_transaction_id,- network_transaction_link_id,- authorized_amount,- external_surcharge_details: _,- applied_offer_details: _,- } = self;-- let card_network = payment_method_data- .as_ref()- .and_then(|data| data.peek().as_object())- .and_then(|card| card.get("card"))- .and_then(|data| data.as_object())- .and_then(|card| card.get("card_network"))- .and_then(|network| network.as_str())- .map(|network| network.to_string());-- let error_details = error;-- Ok(DieselPaymentAttemptNew {- payment_id,- merchant_id,- status,- network_transaction_id,- network_transaction_link_id,- error_message: error_details- .as_ref()- .map(|details| details.message.clone()),- surcharge_amount: amount_details.surcharge_amount,- tax_on_surcharge: amount_details.tax_on_surcharge,- payment_method_id,- authentication_type,- created_at,- modified_at,- last_synced,- cancellation_reason,- browser_info,- payment_token,- error_code: error_details.as_ref().map(|details| details.code.clone()),- connector_metadata,- payment_experience,- payment_method_data,- preprocessing_step_id,- error_reason: error_details- .as_ref()- .and_then(|details| details.reason.clone()),- connector_response_reference_id,- multiple_capture_count,- amount_capturable: amount_details.amount_capturable,- updated_by,- merchant_connector_id,- redirection_data: redirection_data.map(From::from),- encoded_data,- unified_code: error_details- .as_ref()- .and_then(|details| details.unified_code.clone()),- unified_message: error_details- .as_ref()- .and_then(|details| details.unified_message.clone()),- net_amount: amount_details.net_amount,- external_three_ds_authentication_attempted,- external_threeds_authentication_type,- authentication_connector,- authentication_id,- fingerprint_id,- client_source,- client_version,- customer_acceptance,- profile_id,- organization_id,- card_network,- order_tax_amount: amount_details.order_tax_amount,- shipping_cost: amount_details.shipping_cost,- amount_to_capture: amount_details.amount_to_capture,- payment_method_billing_address: payment_method_billing_address.map(Encryption::from),- payment_method_subtype,- connector_payment_id: connector_payment_id- .as_ref()- .map(|txn_id| ConnectorTransactionId::TxnId(txn_id.clone())),- payment_method_type_v2: payment_method_type,- id,- charges,- connector_token_details,- card_discovery,- extended_authorization_applied: None,- request_extended_authorization: None,- extended_authorization_last_applied_at: None,- capture_before: None,- feature_metadata: feature_metadata.as_ref().map(From::from),- connector,- network_advice_code: error_details- .as_ref()- .and_then(|details| details.network_advice_code.clone()),- network_decline_code: error_details- .as_ref()- .and_then(|details| details.network_decline_code.clone()),- network_error_message: error_details- .as_ref()- .and_then(|details| details.network_error_message.clone()),- processor_merchant_id: Some(processor_merchant_id),- created_by: created_by.map(|created_by| created_by.to_string()),- external_surcharge_details: None,- applied_offer_details: None,- connector_request_reference_id,- network_details: None,- tokenization: None,- attempts_group_id,- is_stored_credential: None,- authorized_amount,- amount_captured: amount_details.amount_captured,- encrypted_payment_method_data: None,- error_details: None,- retry_type: None,- })- }-}-#[cfg(feature = "v2")]impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal {fn from(update: PaymentAttemptUpdate) -> Self {diff --git a/crates/payment_methods/src/controller.rs b/crates/payment_methods/src/controller.rsindex d298801b59..08a260b0cf 100644--- a/crates/payment_methods/src/controller.rs+++ b/crates/payment_methods/src/controller.rs@@ -16,7 +16,7 @@ use hyperswitch_masking::{PeekInterface, Secret};#[cfg(feature = "v1")]use scheduler::errors as sch_errors;use serde::{Deserialize, Serialize};-use storage_impl::{errors as storage_errors, payment_method};+use storage_impl::errors as storage_errors;use crate::core::errors;@@ -372,7 +372,7 @@ wherelet encrypted_data = type_encryption::crypto_operation(key_manager_state,- type_name!(payment_method::PaymentMethod),+ type_name!(payment_methods::PaymentMethod),type_encryption::CryptoOperation::Encrypt(secret_data),identifier.clone(),key,diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex c4b0cf12a6..53fd459ef1 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -53,8 +53,6 @@ use futures::TryStreamExt;#[cfg(feature = "v1")]use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData};#[cfg(feature = "v2")]-use hyperswitch_domain_models::behaviour::Conversion;-#[cfg(feature = "v2")]use hyperswitch_domain_models::payment_methods::PaymentMethodUpdate as DomainPaymentMethodUpdate;use hyperswitch_domain_models::{payment_method_data::{BankDebitData, BankRedirectData},@@ -69,6 +67,8 @@ use hyperswitch_interfaces::connector_integration_interface::RouterDataConversiouse hyperswitch_masking::ExposeInterface;use hyperswitch_masking::{PeekInterface, Secret};use router_env::{instrument, tracing};+#[cfg(feature = "v2")]+use storage_impl::behaviour::Conversion;use time::Duration;#[cfg(feature = "v2")]diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex 6dc75b8813..d9cb92cf5b 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -48,8 +48,6 @@ use time::Duration;#[cfg(all(feature = "olap", feature = "payouts"))]use crate::consts as payout_consts;#[cfg(feature = "olap")]-use crate::types::domain::behaviour::Conversion;-#[cfg(feature = "olap")]use crate::types::PayoutActionData;use crate::{core::{@@ -996,7 +994,7 @@ pub async fn payouts_filtered_list_core(join_all(list.into_iter().map(|(p, pa, customer, address)| async {let customer: Option<domain::Customer> = customer.async_and_then(|cust| async {- domain::Customer::convert_back(+ <domain::Customer as storage_impl::behaviour::Conversion>::convert_back(&(&state).into(),cust,&(platform.get_processor().get_key_store().clone()).key,@@ -1018,7 +1016,7 @@ pub async fn payouts_filtered_list_core(let payout_addr: Option<payment_enums::Address> = address.async_and_then(|addr| async {- domain::Address::convert_back(+ <domain::Address as domain::behaviour::Conversion>::convert_back(&(&state).into(),addr,&(platform.get_processor().get_key_store().clone()).key,diff --git a/crates/router/src/core/proxy/utils.rs b/crates/router/src/core/proxy/utils.rsindex cba4decdc4..bff7a5e2a7 100644--- a/crates/router/src/core/proxy/utils.rs+++ b/crates/router/src/core/proxy/utils.rs@@ -6,9 +6,10 @@ use common_utils::{id_type,};use error_stack::ResultExt;-use hyperswitch_domain_models::{behaviour::Conversion, payment_methods};+use hyperswitch_domain_models::payment_methods;use hyperswitch_masking::{Mask, PeekInterface};use serde_json::Value;+use storage_impl::behaviour::Conversion;use x509_parser::nom::{bytes::complete::{tag, take_while1},character::complete::{char, multispace0},diff --git a/crates/router/src/db/payment_method_session.rs b/crates/router/src/db/payment_method_session.rsindex 8b30cf3ad4..1aebea49fd 100644--- a/crates/router/src/db/payment_method_session.rs+++ b/crates/router/src/db/payment_method_session.rs@@ -42,9 +42,11 @@ impl PaymentMethodsSessionInterface for crate::services::Store {}#[cfg(feature = "v2")]mod storage {use error_stack::ResultExt;- use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion};use router_env::{instrument, tracing};- use storage_impl::redis::kv_store::RedisConnInterface;+ use storage_impl::{+ behaviour::{Conversion, ReverseConversion},+ redis::kv_store::RedisConnInterface,+ };use super::PaymentMethodsSessionInterface;use crate::{diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rsindex f8594b7b7d..b249f52db3 100644--- a/crates/storage_impl/src/customers.rs+++ b/crates/storage_impl/src/customers.rs@@ -1,16 +1,16 @@use common_utils::{id_type, pii};+#[cfg(feature = "v2")]use diesel_models::customers;use error_stack::ResultExt;use futures::future::try_join_all;use hyperswitch_domain_models::{- behaviour::{Conversion, ReverseConversion},- customer as domain,- merchant_key_store::MerchantKeyStore,+ customer as domain, merchant_key_store::MerchantKeyStore, type_encryption::AsyncLift,};use hyperswitch_masking::PeekInterface;use router_env::{instrument, tracing};use crate::{+ behaviour::{Conversion, ForeignFrom, ForeignInto, ReverseConversion},diesel_error_to_data_error,errors::StorageError,kv_router_store,@@ -25,7 +25,7 @@ use crate::{utils::try_redis_get_else_try_database_get,};-impl KvStorePartition for customers::Customer {}+impl KvStorePartition for diesel_models::Customer {}#[cfg(feature = "v2")]mod label {@@ -70,7 +70,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStlet maybe_result = Box::pin(self.find_optional_resource_by_id(key_store,storage_scheme,- customers::Customer::find_optional_by_customer_id_merchant_id(+ diesel_models::Customer::find_optional_by_customer_id_merchant_id(&conn,customer_id,merchant_id,@@ -105,7 +105,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStBox::pin(self.find_optional_resource_by_id(key_store,storage_scheme,- customers::Customer::find_optional_by_customer_id_merchant_id(+ diesel_models::Customer::find_optional_by_customer_id_merchant_id(&conn,customer_id,merchant_id,@@ -133,7 +133,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStlet maybe_result = Box::pin(self.find_optional_resource_by_id(key_store,storage_scheme,- customers::Customer::find_optional_by_merchant_id_merchant_reference_id(+ diesel_models::Customer::find_optional_by_merchant_id_merchant_reference_id(&conn,merchant_reference_id,merchant_id,@@ -195,7 +195,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt.await.change_context(StorageError::EncryptionError)?;let customer_update_internal =- diesel_models::CustomerUpdateInternal::from(customer_update.clone());+ diesel_models::CustomerUpdateInternal::foreign_from(customer_update.clone());let updated_customer = customer_update_internal.clone().apply_changeset(customer.clone());@@ -215,11 +215,11 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStBox::pin(self.update_resource(key_store,storage_scheme,- customers::Customer::update_by_customer_id_merchant_id(+ diesel_models::Customer::update_by_customer_id_merchant_id(&conn,customer_id.clone(),merchant_id.clone(),- customer_update.clone().into(),+ customer_update.clone().foreign_into(),),updated_customer,kv_router_store::UpdateResourceParams {@@ -243,7 +243,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStlet result: domain::Customer = Box::pin(self.find_resource_by_id(key_store,storage_scheme,- customers::Customer::find_by_merchant_reference_id_merchant_id(+ diesel_models::Customer::find_by_merchant_reference_id_merchant_id(&conn,merchant_reference_id,merchant_id,@@ -277,7 +277,11 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStlet result: domain::Customer = Box::pin(self.find_resource_by_id(key_store,storage_scheme,- customers::Customer::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id),+ diesel_models::Customer::find_by_customer_id_merchant_id(+ &conn,+ customer_id,+ merchant_id,+ ),kv_router_store::FindResourceBy::Id(format!("cust_{}", customer_id.get_string_repr()),PartitionKey::MerchantIdCustomerId {@@ -337,7 +341,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt.await.change_context(StorageError::EncryptionError)?;- let decided_storage_scheme = Box::pin(decide_storage_scheme::<_, customers::Customer>(+ let decided_storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(self,storage_scheme,Op::Insert,@@ -393,7 +397,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt.construct_new().await.change_context(StorageError::EncryptionError)?;- let storage_scheme = Box::pin(decide_storage_scheme::<_, customers::Customer>(+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(self,storage_scheme,Op::Insert,@@ -447,7 +451,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStlet result: domain::Customer = Box::pin(self.find_resource_by_id(key_store,storage_scheme,- customers::Customer::find_by_global_id(&conn, id),+ diesel_models::Customer::find_by_global_id(&conn, id),kv_router_store::FindResourceBy::Id(format!("cust_{}", id.get_string_repr()),PartitionKey::GlobalId {@@ -477,7 +481,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStlet result: domain::Customer = Box::pin(self.find_resource_by_id(key_store,storage_scheme,- customers::Customer::find_by_global_id_merchant_id(&conn, id, merchant_id),+ diesel_models::Customer::find_by_global_id_merchant_id(&conn, id, merchant_id),kv_router_store::FindResourceBy::Id(format!("cust_{}", id.get_string_repr()),PartitionKey::GlobalId {@@ -509,9 +513,9 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStlet conn = pg_connection_read(self).await?;let database_call = || async {Ok::<_, error_stack::Report<StorageError>>(- customers::Customer::find_by_global_id(&conn, id)+ diesel_models::Customer::find_by_global_id(&conn, id).await- .map(domain::CustomerWithoutEncrypted::from)+ .map(domain::CustomerWithoutEncrypted::foreign_from).map_err(StorageError::from)?,)};@@ -537,7 +541,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt)).await?.try_into_hget()?;- Ok(domain::CustomerWithoutEncrypted::from(customer))+ Ok(domain::CustomerWithoutEncrypted::foreign_from(customer))},database_call,))@@ -571,7 +575,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt.await.change_context(StorageError::EncryptionError)?;let customer_update_internal =- diesel_models::CustomerUpdateInternal::from(customer_update.clone());+ diesel_models::CustomerUpdateInternal::foreign_from(customer_update.clone());let database_call =customers::Customer::update_by_id(&conn, id.clone(), customer_update_internal.clone());let key = PartitionKey::GlobalId {@@ -612,9 +616,9 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {) -> CustomResult<Option<domain::Customer>, StorageError> {let conn = pg_connection_read(self).await?;let maybe_customer: Option<domain::Customer> = self- .find_optional_resource(+ .find_optional_resource_new(key_store,- customers::Customer::find_optional_by_customer_id_merchant_id(+ diesel_models::Customer::find_optional_by_customer_id_merchant_id(&conn,customer_id,merchant_id,@@ -643,9 +647,9 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<Option<domain::Customer>, StorageError> {let conn = pg_connection_read(self).await?;- self.find_optional_resource(+ self.find_optional_resource_new(key_store,- customers::Customer::find_optional_by_customer_id_merchant_id(+ diesel_models::Customer::find_optional_by_customer_id_merchant_id(&conn,customer_id,merchant_id,@@ -665,9 +669,9 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {) -> CustomResult<Option<domain::Customer>, StorageError> {let conn = pg_connection_read(self).await?;let maybe_customer: Option<domain::Customer> = self- .find_optional_resource(+ .find_optional_resource_new(key_store,- customers::Customer::find_optional_by_merchant_id_merchant_reference_id(+ diesel_models::Customer::find_optional_by_merchant_id_merchant_reference_id(&conn,customer_id,merchant_id,@@ -735,13 +739,13 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<domain::Customer, StorageError> {let conn = pg_connection_write(self).await?;- self.call_database(+ self.call_database_new(key_store,- customers::Customer::update_by_customer_id_merchant_id(+ diesel_models::Customer::update_by_customer_id_merchant_id(&conn,customer_id,merchant_id.clone(),- customer_update.into(),+ customer_update.foreign_into(),),).await@@ -758,9 +762,9 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {) -> CustomResult<domain::Customer, StorageError> {let conn = pg_connection_read(self).await?;let customer: domain::Customer = self- .call_database(+ .call_database_new(key_store,- customers::Customer::find_by_customer_id_merchant_id(+ diesel_models::Customer::find_by_customer_id_merchant_id(&conn,customer_id,merchant_id,@@ -784,9 +788,9 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {) -> CustomResult<domain::Customer, StorageError> {let conn = pg_connection_read(self).await?;let customer: domain::Customer = self- .call_database(+ .call_database_new(key_store,- customers::Customer::find_by_merchant_reference_id_merchant_id(+ diesel_models::Customer::find_by_merchant_reference_id_merchant_id(&conn,merchant_reference_id,merchant_id,@@ -809,9 +813,9 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {let conn = pg_connection_read(self).await?;let customer_list_constraints =diesel_models::query::customers::CustomerListConstraints::from(constraints);- self.find_resources(+ self.find_resources_new(key_store,- customers::Customer::list_customers_by_merchant_id_and_constraints(+ diesel_models::Customer::list_customers_by_merchant_id_and_constraints(&conn,merchant_id,customer_list_constraints,@@ -837,25 +841,26 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {time_range: customer_list_constraints.time_range,};let customers = self- .find_resources(+ .find_resources_new(key_store,- customers::Customer::list_customers_by_merchant_id_and_constraints(+ diesel_models::Customer::list_customers_by_merchant_id_and_constraints(&conn,merchant_id,customers_constraints,),).await?;- let total_count = customers::Customer::get_customer_count_by_merchant_id_and_constraints(- &conn,- merchant_id,- customer_list_constraints,- )- .await- .map_err(|error| {- let new_err = diesel_error_to_data_error(*error.current_context());- error.change_context(new_err)- })?;+ let total_count =+ diesel_models::Customer::get_customer_count_by_merchant_id_and_constraints(+ &conn,+ merchant_id,+ customer_list_constraints,+ )+ .await+ .map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ })?;Ok((customers, total_count))}@@ -871,7 +876,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {.construct_new().await.change_context(StorageError::EncryptionError)?;- self.call_database(key_store, customer_new.insert(&conn))+ self.call_database_new(key_store, customer_new.insert(&conn)).await}@@ -883,7 +888,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {merchant_id: &id_type::MerchantId,) -> CustomResult<bool, StorageError> {let conn = pg_connection_write(self).await?;- customers::Customer::delete_by_customer_id_merchant_id(&conn, customer_id, merchant_id)+ diesel_models::Customer::delete_by_customer_id_merchant_id(&conn, customer_id, merchant_id).await.map_err(|error| {let new_err = diesel_error_to_data_error(*error.current_context());@@ -902,9 +907,13 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<domain::Customer, StorageError> {let conn = pg_connection_write(self).await?;- self.call_database(+ self.call_database_new(key_store,- customers::Customer::update_by_id(&conn, id.clone(), customer_update.into()),+ diesel_models::Customer::update_by_id(+ &conn,+ id.clone(),+ customer_update.foreign_into(),+ ),).await}@@ -919,7 +928,10 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {) -> CustomResult<domain::Customer, StorageError> {let conn = pg_connection_read(self).await?;let customer: domain::Customer = self- .call_database(key_store, customers::Customer::find_by_global_id(&conn, id))+ .call_database_new(+ key_store,+ diesel_models::Customer::find_by_global_id(&conn, id),+ ).await?;match customer.name {Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?,@@ -938,9 +950,9 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {) -> CustomResult<domain::Customer, StorageError> {let conn = pg_connection_read(self).await?;let customer: domain::Customer = self- .call_database(+ .call_database_new(key_store,- customers::Customer::find_by_global_id_merchant_id(&conn, id, merchant_id),+ diesel_models::Customer::find_by_global_id_merchant_id(&conn, id, merchant_id),).await?;match customer.name {@@ -960,7 +972,7 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {let conn = pg_connection_read(self).await?;let customer = customers::Customer::find_by_global_id(&conn, id).await- .map(domain::CustomerWithoutEncrypted::from)+ .map(domain::CustomerWithoutEncrypted::foreign_from).map_err(StorageError::from)?;if customer.merchant_id != *merchant_id {@@ -987,7 +999,7 @@ impl domain::CustomerInterface for MockDb {_storage_scheme: MerchantStorageScheme,) -> CustomResult<Option<domain::Customer>, StorageError> {let customers = self.customers.lock().await;- self.find_resource(key_store, customers, |customer| {+ self.find_resource_new(key_store, customers, |customer| {customer.customer_id == *customer_id && &customer.merchant_id == merchant_id}).await@@ -1002,7 +1014,7 @@ impl domain::CustomerInterface for MockDb {_storage_scheme: MerchantStorageScheme,) -> CustomResult<Option<domain::Customer>, StorageError> {let customers = self.customers.lock().await;- self.find_resource(key_store, customers, |customer| {+ self.find_resource_new(key_store, customers, |customer| {customer.customer_id == *customer_id && &customer.merchant_id == merchant_id}).await@@ -1267,3 +1279,544 @@ impl domain::CustomerInterface for MockDb {Err(StorageError::MockDbError)?}}++#[cfg(feature = "v2")]+use common_enums::DeleteStatus;+use common_utils::{+ crypto::Encryptable,+ date_time,+ encryption::Encryption,+ errors::ValidationError,+ types::{+ keymanager::{self, KeyManagerState, ToEncryptable},+ CreatedBy,+ },+};+use hyperswitch_domain_models::type_encryption;+use hyperswitch_masking::{Secret, SwitchStrategy};++#[cfg(feature = "v1")]+#[async_trait::async_trait]+impl Conversion for domain::Customer {+ type DstType = diesel_models::Customer;+ type NewDstType = diesel_models::CustomerNew;+ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {+ let customer_id = self.get_id().clone();+ let global_customer_id = self.get_global_id().cloned();+ Ok(diesel_models::Customer {+ customer_id,+ merchant_id: self.merchant_id,+ name: self.name.map(Encryption::from),+ email: self.email.map(Encryption::from),+ phone: self.phone.map(Encryption::from),+ phone_country_code: self.phone_country_code,+ description: self.description,+ created_at: self.created_at,+ metadata: self.metadata,+ modified_at: self.modified_at,+ connector_customer: self.connector_customer,+ address_id: self.address_id,+ default_payment_method_id: self.default_payment_method_id,+ updated_by: self.updated_by,+ version: self.version,+ tax_registration_id: self.tax_registration_id.map(Encryption::from),+ document_details: self.document_details.map(Encryption::from),+ created_by: self.created_by.map(|created_by| created_by.to_string()),+ last_modified_by: self+ .last_modified_by+ .map(|last_modified_by| last_modified_by.to_string()),+ id: global_customer_id,+ })+ }++ async fn convert_back(+ state: &KeyManagerState,+ item: Self::DstType,+ key: &Secret<Vec<u8>>,+ _key_store_ref_id: keymanager::Identifier,+ ) -> CustomResult<Self, ValidationError>+ where+ Self: Sized,+ {+ let decrypted = type_encryption::crypto_operation(+ state,+ common_utils::type_name!(Self::DstType),+ type_encryption::CryptoOperation::BatchDecrypt(+ domain::EncryptedCustomer::to_encryptable(domain::EncryptedCustomer {+ name: item.name.clone(),+ phone: item.phone.clone(),+ email: item.email.clone(),+ tax_registration_id: item.tax_registration_id.clone(),+ }),+ ),+ keymanager::Identifier::Merchant(item.merchant_id.clone()),+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_batchoperation())+ .change_context(ValidationError::InvalidValue {+ message: "Failed while decrypting customer data".to_string(),+ })?;+ let encryptable_customer = domain::EncryptedCustomer::from_encryptable(decrypted)+ .change_context(ValidationError::InvalidValue {+ message: "Failed while decrypting customer data".to_string(),+ })?;+ let document_details = item+ .document_details+ .async_lift(|inner| async {+ type_encryption::crypto_operation(+ state,+ common_utils::type_name!(Self),+ type_encryption::CryptoOperation::DecryptOptional(inner),+ keymanager::Identifier::Merchant(item.merchant_id.clone()),+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_optionaloperation())+ })+ .await+ .change_context(ValidationError::InvalidValue {+ message: "Failed to decrypt document details".to_string(),+ })?;++ Ok(Self {+ identifiers: domain::CustomerIdentifiers::new(item.customer_id, item.id),+ merchant_id: item.merchant_id,+ name: encryptable_customer.name,+ email: encryptable_customer.email.map(|email| {+ let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(+ email.clone().into_inner().switch_strategy(),+ email.into_encrypted(),+ );+ encryptable+ }),+ phone: encryptable_customer.phone,+ phone_country_code: item.phone_country_code,+ description: item.description,+ created_at: item.created_at,+ metadata: item.metadata,+ modified_at: item.modified_at,+ connector_customer: item.connector_customer,+ address_id: item.address_id,+ default_payment_method_id: item.default_payment_method_id,+ updated_by: item.updated_by,+ version: item.version,+ tax_registration_id: encryptable_customer.tax_registration_id,+ document_details,+ created_by: item+ .created_by+ .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),+ last_modified_by: item+ .last_modified_by+ .and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),+ })+ }++ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {+ let now = date_time::now();+ let customer_id = self.get_id().clone();+ let global_customer_id = self.get_global_id().cloned();+ Ok(diesel_models::CustomerNew {+ id: global_customer_id,+ customer_id,+ merchant_id: self.merchant_id,+ name: self.name.map(Encryption::from),+ email: self.email.map(Encryption::from),+ phone: self.phone.map(Encryption::from),+ description: self.description,+ phone_country_code: self.phone_country_code,+ metadata: self.metadata,+ created_at: now,+ modified_at: now,+ connector_customer: self.connector_customer,+ address_id: self.address_id,+ updated_by: self.updated_by,+ version: self.version,+ tax_registration_id: self.tax_registration_id.map(Encryption::from),+ document_details: self.document_details.map(Encryption::from),+ created_by: self+ .created_by+ .as_ref()+ .map(|created_by| created_by.to_string()),+ last_modified_by: self.created_by.map(|created_by| created_by.to_string()), // Same as created_by on creation+ })+ }+}++#[cfg(feature = "v1")]+impl ForeignFrom<domain::CustomerUpdate> for diesel_models::CustomerUpdateInternal {+ fn foreign_from(customer_update: domain::CustomerUpdate) -> Self {+ match customer_update {+ domain::CustomerUpdate::Update {+ name,+ email,+ phone,+ description,+ phone_country_code,+ metadata,+ connector_customer,+ address_id,+ tax_registration_id,+ document_details,+ last_modified_by,+ } => Self {+ name: name.map(Encryption::from),+ email: email.map(Encryption::from),+ phone: phone.map(Encryption::from),+ description,+ phone_country_code,+ metadata: *metadata,+ connector_customer: *connector_customer,+ modified_at: date_time::now(),+ address_id,+ default_payment_method_id: None,+ updated_by: None,+ tax_registration_id: tax_registration_id.map(Encryption::from),+ document_details: document_details.map(Encryption::from),+ last_modified_by,+ },+ domain::CustomerUpdate::ConnectorCustomer {+ connector_customer,+ last_modified_by,+ } => Self {+ connector_customer,+ modified_at: date_time::now(),+ name: None,+ email: None,+ phone: None,+ description: None,+ phone_country_code: None,+ metadata: None,+ default_payment_method_id: None,+ updated_by: None,+ address_id: None,+ tax_registration_id: None,+ document_details: None,+ last_modified_by,+ },+ domain::CustomerUpdate::UpdateDefaultPaymentMethod {+ default_payment_method_id,+ last_modified_by,+ } => Self {+ default_payment_method_id,+ modified_at: date_time::now(),+ name: None,+ email: None,+ phone: None,+ description: None,+ phone_country_code: None,+ metadata: None,+ connector_customer: None,+ updated_by: None,+ address_id: None,+ tax_registration_id: None,+ document_details: None,+ last_modified_by,+ },+ }+ }+}++#[cfg(feature = "v2")]+#[async_trait::async_trait]+impl Conversion for domain::Customer {+ type DstType = diesel_models::Customer;+ type NewDstType = diesel_models::CustomerNew;+ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {+ Ok(diesel_models::Customer {+ id: self.id.clone(),+ customer_id: Some(self.id),+ merchant_reference_id: self.merchant_reference_id,+ merchant_id: self.merchant_id,+ name: self.name.map(Encryption::from),+ email: self.email.map(Encryption::from),+ phone: self.phone.map(Encryption::from),+ phone_country_code: self.phone_country_code,+ description: self.description,+ created_at: self.created_at,+ metadata: self.metadata,+ modified_at: self.modified_at,+ connector_customer: self.connector_customer,+ default_payment_method_id: self.default_payment_method_id,+ updated_by: self.updated_by,+ default_billing_address: self.default_billing_address.map(Encryption::from),+ default_shipping_address: self.default_shipping_address.map(Encryption::from),+ version: self.version,+ status: self.status,+ tax_registration_id: self.tax_registration_id.map(Encryption::from),+ document_details: self.document_details.map(Encryption::from),+ created_by: self.created_by.map(|created_by| created_by.to_string()),+ last_modified_by: self+ .last_modified_by+ .map(|last_modified_by| last_modified_by.to_string()),+ })+ }++ async fn convert_back(+ state: &KeyManagerState,+ item: Self::DstType,+ key: &Secret<Vec<u8>>,+ _key_store_ref_id: keymanager::Identifier,+ ) -> CustomResult<Self, ValidationError>+ where+ Self: Sized,+ {+ let decrypted = type_encryption::crypto_operation(+ state,+ common_utils::type_name!(Self::DstType),+ type_encryption::CryptoOperation::BatchDecrypt(+ domain::EncryptedCustomer::to_encryptable(domain::EncryptedCustomer {+ name: item.name.clone(),+ phone: item.phone.clone(),+ email: item.email.clone(),+ tax_registration_id: item.tax_registration_id.clone(),+ }),+ ),+ keymanager::Identifier::Merchant(item.merchant_id.clone()),+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_batchoperation())+ .change_context(ValidationError::InvalidValue {+ message: "Failed while decrypting customer data".to_string(),+ })?;+ let encryptable_customer = domain::EncryptedCustomer::from_encryptable(decrypted)+ .change_context(ValidationError::InvalidValue {+ message: "Failed while decrypting customer data".to_string(),+ })?;++ let default_billing_address = item+ .default_billing_address+ .async_lift(|inner| async {+ type_encryption::crypto_operation(+ state,+ common_utils::type_name!(Self),+ type_encryption::CryptoOperation::DecryptOptional(inner),+ keymanager::Identifier::Merchant(item.merchant_id.clone()),+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_optionaloperation())+ })+ .await+ .change_context(ValidationError::InvalidValue {+ message: "Failed to decrypt default billing address".to_string(),+ })?;++ let default_shipping_address = item+ .default_shipping_address+ .async_lift(|inner| async {+ type_encryption::crypto_operation(+ state,+ common_utils::type_name!(Self),+ type_encryption::CryptoOperation::DecryptOptional(inner),+ keymanager::Identifier::Merchant(item.merchant_id.clone()),+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_optionaloperation())+ })+ .await+ .change_context(ValidationError::InvalidValue {+ message: "Failed to decrypt default shipping address".to_string(),+ })?;++ let document_details = item+ .document_details+ .async_lift(|inner| async {+ type_encryption::crypto_operation(+ state,+ common_utils::type_name!(Self),+ type_encryption::CryptoOperation::DecryptOptional(inner),+ keymanager::Identifier::Merchant(item.merchant_id.clone()),+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_optionaloperation())+ })+ .await+ .change_context(ValidationError::InvalidValue {+ message: "Failed to decrypt document details".to_string(),+ })?;++ Ok(Self {+ id: item.id,+ merchant_reference_id: item.merchant_reference_id,+ merchant_id: item.merchant_id,+ name: encryptable_customer.name,+ email: encryptable_customer.email.map(|email| {+ let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(+ email.clone().into_inner().switch_strategy(),+ email.into_encrypted(),+ );+ encryptable+ }),+ phone: encryptable_customer.phone,+ phone_country_code: item.phone_country_code,+ description: item.description,+ created_at: item.created_at,+ metadata: item.metadata,+ modified_at: item.modified_at,+ connector_customer: item.connector_customer,+ default_payment_method_id: item.default_payment_method_id,+ updated_by: item.updated_by,+ default_billing_address,+ default_shipping_address,+ version: item.version,+ status: item.status,+ tax_registration_id: encryptable_customer.tax_registration_id,+ document_details,+ created_by: item+ .created_by+ .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),+ last_modified_by: item+ .last_modified_by+ .and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),+ })+ }++ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {+ let now = date_time::now();+ Ok(customers::CustomerNew {+ id: self.id.clone(),+ merchant_reference_id: self.merchant_reference_id,+ merchant_id: self.merchant_id,+ name: self.name.map(Encryption::from),+ email: self.email.map(Encryption::from),+ phone: self.phone.map(Encryption::from),+ description: self.description,+ phone_country_code: self.phone_country_code,+ metadata: self.metadata,+ default_payment_method_id: None,+ created_at: now,+ modified_at: now,+ connector_customer: self.connector_customer,+ updated_by: self.updated_by,+ default_billing_address: self.default_billing_address.map(Encryption::from),+ default_shipping_address: self.default_shipping_address.map(Encryption::from),+ version: common_types::consts::API_VERSION,+ status: self.status,+ tax_registration_id: self.tax_registration_id.map(Encryption::from),+ document_details: self.document_details.map(Encryption::from),+ created_by: self+ .created_by+ .as_ref()+ .map(|created_by| created_by.to_string()),+ last_modified_by: self.created_by.map(|created_by| created_by.to_string()), // Same as created_by on creation+ customer_id: Some(self.id),+ })+ }+}++#[cfg(feature = "v2")]+impl ForeignFrom<domain::CustomerUpdate> for diesel_models::CustomerUpdateInternal {+ fn foreign_from(customer_update: domain::CustomerUpdate) -> Self {+ match customer_update {+ domain::CustomerUpdate::Update(update) => {+ let domain::CustomerGeneralUpdate {+ name,+ email,+ phone,+ description,+ phone_country_code,+ metadata,+ connector_customer,+ default_billing_address,+ default_shipping_address,+ default_payment_method_id,+ status,+ tax_registration_id,+ document_details,+ last_modified_by,+ } = *update;+ Self {+ name: name.map(Encryption::from),+ email: email.map(Encryption::from),+ phone: phone.map(Encryption::from),+ description,+ phone_country_code,+ metadata,+ connector_customer: *connector_customer,+ modified_at: date_time::now(),+ default_billing_address: default_billing_address.map(Encryption::from),+ default_shipping_address: default_shipping_address.map(Encryption::from),+ default_payment_method_id,+ updated_by: None,+ status,+ tax_registration_id: tax_registration_id.map(Encryption::from),+ document_details: document_details.map(Encryption::from),+ last_modified_by,+ }+ }+ domain::CustomerUpdate::ConnectorCustomer {+ connector_customer,+ last_modified_by,+ } => Self {+ connector_customer,+ name: None,+ email: None,+ phone: None,+ description: None,+ phone_country_code: None,+ metadata: None,+ modified_at: date_time::now(),+ default_payment_method_id: None,+ updated_by: None,+ default_billing_address: None,+ default_shipping_address: None,+ status: None,+ tax_registration_id: None,+ document_details: None,+ last_modified_by,+ },+ domain::CustomerUpdate::UpdateDefaultPaymentMethod {+ default_payment_method_id,+ last_modified_by,+ } => Self {+ default_payment_method_id,+ modified_at: date_time::now(),+ name: None,+ email: None,+ phone: None,+ description: None,+ phone_country_code: None,+ metadata: None,+ connector_customer: None,+ updated_by: None,+ default_billing_address: None,+ default_shipping_address: None,+ status: None,+ tax_registration_id: None,+ document_details: None,+ last_modified_by,+ },+ }+ }+}++#[cfg(feature = "v2")]+impl ForeignFrom<diesel_models::Customer> for domain::CustomerWithoutEncrypted {+ fn foreign_from(customer: diesel_models::Customer) -> Self {+ Self {+ merchant_id: customer.merchant_id,+ phone_country_code: customer.phone_country_code,+ description: customer.description,+ created_at: customer.created_at,+ metadata: customer.metadata,+ connector_customer: customer.connector_customer,+ modified_at: customer.modified_at,+ default_payment_method_id: customer.default_payment_method_id,+ updated_by: customer.updated_by,+ merchant_reference_id: customer.merchant_reference_id,+ id: customer.id,+ version: customer.version,+ status: customer.status,+ created_by: customer+ .created_by+ .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),+ last_modified_by: customer+ .last_modified_by+ .and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),+ }+ }+}diff --git a/crates/storage_impl/src/kv_router_store.rs b/crates/storage_impl/src/kv_router_store.rsindex 570ae2f8d2..a7e6552423 100644--- a/crates/storage_impl/src/kv_router_store.rs+++ b/crates/storage_impl/src/kv_router_store.rs@@ -7,10 +7,7 @@ use common_utils::{};use diesel_models::{errors::DatabaseError, kv};use error_stack::ResultExt;-use hyperswitch_domain_models::{- behaviour::{Conversion, ReverseConversion},- merchant_key_store::MerchantKeyStore,-};+use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;#[cfg(not(feature = "payouts"))]use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};use hyperswitch_masking::StrongSecret;@@ -20,8 +17,8 @@ use serde::de;#[cfg(not(feature = "payouts"))]pub use crate::database::store::Store;-pub use crate::{database::store::DatabaseStore, mock_db::MockDb};use crate::{+ behaviour::{Conversion, ReverseConversion},database::store::PgPool,diesel_error_to_data_error,errors::{self, RedisErrorExt, StorageResult},@@ -34,6 +31,7 @@ use crate::{utils::{find_all_combined_kv_database, try_redis_get_else_try_database_get},RouterStore, TenantConfig, UniqueConstraints,};+pub use crate::{database::store::DatabaseStore, mock_db::MockDb};#[derive(Debug, Clone)]pub struct KVRouterStore<T: DatabaseStore> {@@ -317,6 +315,85 @@ impl<T: DatabaseStore> KVRouterStore<T> {.change_context(errors::StorageError::DecryptionError)}+ // Equivalent of find_resource_by_id but where the conversion trait is still+ // implemented in the hyperswitch_domain_models crate (used by types not yet+ // migrated to the storage_impl Conversion impls, e.g. PaymentIntent).+ pub async fn find_resource_by_id_old<D, R, M>(+ &self,+ key_store: &MerchantKeyStore,+ storage_scheme: MerchantStorageScheme,+ find_resource_db_fut: R,+ find_by: FindResourceBy<'_>,+ ) -> error_stack::Result<D, errors::StorageError>+ where+ D: Debug + Sync + hyperswitch_domain_models::behaviour::Conversion,+ M: de::DeserializeOwned+ + serde::Serialize+ + Debug+ + KvStorePartition+ + UniqueConstraints+ + Sync+ + Send+ + hyperswitch_domain_models::behaviour::ReverseConversion<D>,+ R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,+ {+ let database_call = || async {+ find_resource_db_fut.await.map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ })+ };+ let storage_scheme = Box::pin(decide_storage_scheme::<T, M>(+ self,+ storage_scheme,+ Op::Find,+ ))+ .await;+ let res = || async {+ match storage_scheme {+ MerchantStorageScheme::PostgresOnly => database_call().await,+ MerchantStorageScheme::RedisKv => {+ let (field, key) = match find_by {+ FindResourceBy::Id(field, key) => (field, key),+ FindResourceBy::LookupId(lookup_id) => {+ let lookup = fallback_reverse_lookup_not_found!(+ self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)+ .await,+ database_call().await+ );+ (+ lookup.clone().sk_id,+ PartitionKey::CombinationKey {+ combination: &lookup.clone().pk_id,+ },+ )+ }+ };++ Box::pin(try_redis_get_else_try_database_get(+ async {+ Box::pin(kv_wrapper(self, KvOperation::<M>::HGet(&field), key))+ .await?+ .try_into_hget()+ },+ database_call,+ ))+ .await+ }+ }+ };+ res()+ .await?+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key_store.key.get_inner(),+ key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)+ }+pub async fn find_optional_resource_by_id<D, R, M>(&self,key_store: &MerchantKeyStore,@@ -538,6 +615,174 @@ impl<T: DatabaseStore> KVRouterStore<T> {.await.change_context(errors::StorageError::DecryptionError)}++ // Equivalent of insert_resource but where the conversion trait is still+ // implemented in the hyperswitch_domain_models crate (used by types not yet+ // migrated to the storage_impl Conversion impls, e.g. PaymentIntent).+ pub async fn insert_resource_old<D, R, M, DrainerQueryFut>(+ &self,+ key_store: &MerchantKeyStore,+ storage_scheme: MerchantStorageScheme,+ create_resource_fut: R,+ resource_new: M,+ InsertResourceParams {+ drainer_query_fut,+ reverse_lookups,+ key,+ identifier,+ resource_type,+ }: InsertResourceParams<'_, DrainerQueryFut>,+ ) -> error_stack::Result<D, errors::StorageError>+ where+ D: Debug + Sync + hyperswitch_domain_models::behaviour::Conversion,+ M: de::DeserializeOwned+ + serde::Serialize+ + Debug+ + KvStorePartition+ + UniqueConstraints+ + Sync+ + Send+ + hyperswitch_domain_models::behaviour::ReverseConversion<D>,+ R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,+ DrainerQueryFut:+ futures::Future<Output = diesel_models::StorageResult<kv::SerializableQuery>> + Send,+ {+ let storage_scheme = Box::pin(decide_storage_scheme::<_, M>(+ self,+ storage_scheme,+ Op::Insert,+ ))+ .await;+ match storage_scheme {+ MerchantStorageScheme::PostgresOnly => create_resource_fut.await.map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ }),+ MerchantStorageScheme::RedisKv => {+ let key_str = key.to_string();+ let reverse_lookup_entry = |v: String| diesel_models::ReverseLookupNew {+ sk_id: identifier.clone(),+ pk_id: key_str.clone(),+ lookup_id: v,+ source: resource_type.to_string(),+ updated_by: storage_scheme.to_string(),+ };+ let results = reverse_lookups+ .into_iter()+ .map(|v| self.insert_reverse_lookup(reverse_lookup_entry(v), storage_scheme));++ futures::future::try_join_all(results).await?;++ let drainer_query = drainer_query_fut+ .await+ .change_context(errors::StorageError::KVError)+ .attach_printable("Failed to generate drainer insert query")?;++ match Box::pin(kv_wrapper::<M, _, _>(+ self,+ KvOperation::<M>::HSetNx(&identifier, &resource_new, drainer_query),+ key.clone(),+ ))+ .await+ .map_err(|err| err.to_redis_failed_response(&key.to_string()))?+ .try_into_hsetnx()+ {+ Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {+ entity: resource_type,+ key: Some(key_str),+ }+ .into()),+ Ok(HsetnxReply::KeySet) => Ok(resource_new),+ Err(er) => Err(er).change_context(errors::StorageError::KVError),+ }+ }+ }?+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key_store.key.get_inner(),+ key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)+ }++ // Equivalent of update_resource but where the conversion trait is still+ // implemented in the hyperswitch_domain_models crate (used by types not yet+ // migrated to the storage_impl Conversion impls, e.g. PaymentIntent).+ pub async fn update_resource_old<D, R, M, DrainerQueryFut>(+ &self,+ key_store: &MerchantKeyStore,+ storage_scheme: MerchantStorageScheme,+ update_resource_fut: R,+ updated_resource: M,+ UpdateResourceParams {+ drainer_query_fut,+ operation,+ }: UpdateResourceParams<'_, DrainerQueryFut>,+ ) -> error_stack::Result<D, errors::StorageError>+ where+ D: Debug + Sync + hyperswitch_domain_models::behaviour::Conversion,+ M: de::DeserializeOwned+ + serde::Serialize+ + Debug+ + KvStorePartition+ + UniqueConstraints+ + Sync+ + Send+ + hyperswitch_domain_models::behaviour::ReverseConversion<D>,+ R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,+ DrainerQueryFut:+ futures::Future<Output = diesel_models::StorageResult<kv::SerializableQuery>> + Send,+ {+ match operation {+ Op::Update(key, field, updated_by) => {+ let storage_scheme = Box::pin(decide_storage_scheme::<_, M>(+ self,+ storage_scheme,+ Op::Update(key.clone(), field, updated_by),+ ))+ .await;+ match storage_scheme {+ MerchantStorageScheme::PostgresOnly => {+ update_resource_fut.await.map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ })+ }+ MerchantStorageScheme::RedisKv => {+ let key_str = key.to_string();+ let redis_value = serde_json::to_string(&updated_resource)+ .change_context(errors::StorageError::SerializationFailed)?;+ let drainer_query = drainer_query_fut+ .await+ .change_context(errors::StorageError::KVError)+ .attach_printable("Failed to generate drainer update query")?;++ Box::pin(kv_wrapper::<(), _, _>(+ self,+ KvOperation::<M>::Hset((field, redis_value), drainer_query),+ key,+ ))+ .await+ .map_err(|err| err.to_redis_failed_response(&key_str))?+ .try_into_hset()+ .change_context(errors::StorageError::KVError)?;+ Ok(updated_resource)+ }+ }+ }+ _ => Err(errors::StorageError::KVError.into()),+ }?+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key_store.key.get_inner(),+ key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(errors::StorageError::DecryptionError)+ }pub async fn filter_resources<D, R, M>(&self,key_store: &MerchantKeyStore,diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rsindex 0bc9fef8d1..7e439ce0aa 100644--- a/crates/storage_impl/src/lib.rs+++ b/crates/storage_impl/src/lib.rs@@ -303,6 +303,37 @@ impl<T: DatabaseStore> RouterStore<T> {}}+ pub async fn find_optional_resource_new<D, R, M>(+ &self,+ key_store: &MerchantKeyStore,+ execute_query_fut: R,+ ) -> error_stack::Result<Option<D>, StorageError>+ where+ D: Debug + Sync + behaviour::Conversion,+ R: futures::Future<+ Output = error_stack::Result<Option<M>, diesel_models::errors::DatabaseError>,+ > + Send,+ M: behaviour::ReverseConversion<D>,+ {+ match execute_query_fut.await.map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ })? {+ Some(resource) => Ok(Some(+ resource+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key_store.key.get_inner(),+ key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(StorageError::DecryptionError)?,+ )),+ None => Ok(None),+ }+ }+// TODO: This needs to be removed after the removal of diesel_models dependency from domain_models is donepub async fn find_resources<D, R, M>(&self,diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rsindex 2aee44073e..b259c07b0b 100644--- a/crates/storage_impl/src/mock_db.rs+++ b/crates/storage_impl/src/mock_db.rs@@ -162,6 +162,33 @@ impl MockDb {}}+ /// TODO: Remove this once diesel_model dependency is removed from domain_models+ pub async fn find_resource_new<D, R>(+ &self,+ key_store: &MerchantKeyStore,+ resources: MutexGuard<'_, Vec<D>>,+ filter_fn: impl Fn(&&D) -> bool,+ ) -> CustomResult<Option<R>, StorageError>+ where+ D: Sync + crate::behaviour::ReverseConversion<R> + Clone,+ R: crate::behaviour::Conversion,+ {+ let resource = resources.iter().find(filter_fn).cloned();+ match resource {+ Some(res) => Ok(Some(+ res.convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key_store.key.get_inner(),+ key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(StorageError::DecryptionError)?,+ )),+ None => Ok(None),+ }+ }+/// Throws errors when the requested resource is not foundpub async fn get_resource<D, R>(&self,@@ -180,6 +207,27 @@ impl MockDb {}}+ /// TODO: Remove this once diesel_model dependency is removed from domain_models+ pub async fn get_resource_new<D, R>(+ &self,+ key_store: &MerchantKeyStore,+ resources: MutexGuard<'_, Vec<D>>,+ filter_fn: impl Fn(&&D) -> bool,+ error_message: String,+ ) -> CustomResult<R, StorageError>+ where+ D: Sync + crate::behaviour::ReverseConversion<R> + Clone,+ R: crate::behaviour::Conversion,+ {+ match self+ .find_resource_new(key_store, resources, filter_fn)+ .await?+ {+ Some(res) => Ok(res),+ None => Err(StorageError::ValueNotFound(error_message).into()),+ }+ }+pub async fn get_resources<D, R>(&self,key_store: &MerchantKeyStore,@@ -215,6 +263,42 @@ impl MockDb {}}+ /// TODO: Remove this once diesel_model dependency is removed from domain_models+ pub async fn get_resources_new<D, R>(+ &self,+ key_store: &MerchantKeyStore,+ resources: MutexGuard<'_, Vec<D>>,+ filter_fn: impl Fn(&&D) -> bool,+ error_message: String,+ ) -> CustomResult<Vec<R>, StorageError>+ where+ D: Sync + crate::behaviour::ReverseConversion<R> + Clone,+ R: crate::behaviour::Conversion,+ {+ let resources: Vec<_> = resources.iter().filter(filter_fn).cloned().collect();+ if resources.is_empty() {+ Err(StorageError::ValueNotFound(error_message).into())+ } else {+ let pm_futures = resources+ .into_iter()+ .map(|pm| async {+ pm.convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key_store.key.get_inner(),+ key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(StorageError::DecryptionError)+ })+ .collect::<Vec<_>>();++ let domain_resources = futures::future::try_join_all(pm_futures).await?;++ Ok(domain_resources)+ }+ }+pub async fn update_resource<D, R>(&self,key_store: &MerchantKeyStore,@@ -244,6 +328,36 @@ impl MockDb {}}+ /// TODO: Remove this once diesel_model dependency is removed from domain_models+ pub async fn update_resource_new<D, R>(+ &self,+ key_store: &MerchantKeyStore,+ mut resources: MutexGuard<'_, Vec<D>>,+ resource_updated: D,+ filter_fn: impl Fn(&&mut D) -> bool,+ error_message: String,+ ) -> CustomResult<R, StorageError>+ where+ D: Sync + crate::behaviour::ReverseConversion<R> + Clone,+ R: crate::behaviour::Conversion,+ {+ if let Some(pm) = resources.iter_mut().find(filter_fn) {+ *pm = resource_updated.clone();+ let result = resource_updated+ .convert(+ self.get_keymanager_state()+ .attach_printable("Missing KeyManagerState")?,+ key_store.key.get_inner(),+ key_store.merchant_id.clone().into(),+ )+ .await+ .change_context(StorageError::DecryptionError)?;+ Ok(result)+ } else {+ Err(StorageError::ValueNotFound(error_message).into())+ }+ }+pub fn master_key(&self) -> &[u8] {&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,diff --git a/crates/storage_impl/src/payment_method.rs b/crates/storage_impl/src/payment_method.rsindex 9cbfb3471c..44df73ec2d 100644--- a/crates/storage_impl/src/payment_method.rs+++ b/crates/storage_impl/src/payment_method.rs@@ -2,18 +2,15 @@use std::collections::HashSet;use common_enums::enums::MerchantStorageScheme;-#[cfg(feature = "v2")]-use common_utils::ext_traits::OptionExt;use common_utils::{errors::CustomResult, id_type};pub use diesel_models::payment_method::PaymentMethod;use diesel_models::payment_method::{PaymentMethodUpdate, PaymentMethodUpdateInternal};use error_stack::ResultExt;#[cfg(feature = "v1")]-use hyperswitch_domain_models::behaviour::ReverseConversion;+use hyperswitch_domain_models::payment_methods::PaymentMethodVaultSourceDetails;#[cfg(feature = "v2")]use hyperswitch_domain_models::platform::Initiator;use hyperswitch_domain_models::{- behaviour::Conversion,merchant_key_store::MerchantKeyStore,payment_methods::{PaymentMethod as DomainPaymentMethod, PaymentMethodCompatAction, PaymentMethodInterface,@@ -23,6 +20,7 @@ use router_env::{instrument, tracing};use super::MockDb;use crate::{+ behaviour::{Conversion, ReverseConversion},diesel_error_to_data_error, errors,kv_router_store::{FindResourceBy, KVRouterStore},redis::kv_store::KvStorePartition,@@ -495,7 +493,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<DomainPaymentMethod, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.call_database(+ self.call_database_new(key_store,PaymentMethod::find_by_payment_method_id(&conn, payment_method_id),)@@ -510,7 +508,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<DomainPaymentMethod, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.call_database(+ self.call_database_new(key_store,PaymentMethod::find_by_id(&conn, payment_method_id),)@@ -525,7 +523,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<DomainPaymentMethod, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.call_database(+ self.call_database_new(key_store,PaymentMethod::find_by_locker_id(&conn, locker_id),)@@ -542,7 +540,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.find_resources(+ self.find_resources_new(key_store,PaymentMethod::find_by_merchant_id_payment_method_ids(&conn,@@ -606,7 +604,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {let conn = pg_connection_write(self).await?;let payment_method: DomainPaymentMethod =- Box::pin(self.call_database(key_store, payment_method_new.insert(&conn))).await?;+ Box::pin(self.call_database_new(key_store, payment_method_new.insert(&conn))).await?;if let Some(compat_action) = compat_action {compat_action.execute(&payment_method).await;@@ -630,7 +628,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {.change_context(errors::StorageError::DecryptionError)?;let conn = pg_connection_write(self).await?;- let payment_method: DomainPaymentMethod = Box::pin(self.call_database(+ let payment_method: DomainPaymentMethod = Box::pin(self.call_database_new(key_store,payment_method.update_with_payment_method_id(&conn, payment_method_update.into()),))@@ -657,7 +655,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {.await.change_context(errors::StorageError::DecryptionError)?;let conn = pg_connection_write(self).await?;- let payment_method: DomainPaymentMethod = Box::pin(self.call_database(+ let payment_method: DomainPaymentMethod = Box::pin(self.call_database_new(key_store,payment_method.update_with_id(&conn, payment_method_update.into()),))@@ -680,7 +678,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {limit: Option<i64>,) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.find_resources(+ self.find_resources_new(key_store,PaymentMethod::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id, limit),)@@ -697,7 +695,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {limit: Option<i64>,) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.find_resources(+ self.find_resources_new(key_store,PaymentMethod::find_by_global_customer_id(&conn, id, limit),)@@ -716,7 +714,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.find_resources(+ self.find_resources_new(key_store,PaymentMethod::find_by_customer_id_merchant_id_status(&conn,@@ -742,7 +740,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<Vec<DomainPaymentMethod>, Self::Error> {let conn = pg_connection_read(self).await?;- self.find_resources(+ self.find_resources_new(key_store,PaymentMethod::find_by_customer_id_merchant_id_status_pm_type(&conn,@@ -768,7 +766,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.find_resources(+ self.find_resources_new(key_store,PaymentMethod::find_by_global_customer_id_merchant_id_status(&conn,@@ -793,7 +791,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {_storage_scheme: MerchantStorageScheme,) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.find_resources(+ self.find_resources_new(key_store,PaymentMethod::find_by_global_customer_id_merchant_id_statuses(&conn,@@ -814,7 +812,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {payment_method_id: &str,) -> CustomResult<DomainPaymentMethod, errors::StorageError> {let conn = pg_connection_write(self).await?;- self.call_database(+ self.call_database_new(key_store,PaymentMethod::delete_by_merchant_id_payment_method_id(&conn,@@ -842,7 +840,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {.and_then(|initiator| initiator.to_created_by()).map(|last_modified_by| last_modified_by.to_string()),};- Box::pin(self.call_database(+ Box::pin(self.call_database_new(key_store,payment_method.update_with_id(&conn, payment_method_update.into()),))@@ -855,7 +853,7 @@ impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {fingerprint_id: &str,) -> CustomResult<DomainPaymentMethod, errors::StorageError> {let conn = pg_connection_read(self).await?;- self.call_database(+ self.call_database_new(key_store,PaymentMethod::find_by_fingerprint_id(&conn, fingerprint_id),)@@ -874,7 +872,7 @@ impl PaymentMethodInterface for MockDb {_storage_scheme: MerchantStorageScheme,) -> CustomResult<DomainPaymentMethod, errors::StorageError> {let payment_methods = self.payment_methods.lock().await;- self.get_resource::<PaymentMethod, _>(+ self.get_resource_new::<PaymentMethod, _>(key_store,payment_methods,|pm| pm.get_id() == payment_method_id,@@ -891,7 +889,7 @@ impl PaymentMethodInterface for MockDb {_storage_scheme: MerchantStorageScheme,) -> CustomResult<DomainPaymentMethod, errors::StorageError> {let payment_methods = self.payment_methods.lock().await;- self.get_resource::<PaymentMethod, _>(+ self.get_resource_new::<PaymentMethod, _>(key_store,payment_methods,|pm| pm.get_id() == payment_method_id,@@ -907,7 +905,7 @@ impl PaymentMethodInterface for MockDb {_storage_scheme: MerchantStorageScheme,) -> CustomResult<DomainPaymentMethod, errors::StorageError> {let payment_methods = self.payment_methods.lock().await;- self.get_resource::<PaymentMethod, _>(+ self.get_resource_new::<PaymentMethod, _>(key_store,payment_methods,|pm| pm.locker_id == Some(locker_id.to_string()),@@ -929,7 +927,7 @@ impl PaymentMethodInterface for MockDb {}let ids: HashSet<_> = payment_method_ids.iter().cloned().collect();let payment_methods = self.payment_methods.lock().await;- self.get_resources(+ self.get_resources_new(key_store,payment_methods,|pm| pm.merchant_id == *merchant_id && ids.contains(pm.get_id()),@@ -999,7 +997,7 @@ impl PaymentMethodInterface for MockDb {_limit: Option<i64>,) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {let payment_methods = self.payment_methods.lock().await;- self.get_resources(+ self.get_resources_new(key_store,payment_methods,|pm| pm.customer_id == *customer_id && pm.merchant_id == *merchant_id,@@ -1030,7 +1028,7 @@ impl PaymentMethodInterface for MockDb {_storage_scheme: MerchantStorageScheme,) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {let payment_methods = self.payment_methods.lock().await;- self.get_resources(+ self.get_resources_new(key_store,payment_methods,|pm| {@@ -1054,7 +1052,7 @@ impl PaymentMethodInterface for MockDb {_storage_scheme: MerchantStorageScheme,) -> CustomResult<Vec<DomainPaymentMethod>, Self::Error> {let payment_methods = self.payment_methods.lock().await;- self.get_resources(+ self.get_resources_new(key_store,payment_methods,|pm| {@@ -1087,7 +1085,7 @@ impl PaymentMethodInterface for MockDb {customer_id_matches && pm.merchant_id == *merchant_id && pm.status == status};let error_message = "cannot find payment method".to_string();- self.get_resources(key_store, payment_methods, find_pm_by, error_message)+ self.get_resources_new(key_store, payment_methods, find_pm_by, error_message).await}@@ -1111,7 +1109,7 @@ impl PaymentMethodInterface for MockDb {customer_id_matches && pm.merchant_id == *merchant_id && statuses.contains(&pm.status)};let error_message = "cannot find payment method".to_string();- self.get_resources(key_store, payment_methods, find_pm_by, error_message)+ self.get_resources_new(key_store, payment_methods, find_pm_by, error_message).await}@@ -1161,7 +1159,7 @@ impl PaymentMethodInterface for MockDb {.change_context(errors::StorageError::EncryptionError)?,);let payment_method: DomainPaymentMethod = self- .update_resource::<PaymentMethod, _>(+ .update_resource_new::<PaymentMethod, _>(key_store,self.payment_methods.lock().await,payment_method_updated,@@ -1196,7 +1194,7 @@ impl PaymentMethodInterface for MockDb {.await.change_context(errors::StorageError::EncryptionError)?,);- self.update_resource::<PaymentMethod, _>(+ self.update_resource_new::<PaymentMethod, _>(key_store,self.payment_methods.lock().await,payment_method_updated,@@ -1212,7 +1210,7 @@ impl PaymentMethodInterface for MockDb {fingerprint_id: &str,) -> CustomResult<DomainPaymentMethod, errors::StorageError> {let payment_methods = self.payment_methods.lock().await;- self.get_resource::<PaymentMethod, _>(+ self.get_resource_new::<PaymentMethod, _>(key_store,payment_methods,|pm| pm.locker_fingerprint_id == Some(fingerprint_id.to_string()),@@ -1221,3 +1219,625 @@ impl PaymentMethodInterface for MockDb {.await}}++#[cfg(feature = "v2")]+use api_models::payment_methods::PaymentMethodsData;+// specific imports because of using the macro+#[cfg(feature = "v2")]+use common_utils::{crypto::Encryptable, encryption::Encryption};+use common_utils::{+ errors::ValidationError,+ ext_traits::OptionExt,+ type_name,+ types::{keymanager, keymanager::ToEncryptable, CreatedBy},+};+pub use diesel_models::{+ enums as storage_enums, PaymentMethodUpdate as StoragePaymentMethodUpdate,+};+#[cfg(feature = "v2")]+use hyperswitch_domain_models::payment_methods::EncryptedPaymentMethodSession;+use hyperswitch_domain_models::{+ payment_methods::EncryptedPaymentMethod,+ type_encryption::{crypto_operation, CryptoOperation},+};+#[cfg(feature = "v2")]+use hyperswitch_masking::ExposeInterface;+use hyperswitch_masking::{PeekInterface, Secret};+#[cfg(feature = "v2")]+use serde_json::Value;++#[cfg(feature = "v1")]+#[async_trait::async_trait]+impl Conversion for hyperswitch_domain_models::payment_methods::PaymentMethod {+ type DstType = PaymentMethod;+ type NewDstType = diesel_models::payment_method::PaymentMethodNew;+ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {+ let (vault_type, external_vault_source) = self.vault_source_details.into();+ // Note: caller must ensure customer_id is not null before calling convert as storage model requires it.+ Ok(Self::DstType {+ customer_id: self.customer_id.get_required_value("customer_id")?,+ merchant_id: self.merchant_id,+ payment_method_id: self.payment_method_id,+ accepted_currency: self.accepted_currency,+ scheme: self.scheme,+ token: self.token,+ cardholder_name: self.cardholder_name,+ issuer_name: self.issuer_name,+ issuer_country: self.issuer_country,+ payer_country: self.payer_country,+ is_stored: self.is_stored,+ swift_code: self.swift_code,+ direct_debit_token: self.direct_debit_token,+ created_at: self.created_at,+ last_modified: self.last_modified,+ payment_method: self.payment_method,+ payment_method_type: self.payment_method_type,+ payment_method_issuer: self.payment_method_issuer,+ payment_method_issuer_code: self.payment_method_issuer_code,+ metadata: self.metadata,+ payment_method_data: self.payment_method_data.map(|val| val.into()),+ locker_id: self.locker_id,+ last_used_at: self.last_used_at,+ connector_mandate_details: self.connector_mandate_details,+ customer_acceptance: self.customer_acceptance,+ status: self.status,+ network_transaction_id: self.network_transaction_id,+ network_transaction_link_id: self.network_transaction_link_id,+ client_secret: self.client_secret,+ payment_method_billing_address: self+ .payment_method_billing_address+ .map(|val| val.into()),+ updated_by: self.updated_by,+ version: self.version,+ network_token_requestor_reference_id: self.network_token_requestor_reference_id,+ network_token_locker_id: self.network_token_locker_id,+ network_token_payment_method_data: self+ .network_token_payment_method_data+ .map(|val| val.into()),+ external_vault_source,+ vault_type,+ created_by: self.created_by.map(|created_by| created_by.to_string()),+ last_modified_by: self+ .last_modified_by+ .map(|last_modified_by| last_modified_by.to_string()),+ customer_details: self.customer_details.map(|val| val.into()),+ locker_fingerprint_id: self.locker_fingerprint_id,+ network_tokenization_data: self.network_tokenization_data.map(|val| val.into()),+ connector_payment_method_details: self.connector_payment_method_details.clone(),+ payment_method_type_v2: None,+ payment_method_subtype: None,+ id: None,+ compatibility_updated_at: self.compatibility_updated_at,+ auxiliary_fingerprint_id: None,+ })+ }++ async fn convert_back(+ state: &keymanager::KeyManagerState,+ item: Self::DstType,+ key: &Secret<Vec<u8>>,+ key_manager_identifier: keymanager::Identifier,+ ) -> CustomResult<Self, ValidationError>+ where+ Self: Sized,+ {+ // Decrypt encrypted fields first+ let data = async {+ let decrypted_data = crypto_operation(+ state,+ type_name!(Self::DstType),+ CryptoOperation::BatchDecrypt(EncryptedPaymentMethod::to_encryptable(+ EncryptedPaymentMethod {+ payment_method_data: item.payment_method_data,+ payment_method_billing_address: item.payment_method_billing_address,+ network_token_payment_method_data: item.network_token_payment_method_data,+ customer_details: item.customer_details,+ network_tokenization_data: item.network_tokenization_data,+ },+ )),+ key_manager_identifier,+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_batchoperation())?;++ EncryptedPaymentMethod::from_encryptable(decrypted_data)+ .change_context(common_utils::errors::CryptoError::DecodingFailed)+ .attach_printable("Invalid batch operation data")+ }+ .await+ .change_context(ValidationError::InvalidValue {+ message: "Failed while decrypting payment method data".to_string(),+ })?;++ let vault_source_details = PaymentMethodVaultSourceDetails::try_from((+ item.vault_type,+ item.external_vault_source,+ ))?;+ let payment_method_subtype =+ item.payment_method_subtype+ .and_then(|payment_method_subtype| {+ if payment_method_subtype.eq_ignore_ascii_case("card") {+ None+ } else {+ payment_method_subtype+ .parse::<storage_enums::PaymentMethodType>()+ .map_err(|error| {+ router_env::logger::warn!(+ ?error,+ payment_method_subtype,+ "Failed to parse payment_method_subtype compatibility field"+ );+ })+ .ok()+ }+ });++ // Construct the domain type+ // Storage always has customer_id, wrap in Some for domain+ Ok(Self {+ customer_id: Some(item.customer_id),+ merchant_id: item.merchant_id,+ payment_method_id: item.payment_method_id,+ accepted_currency: item.accepted_currency,+ scheme: item.scheme,+ token: item.token,+ cardholder_name: item.cardholder_name,+ issuer_name: item.issuer_name,+ issuer_country: item.issuer_country,+ payer_country: item.payer_country,+ is_stored: item.is_stored,+ swift_code: item.swift_code,+ direct_debit_token: item.direct_debit_token,+ created_at: item.created_at,+ last_modified: item.last_modified,+ payment_method: item.payment_method.or(item.payment_method_type_v2),+ payment_method_type: item.payment_method_type.or(payment_method_subtype),+ payment_method_issuer: item.payment_method_issuer,+ payment_method_issuer_code: item.payment_method_issuer_code,+ metadata: item.metadata,+ payment_method_data: data.payment_method_data,+ locker_id: item.locker_id,+ last_used_at: item.last_used_at,+ connector_mandate_details: item.connector_mandate_details,+ customer_acceptance: item.customer_acceptance,+ status: item.status,+ network_transaction_id: item.network_transaction_id,+ network_transaction_link_id: item.network_transaction_link_id,+ client_secret: item.client_secret,+ payment_method_billing_address: data.payment_method_billing_address,+ updated_by: item.updated_by,+ version: item.version,+ network_token_requestor_reference_id: item.network_token_requestor_reference_id,+ network_token_locker_id: item.network_token_locker_id,+ network_token_payment_method_data: data.network_token_payment_method_data,+ vault_source_details,+ created_by: item+ .created_by+ .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),+ last_modified_by: item+ .last_modified_by+ .and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),+ customer_details: data.customer_details,+ locker_fingerprint_id: item.locker_fingerprint_id,+ network_tokenization_data: data.network_tokenization_data,+ storage_type: None,+ compatibility_updated_at: item.compatibility_updated_at,+ connector_payment_method_details: item.connector_payment_method_details,+ })+ }++ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {+ let (vault_type, external_vault_source) = self.vault_source_details.into();+ // Note: caller must ensure customer_id is not null before calling convert as storage model requires it.+ Ok(Self::NewDstType {+ customer_id: self.customer_id.get_required_value("customer_id")?,+ merchant_id: self.merchant_id,+ payment_method_id: self.payment_method_id,+ accepted_currency: self.accepted_currency,+ scheme: self.scheme,+ token: self.token,+ cardholder_name: self.cardholder_name,+ issuer_name: self.issuer_name,+ issuer_country: self.issuer_country,+ payer_country: self.payer_country,+ is_stored: self.is_stored,+ swift_code: self.swift_code,+ direct_debit_token: self.direct_debit_token,+ created_at: self.created_at,+ last_modified: self.last_modified,+ payment_method: self.payment_method,+ payment_method_type: self.payment_method_type,+ payment_method_issuer: self.payment_method_issuer,+ payment_method_issuer_code: self.payment_method_issuer_code,+ metadata: self.metadata,+ payment_method_data: self.payment_method_data.map(|val| val.into()),+ locker_id: self.locker_id,+ last_used_at: self.last_used_at,+ connector_mandate_details: self.connector_mandate_details,+ customer_acceptance: self.customer_acceptance,+ status: self.status,+ network_transaction_id: self.network_transaction_id,+ network_transaction_link_id: self.network_transaction_link_id,+ client_secret: self.client_secret,+ payment_method_billing_address: self+ .payment_method_billing_address+ .map(|val| val.into()),+ updated_by: self.updated_by,+ version: self.version,+ network_token_requestor_reference_id: self.network_token_requestor_reference_id,+ network_token_locker_id: self.network_token_locker_id,+ network_token_payment_method_data: self+ .network_token_payment_method_data+ .map(|val| val.into()),+ external_vault_source,+ vault_type,+ created_by: self.created_by.map(|created_by| created_by.to_string()),+ last_modified_by: self+ .last_modified_by+ .map(|last_modified_by| last_modified_by.to_string()),+ customer_details: self.customer_details.map(|val| val.into()),+ locker_fingerprint_id: self.locker_fingerprint_id,+ network_tokenization_data: self.network_tokenization_data.map(|val| val.into()),+ connector_payment_method_details: self.connector_payment_method_details.clone(),+ id: None,+ compatibility_updated_at: self.compatibility_updated_at,+ auxiliary_fingerprint_id: None,+ })+ }+}++#[cfg(feature = "v2")]+#[async_trait::async_trait]+impl Conversion for hyperswitch_domain_models::payment_methods::PaymentMethod {+ type DstType = PaymentMethod;+ type NewDstType = diesel_models::payment_method::PaymentMethodNew;+ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {+ let payment_method_id = self.id.get_string_repr().to_owned();+ Ok(Self::DstType {+ customer_id: self.customer_id,+ merchant_id: self.merchant_id,+ id: self.id,+ payment_method_id: Some(payment_method_id),+ created_at: self.created_at,+ last_modified: self.last_modified,+ payment_method: None,+ payment_method_type: None,+ payment_method_type_v2: self.payment_method_type,+ payment_method_subtype: self.payment_method_subtype,+ payment_method_data: self.payment_method_data.map(|val| val.into()),+ locker_id: self.locker_id.map(|id| id.get_string_repr().clone()),+ last_used_at: self.last_used_at,+ connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()),+ customer_acceptance: self.customer_acceptance,+ status: self.status,+ network_transaction_id: self.network_transaction_id.map(Secret::new),+ network_transaction_link_id: self.network_transaction_link_id.map(Secret::new),+ client_secret: self.client_secret,+ payment_method_billing_address: self+ .payment_method_billing_address+ .map(|val| val.into()),+ updated_by: self.updated_by,+ locker_fingerprint_id: self.locker_fingerprint_id,+ version: self.version,+ network_token_requestor_reference_id: self.network_token_requestor_reference_id,+ network_token_locker_id: self.network_token_locker_id,+ network_token_payment_method_data: self+ .network_token_payment_method_data+ .map(|val| val.into()),+ external_vault_source: self.external_vault_source,+ external_vault_token_data: self.external_vault_token_data.map(|val| val.into()),+ vault_type: self.vault_type,+ created_by: self.created_by.map(|created_by| created_by.to_string()),+ last_modified_by: self+ .last_modified_by+ .map(|last_modified_by| last_modified_by.to_string()),+ customer_details: self.customer_details.map(|val| val.into()),+ network_tokenization_data: self.network_tokenization_data.map(|val| val.into()),+ auxiliary_fingerprint_id: self.auxiliary_fingerprint_id,+ compatibility_updated_at: self.compatibility_updated_at,+ connector_payment_method_details: None,+ })+ }++ async fn convert_back(+ state: &keymanager::KeyManagerState,+ storage_model: Self::DstType,+ key: &Secret<Vec<u8>>,+ key_manager_identifier: keymanager::Identifier,+ ) -> CustomResult<Self, ValidationError>+ where+ Self: Sized,+ {+ use common_utils::ext_traits::ValueExt;++ async {+ let decrypted_data = crypto_operation(+ state,+ type_name!(Self::DstType),+ CryptoOperation::BatchDecrypt(EncryptedPaymentMethod::to_encryptable(+ EncryptedPaymentMethod {+ payment_method_data: storage_model.payment_method_data,+ payment_method_billing_address: storage_model+ .payment_method_billing_address,+ network_token_payment_method_data: storage_model+ .network_token_payment_method_data,+ external_vault_token_data: storage_model.external_vault_token_data,+ customer_details: storage_model.customer_details,+ network_tokenization_data: storage_model.network_tokenization_data,+ },+ )),+ key_manager_identifier,+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_batchoperation())?;++ let data = EncryptedPaymentMethod::from_encryptable(decrypted_data)+ .change_context(common_utils::errors::CryptoError::DecodingFailed)+ .attach_printable("Invalid batch operation data")?;++ let payment_method_billing_address = data+ .payment_method_billing_address+ .map(|billing| {+ billing.deserialize_inner_value(|value| value.parse_value("Address"))+ })+ .transpose()+ .change_context(common_utils::errors::CryptoError::DecodingFailed)+ .attach_printable("Error while deserializing Address")?;++ let payment_method_data = data+ .payment_method_data+ .map(|payment_method_data| {+ payment_method_data+ .deserialize_inner_value(|value| value.parse_value("Payment Method Data"))+ })+ .transpose()+ .change_context(common_utils::errors::CryptoError::DecodingFailed)+ .attach_printable("Error while deserializing Payment Method Data")?;++ let network_token_payment_method_data = data+ .network_token_payment_method_data+ .map(|network_token_payment_method_data| {+ network_token_payment_method_data.deserialize_inner_value(|value| {+ value.parse_value("Network token Payment Method Data")+ })+ })+ .transpose()+ .change_context(common_utils::errors::CryptoError::DecodingFailed)+ .attach_printable("Error while deserializing Network token Payment Method Data")?;++ let customer_details = data+ .customer_details+ .map(|customer_details| {+ customer_details.deserialize_inner_value(|value| {+ value.parse_value("Payment Method Customer Details")+ })+ })+ .transpose()+ .change_context(common_utils::errors::CryptoError::DecodingFailed)+ .attach_printable("Error while deserializing Payment Method Customer Details")?;++ let external_vault_token_data = data+ .external_vault_token_data+ .map(|external_vault_token_data| {+ external_vault_token_data.deserialize_inner_value(|value| {+ value.parse_value("External Vault Token Data")+ })+ })+ .transpose()+ .change_context(common_utils::errors::CryptoError::DecodingFailed)+ .attach_printable("Error while deserializing External Vault Token Data")?;++ let network_tokenization_data = data+ .network_tokenization_data+ .map(|tokenization_data| {+ tokenization_data.deserialize_inner_value(|value| {+ value.parse_value("Network Tokenization Data")+ })+ })+ .transpose()+ .change_context(common_utils::errors::CryptoError::DecodingFailed)+ .attach_printable("Error while deserializing Network Tokenization Data")?;++ Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {+ customer_id: storage_model.customer_id,+ merchant_id: storage_model.merchant_id,+ id: storage_model.id,+ created_at: storage_model.created_at,+ last_modified: storage_model.last_modified,+ payment_method_type: storage_model.payment_method_type_v2,+ payment_method_subtype: storage_model.payment_method_subtype,+ payment_method_data,+ locker_id: storage_model+ .locker_id+ .map(hyperswitch_domain_models::payment_methods::VaultId::generate),+ last_used_at: storage_model.last_used_at,+ connector_mandate_details: storage_model.connector_mandate_details.map(From::from),+ customer_acceptance: storage_model.customer_acceptance,+ status: storage_model.status,+ network_transaction_id: storage_model+ .network_transaction_id+ .map(ExposeInterface::expose),+ client_secret: storage_model.client_secret,+ payment_method_billing_address,+ updated_by: storage_model.updated_by,+ locker_fingerprint_id: storage_model.locker_fingerprint_id,+ version: storage_model.version,+ network_token_requestor_reference_id: storage_model+ .network_token_requestor_reference_id,+ network_token_locker_id: storage_model.network_token_locker_id,+ network_token_payment_method_data,+ external_vault_source: storage_model.external_vault_source,+ external_vault_token_data,+ vault_type: storage_model.vault_type,+ created_by: storage_model+ .created_by+ .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),+ last_modified_by: storage_model+ .last_modified_by+ .and_then(|last_modified_by| last_modified_by.parse::<CreatedBy>().ok()),+ customer_details,+ network_tokenization_data,+ network_transaction_link_id: storage_model+ .network_transaction_link_id+ .map(ExposeInterface::expose),+ auxiliary_fingerprint_id: storage_model.auxiliary_fingerprint_id,+ compatibility_updated_at: storage_model.compatibility_updated_at,+ })+ }+ .await+ .change_context(ValidationError::InvalidValue {+ message: "Failed while decrypting payment method data".to_string(),+ })+ }++ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {+ let payment_method_id = self.id.get_string_repr().to_owned();+ Ok(Self::NewDstType {+ customer_id: self.customer_id,+ merchant_id: self.merchant_id,+ id: self.id,+ payment_method_id: Some(payment_method_id),+ created_at: self.created_at,+ last_modified: self.last_modified,+ payment_method: None,+ payment_method_type: None,+ payment_method_type_v2: self.payment_method_type,+ payment_method_subtype: self.payment_method_subtype,+ payment_method_data: self.payment_method_data.map(|val| val.into()),+ locker_id: self.locker_id.map(|id| id.get_string_repr().clone()),+ last_used_at: self.last_used_at,+ connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()),+ customer_acceptance: self.customer_acceptance,+ status: self.status,+ network_transaction_id: self.network_transaction_id,+ network_transaction_link_id: self.network_transaction_link_id,+ client_secret: self.client_secret,+ payment_method_billing_address: self+ .payment_method_billing_address+ .map(|val| val.into()),+ updated_by: self.updated_by,+ locker_fingerprint_id: self.locker_fingerprint_id,+ version: self.version,+ network_token_requestor_reference_id: self.network_token_requestor_reference_id,+ network_token_locker_id: self.network_token_locker_id,+ network_token_payment_method_data: self+ .network_token_payment_method_data+ .map(|val| val.into()),+ external_vault_token_data: self.external_vault_token_data.map(|val| val.into()),+ vault_type: self.vault_type,+ created_by: self.created_by.map(|created_by| created_by.to_string()),+ last_modified_by: self+ .last_modified_by+ .map(|last_modified_by| last_modified_by.to_string()),+ customer_details: self.customer_details.map(|val| val.into()),+ compatibility_updated_at: self.compatibility_updated_at,+ external_vault_source: self.external_vault_source,+ auxiliary_fingerprint_id: self.auxiliary_fingerprint_id,+ })+ }+}++#[cfg(feature = "v2")]+#[async_trait::async_trait]+impl Conversion for hyperswitch_domain_models::payment_methods::PaymentMethodSession {+ type DstType = diesel_models::payment_methods_session::PaymentMethodSession;+ type NewDstType = diesel_models::payment_methods_session::PaymentMethodSession;+ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {+ Ok(Self::DstType {+ id: self.id,+ customer_id: self.customer_id,+ billing: self.billing.map(|val| val.into()),+ psp_tokenization: self.psp_tokenization,+ network_tokenization: self.network_tokenization,+ tokenization_data: self.tokenization_data,+ expires_at: self.expires_at,+ associated_payment_methods: self.associated_payment_methods,+ associated_payment: self.associated_payment,+ return_url: self.return_url,+ associated_token_id: self.associated_token_id,+ storage_type: self.storage_type,+ keep_alive: self.keep_alive,+ })+ }++ async fn convert_back(+ state: &keymanager::KeyManagerState,+ storage_model: Self::DstType,+ key: &Secret<Vec<u8>>,+ key_manager_identifier: keymanager::Identifier,+ ) -> CustomResult<Self, ValidationError>+ where+ Self: Sized,+ {+ use common_utils::ext_traits::ValueExt;++ async {+ let decrypted_data = crypto_operation(+ state,+ type_name!(Self::DstType),+ CryptoOperation::BatchDecrypt(EncryptedPaymentMethodSession::to_encryptable(+ EncryptedPaymentMethodSession {+ billing: storage_model.billing,+ },+ )),+ key_manager_identifier,+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_batchoperation())?;++ let data = EncryptedPaymentMethodSession::from_encryptable(decrypted_data)+ .change_context(common_utils::errors::CryptoError::DecodingFailed)+ .attach_printable("Invalid batch operation data")?;++ let billing = data+ .billing+ .map(|billing| {+ billing.deserialize_inner_value(|value| value.parse_value("Address"))+ })+ .transpose()+ .change_context(common_utils::errors::CryptoError::DecodingFailed)+ .attach_printable("Error while deserializing Address")?;++ Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {+ id: storage_model.id,+ customer_id: storage_model.customer_id,+ billing,+ psp_tokenization: storage_model.psp_tokenization,+ network_tokenization: storage_model.network_tokenization,+ tokenization_data: storage_model.tokenization_data,+ expires_at: storage_model.expires_at,+ associated_payment_methods: storage_model.associated_payment_methods,+ associated_payment: storage_model.associated_payment,+ return_url: storage_model.return_url,+ associated_token_id: storage_model.associated_token_id,+ storage_type: storage_model.storage_type,+ keep_alive: storage_model.keep_alive,+ })+ }+ .await+ .change_context(ValidationError::InvalidValue {+ message: "Failed while decrypting payment method data".to_string(),+ })+ }++ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {+ Ok(Self::NewDstType {+ id: self.id,+ customer_id: self.customer_id,+ billing: self.billing.map(|val| val.into()),+ psp_tokenization: self.psp_tokenization,+ network_tokenization: self.network_tokenization,+ tokenization_data: self.tokenization_data,+ expires_at: self.expires_at,+ associated_payment_methods: self.associated_payment_methods,+ associated_payment: self.associated_payment,+ return_url: self.return_url,+ associated_token_id: self.associated_token_id,+ storage_type: self.storage_type,+ keep_alive: self.keep_alive,+ })+ }+}diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rsindex 3f702b7e99..2daa5896dc 100644--- a/crates/storage_impl/src/payments/payment_attempt.rs+++ b/crates/storage_impl/src/payments/payment_attempt.rs@@ -1,6 +1,8 @@#[cfg(feature = "v1")]use common_utils::fallback_reverse_lookup_not_found;use common_utils::{errors::CustomResult, ext_traits::AsyncExt};+#[cfg(feature = "v2")]+use diesel_models::payment_attempt::PaymentAttemptNew as DieselPaymentAttemptNew;use diesel_models::{enums::{MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType,@@ -12,10 +14,9 @@ use diesel_models::{use error_stack::ResultExt;#[cfg(all(feature = "v1", feature = "olap"))]use futures::future::{try_join_all, FutureExt};-#[cfg(feature = "v2")]-use hyperswitch_domain_models::behaviour::ReverseConversion;+#[cfg(feature = "v1")]+use hyperswitch_domain_models::behaviour::Conversion;use hyperswitch_domain_models::{- behaviour::Conversion,mandates::{MandateAmountData, MandateDataType, MandateDetails},merchant_key_store::MerchantKeyStore,payments::payment_attempt::{PaymentAttempt, PaymentAttemptInterface, PaymentAttemptUpdate},@@ -29,6 +30,8 @@ use label::*;use redis_interface::HsetnxReply;use router_env::{instrument, tracing};+#[cfg(feature = "v2")]+use crate::behaviour::{Conversion, ReverseConversion};#[cfg(feature = "v2")]use crate::kv_router_store::{FilterResourceParams, FindResourceBy, UpdateResourceParams};use crate::{@@ -2078,3 +2081,521 @@ mod label {format!("attempt_global_id_{}", attempt_id.get_string_repr())}}++#[cfg(feature = "v2")]+use common_utils::{+ errors::ValidationError,+ ext_traits::ValueExt,+ types::{+ keymanager::{self, ToEncryptable},+ ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy,+ },+};+#[cfg(feature = "v2")]+use hyperswitch_domain_models::{+ payments::payment_attempt::{+ AttemptAmountDetails, AttemptAmountDetailsSetter, EncryptedPaymentAttempt, ErrorDetails,+ },+ type_encryption::{crypto_operation, CryptoOperation},+};+#[cfg(feature = "v2")]+use hyperswitch_masking::{PeekInterface, Secret};++#[cfg(feature = "v2")]+use crate::KeyManagerState;++#[cfg(feature = "v2")]+#[async_trait::async_trait]+impl Conversion for PaymentAttempt {+ type DstType = DieselPaymentAttempt;+ type NewDstType = DieselPaymentAttemptNew;++ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {+ use common_utils::encryption::Encryption;++ let card_network = self+ .payment_method_data+ .as_ref()+ .and_then(|data| data.peek().as_object())+ .and_then(|card| card.get("card"))+ .and_then(|data| data.as_object())+ .and_then(|card| card.get("card_network"))+ .and_then(|network| network.as_str())+ .map(|network| network.to_string());++ let Self {+ payment_id,+ merchant_id,+ attempts_group_id,+ status,+ error,+ amount_details,+ authentication_type,+ created_at,+ modified_at,+ last_synced,+ cancellation_reason,+ browser_info,+ payment_token,+ connector_metadata,+ payment_experience,+ payment_method_data,+ routing_result,+ preprocessing_step_id,+ multiple_capture_count,+ connector_response_reference_id,+ updated_by,+ redirection_data,+ encoded_data,+ merchant_connector_id,+ external_three_ds_authentication_attempted,+ external_threeds_authentication_type,+ authentication_connector,+ authentication_id,+ fingerprint_id,+ client_source,+ client_version,+ customer_acceptance,+ profile_id,+ organization_id,+ payment_method_type,+ connector_payment_id,+ payment_method_subtype,+ authentication_applied,+ external_reference_id,+ id,+ payment_method_id,+ payment_method_billing_address,+ connector,+ connector_token_details,+ card_discovery,+ charges,+ feature_metadata,+ processor_merchant_id,+ created_by,+ connector_request_reference_id,+ network_transaction_id,+ network_transaction_link_id,+ authorized_amount,+ external_surcharge_details,+ applied_offer_details,+ } = self;++ let net_amount = amount_details.get_net_amount();+ let tax_on_surcharge = amount_details.get_tax_on_surcharge();+ let surcharge_amount = amount_details.get_surcharge_amount();+ let order_tax_amount = amount_details.get_order_tax_amount();+ let shipping_cost = amount_details.get_shipping_cost();+ let amount_capturable = amount_details.get_amount_capturable();+ let amount_to_capture = amount_details.get_amount_to_capture();+ let amount_captured = amount_details.get_amount_captured();++ let (connector_payment_id, connector_payment_data) = connector_payment_id+ .map(ConnectorTransactionId::form_id_and_data)+ .map(|(txn_id, txn_data)| (Some(txn_id), txn_data))+ .unwrap_or((None, None));+ let feature_metadata = feature_metadata.as_ref().map(From::from);++ Ok(DieselPaymentAttempt {+ payment_id,+ merchant_id,+ id,+ status,+ error_message: error.as_ref().map(|details| details.message.clone()),+ payment_method_id,+ payment_method_type_v2: payment_method_type,+ connector_payment_id,+ authentication_type,+ created_at,+ modified_at,+ last_synced,+ cancellation_reason,+ amount_to_capture,+ browser_info,+ error_code: error.as_ref().map(|details| details.code.clone()),+ payment_token,+ connector_metadata,+ payment_experience,+ payment_method_subtype,+ payment_method_data,+ preprocessing_step_id,+ error_reason: error.as_ref().and_then(|details| details.reason.clone()),+ multiple_capture_count,+ connector_response_reference_id,+ amount_capturable,+ updated_by,+ merchant_connector_id,+ redirection_data: redirection_data.map(From::from),+ encoded_data,+ unified_code: error+ .as_ref()+ .and_then(|details| details.unified_code.clone()),+ unified_message: error+ .as_ref()+ .and_then(|details| details.unified_message.clone()),+ net_amount,+ external_three_ds_authentication_attempted,+ external_threeds_authentication_type,+ authentication_connector,+ authentication_id,+ fingerprint_id,+ client_source,+ client_version,+ customer_acceptance,+ profile_id,+ organization_id,+ card_network,+ order_tax_amount,+ shipping_cost,+ routing_result,+ authentication_applied,+ external_reference_id,+ connector,+ surcharge_amount,+ tax_on_surcharge,+ payment_method_billing_address: payment_method_billing_address.map(Encryption::from),+ connector_payment_data,+ connector_token_details,+ card_discovery,+ request_extended_authorization: None,+ extended_authorization_applied: None,+ extended_authorization_last_applied_at: None,+ capture_before: None,+ charges,+ feature_metadata,+ network_advice_code: error+ .as_ref()+ .and_then(|details| details.network_advice_code.clone()),+ network_decline_code: error+ .as_ref()+ .and_then(|details| details.network_decline_code.clone()),+ network_error_message: error+ .as_ref()+ .and_then(|details| details.network_error_message.clone()),+ processor_merchant_id: Some(processor_merchant_id),+ created_by: created_by.map(|created_by| created_by.to_string()),+ connector_request_reference_id,+ network_transaction_id,+ network_transaction_link_id,+ is_overcapture_enabled: None,+ network_details: None,+ attempts_group_id,+ is_stored_credential: None,+ authorized_amount,+ tokenization: None,+ amount_captured,+ encrypted_payment_method_data: None,+ error_details: None,+ retry_type: None,+ installment_data: None,+ external_surcharge_details: None,+ applied_offer_details,+ sender_payment_instrument_id: None,+ })+ }++ async fn convert_back(+ state: &KeyManagerState,+ storage_model: Self::DstType,+ key: &Secret<Vec<u8>>,+ key_manager_identifier: keymanager::Identifier,+ ) -> CustomResult<Self, ValidationError>+ where+ Self: Sized,+ {+ async {+ let connector_payment_id = storage_model+ .get_optional_connector_transaction_id()+ .cloned();++ let decrypted_data = crypto_operation(+ state,+ common_utils::type_name!(Self::DstType),+ CryptoOperation::BatchDecrypt(EncryptedPaymentAttempt::to_encryptable(+ EncryptedPaymentAttempt {+ payment_method_billing_address: storage_model+ .payment_method_billing_address,+ },+ )),+ key_manager_identifier,+ key.peek(),+ )+ .await+ .and_then(|val| val.try_into_batchoperation())?;++ let decrypted_data = EncryptedPaymentAttempt::from_encryptable(decrypted_data)+ .change_context(common_utils::errors::CryptoError::DecodingFailed)+ .attach_printable("Invalid batch operation data")?;++ let payment_method_billing_address = decrypted_data+ .payment_method_billing_address+ .map(|billing| {+ billing.deserialize_inner_value(|value| value.parse_value("Address"))+ })+ .transpose()+ .change_context(common_utils::errors::CryptoError::DecodingFailed)+ .attach_printable("Error while deserializing Address")?;++ let amount_details = AttemptAmountDetailsSetter {+ net_amount: storage_model.net_amount,+ tax_on_surcharge: storage_model.tax_on_surcharge,+ surcharge_amount: storage_model.surcharge_amount,+ order_tax_amount: storage_model.order_tax_amount,+ shipping_cost: storage_model.shipping_cost,+ amount_capturable: storage_model.amount_capturable,+ amount_to_capture: storage_model.amount_to_capture,+ amount_captured: storage_model.amount_captured,+ };++ let error = storage_model+ .error_code+ .zip(storage_model.error_message)+ .map(|(error_code, error_message)| ErrorDetails {+ code: error_code,+ message: error_message,+ reason: storage_model.error_reason,+ unified_code: storage_model.unified_code,+ unified_message: storage_model.unified_message,+ network_advice_code: storage_model.network_advice_code,+ network_decline_code: storage_model.network_decline_code,+ network_error_message: storage_model.network_error_message,+ });++ Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {+ payment_id: storage_model.payment_id,+ merchant_id: storage_model.merchant_id.clone(),+ attempts_group_id: storage_model.attempts_group_id,+ id: storage_model.id,+ status: storage_model.status,+ amount_details: amount_details.into(),+ error,+ payment_method_id: storage_model.payment_method_id,+ payment_method_type: storage_model.payment_method_type_v2,+ connector_payment_id,+ authentication_type: storage_model.authentication_type,+ created_at: storage_model.created_at,+ modified_at: storage_model.modified_at,+ last_synced: storage_model.last_synced,+ cancellation_reason: storage_model.cancellation_reason,+ browser_info: storage_model.browser_info,+ payment_token: storage_model.payment_token,+ connector_metadata: storage_model.connector_metadata,+ payment_experience: storage_model.payment_experience,+ payment_method_data: storage_model.payment_method_data,+ routing_result: storage_model.routing_result,+ preprocessing_step_id: storage_model.preprocessing_step_id,+ multiple_capture_count: storage_model.multiple_capture_count,+ connector_response_reference_id: storage_model.connector_response_reference_id,+ updated_by: storage_model.updated_by,+ redirection_data: storage_model.redirection_data.map(From::from),+ encoded_data: storage_model.encoded_data,+ merchant_connector_id: storage_model.merchant_connector_id,+ external_three_ds_authentication_attempted: storage_model+ .external_three_ds_authentication_attempted,+ authentication_connector: storage_model.authentication_connector,+ authentication_id: storage_model.authentication_id,+ fingerprint_id: storage_model.fingerprint_id,+ charges: storage_model.charges,+ client_source: storage_model.client_source,+ client_version: storage_model.client_version,+ customer_acceptance: storage_model.customer_acceptance,+ profile_id: storage_model.profile_id,+ organization_id: storage_model.organization_id,+ payment_method_subtype: storage_model.payment_method_subtype,+ authentication_applied: storage_model.authentication_applied,+ external_reference_id: storage_model.external_reference_id,+ connector: storage_model.connector,+ payment_method_billing_address,+ connector_token_details: storage_model.connector_token_details,+ card_discovery: storage_model.card_discovery,+ feature_metadata: storage_model.feature_metadata.map(From::from),+ processor_merchant_id: storage_model+ .processor_merchant_id+ .unwrap_or(storage_model.merchant_id),+ created_by: storage_model+ .created_by+ .and_then(|created_by| created_by.parse::<CreatedBy>().ok()),+ connector_request_reference_id: storage_model.connector_request_reference_id,+ network_transaction_id: storage_model.network_transaction_id,+ network_transaction_link_id: storage_model.network_transaction_link_id,+ authorized_amount: storage_model.authorized_amount,+ external_threeds_authentication_type: storage_model+ .external_threeds_authentication_type,+ external_surcharge_details: storage_model.external_surcharge_details,+ applied_offer_details: storage_model.applied_offer_details,+ })+ }+ .await+ .change_context(ValidationError::InvalidValue {+ message: "Failed while decrypting payment attempt".to_string(),+ })+ }++ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {+ use common_utils::encryption::Encryption;+ let Self {+ payment_id,+ merchant_id,+ attempts_group_id,+ status,+ error,+ amount_details,+ authentication_type,+ created_at,+ modified_at,+ last_synced,+ cancellation_reason,+ browser_info,+ payment_token,+ connector_metadata,+ payment_experience,+ payment_method_data,+ routing_result: _,+ preprocessing_step_id,+ multiple_capture_count,+ connector_response_reference_id,+ updated_by,+ redirection_data,+ encoded_data,+ merchant_connector_id,+ external_three_ds_authentication_attempted,+ external_threeds_authentication_type,+ authentication_connector,+ authentication_id,+ fingerprint_id,+ client_source,+ client_version,+ customer_acceptance,+ profile_id,+ organization_id,+ payment_method_type,+ connector_payment_id,+ payment_method_subtype,+ authentication_applied: _,+ external_reference_id: _,+ id,+ payment_method_id,+ payment_method_billing_address,+ connector,+ connector_token_details,+ card_discovery,+ charges,+ feature_metadata,+ processor_merchant_id,+ created_by,+ connector_request_reference_id,+ network_transaction_id,+ network_transaction_link_id,+ authorized_amount,+ external_surcharge_details: _,+ applied_offer_details: _,+ } = self;++ let card_network = payment_method_data+ .as_ref()+ .and_then(|data| data.peek().as_object())+ .and_then(|card| card.get("card"))+ .and_then(|data| data.as_object())+ .and_then(|card| card.get("card_network"))+ .and_then(|network| network.as_str())+ .map(|network| network.to_string());++ let error_details = error;++ Ok(DieselPaymentAttemptNew {+ payment_id,+ merchant_id,+ status,+ network_transaction_id,+ network_transaction_link_id,+ error_message: error_details+ .as_ref()+ .map(|details| details.message.clone()),+ surcharge_amount: amount_details.get_surcharge_amount(),+ tax_on_surcharge: amount_details.get_tax_on_surcharge(),+ payment_method_id,+ authentication_type,+ created_at,+ modified_at,+ last_synced,+ cancellation_reason,+ browser_info,+ payment_token,+ error_code: error_details.as_ref().map(|details| details.code.clone()),+ connector_metadata,+ payment_experience,+ payment_method_data,+ preprocessing_step_id,+ error_reason: error_details+ .as_ref()+ .and_then(|details| details.reason.clone()),+ connector_response_reference_id,+ multiple_capture_count,+ amount_capturable: amount_details.get_amount_capturable(),+ updated_by,+ merchant_connector_id,+ redirection_data: redirection_data.map(From::from),+ encoded_data,+ unified_code: error_details+ .as_ref()+ .and_then(|details| details.unified_code.clone()),+ unified_message: error_details+ .as_ref()+ .and_then(|details| details.unified_message.clone()),+ net_amount: amount_details.get_net_amount(),+ external_three_ds_authentication_attempted,+ external_threeds_authentication_type,+ authentication_connector,+ authentication_id,+ fingerprint_id,+ client_source,+ client_version,+ customer_acceptance,+ profile_id,+ organization_id,+ card_network,+ order_tax_amount: amount_details.get_order_tax_amount(),+ shipping_cost: amount_details.get_shipping_cost(),+ amount_to_capture: amount_details.get_amount_to_capture(),+ payment_method_billing_address: payment_method_billing_address.map(Encryption::from),+ payment_method_subtype,+ connector_payment_id: connector_payment_id+ .as_ref()+ .map(|txn_id| ConnectorTransactionId::TxnId(txn_id.clone())),+ payment_method_type_v2: payment_method_type,+ id,+ charges,+ connector_token_details,+ card_discovery,+ extended_authorization_applied: None,+ request_extended_authorization: None,+ extended_authorization_last_applied_at: None,+ capture_before: None,+ feature_metadata: feature_metadata.as_ref().map(From::from),+ connector,+ network_advice_code: error_details+ .as_ref()+ .and_then(|details| details.network_advice_code.clone()),+ network_decline_code: error_details+ .as_ref()+ .and_then(|details| details.network_decline_code.clone()),+ network_error_message: error_details+ .as_ref()+ .and_then(|details| details.network_error_message.clone()),+ processor_merchant_id: Some(processor_merchant_id),+ created_by: created_by.map(|created_by| created_by.to_string()),+ connector_request_reference_id,+ network_details: None,+ tokenization: None,+ attempts_group_id,+ is_stored_credential: None,+ authorized_amount,+ amount_captured: amount_details.get_amount_captured(),+ encrypted_payment_method_data: None,+ error_details: None,+ retry_type: None,+ external_surcharge_details: None,+ applied_offer_details: None,+ })+ }+}diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rsindex e09ce797e6..1752ce0d4b 100644--- a/crates/storage_impl/src/payments/payment_intent.rs+++ b/crates/storage_impl/src/payments/payment_intent.rs@@ -100,7 +100,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {.clone().generate_drainer_insert_query(&mut query_gen_conn);- Box::pin(self.insert_resource(+ Box::pin(self.insert_resource_old(merchant_key_store,storage_scheme,new_payment_intent.insert(&conn),@@ -249,7 +249,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {origin_diesel_intent.processor_merchant_id.clone(),);- Box::pin(self.update_resource(+ Box::pin(self.update_resource_old(merchant_key_store,storage_scheme,origin_diesel_intent.update(&conn, diesel_intent_update),@@ -350,7 +350,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {storage_scheme: MerchantStorageScheme,) -> error_stack::Result<PaymentIntent, StorageError> {let conn = pg_connection_read(self).await?;- Box::pin(self.find_resource_by_id(+ Box::pin(self.find_resource_by_id_old(merchant_key_store,storage_scheme,DieselPaymentIntent::find_by_payment_id_processor_merchant_id(@@ -1392,6 +1392,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {.get_keymanager_state().attach_printable("Missing KeyManagerState")?;+ use crate::behaviour::Conversion;query.get_results_async::<(DieselPaymentIntent,