repo
stringclasses
4 values
file_path
stringlengths
6
193
extension
stringclasses
23 values
content
stringlengths
0
1.73M
token_count
int64
0
724k
__index_level_0__
int64
0
10.8k
hyperswitch
crates/router/src/types/api/refunds.rs
.rs
pub use api_models::refunds::{ RefundRequest, RefundResponse, RefundStatus, RefundType, RefundUpdateRequest, RefundsRetrieveRequest, }; pub use hyperswitch_domain_models::router_flow_types::refunds::{Execute, RSync}; pub use hyperswitch_interfaces::api::refunds::{Refund, RefundExecute, RefundSync}; use crate::types::{storage::enums as storage_enums, transformers::ForeignFrom}; impl ForeignFrom<storage_enums::RefundStatus> for RefundStatus { fn foreign_from(status: storage_enums::RefundStatus) -> Self { match status { storage_enums::RefundStatus::Failure | storage_enums::RefundStatus::TransactionFailure => Self::Failed, storage_enums::RefundStatus::ManualReview => Self::Review, storage_enums::RefundStatus::Pending => Self::Pending, storage_enums::RefundStatus::Success => Self::Succeeded, } } }
214
1,405
hyperswitch
crates/router/src/types/api/fraud_check.rs
.rs
use std::str::FromStr; use api_models::enums; use common_utils::errors::CustomResult; use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::fraud_check::{ Checkout, Fulfillment, RecordReturn, Sale, Transaction, }; pub use hyperswitch_interfaces::api::fraud_check::{ FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale, FraudCheckTransaction, }; pub use super::fraud_check_v2::{ FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2, FraudCheckTransactionV2, FraudCheckV2, }; use super::{ConnectorData, SessionConnectorDatas}; use crate::{connector, core::errors, services::connector_integration_interface::ConnectorEnum}; #[derive(Clone)] pub struct FraudCheckConnectorData { pub connector: ConnectorEnum, pub connector_name: enums::FrmConnectors, } pub enum ConnectorCallType { PreDetermined(ConnectorData), Retryable(Vec<ConnectorData>), SessionMultiple(SessionConnectorDatas), } impl FraudCheckConnectorData { pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> { let connector_name = enums::FrmConnectors::from_str(name) .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven) .attach_printable_lazy(|| { format!("unable to parse connector: {:?}", name.to_string()) })?; let connector = Self::convert_connector(connector_name)?; Ok(Self { connector, connector_name, }) } fn convert_connector( connector_name: enums::FrmConnectors, ) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> { match connector_name { enums::FrmConnectors::Signifyd => { Ok(ConnectorEnum::Old(Box::new(&connector::Signifyd))) } enums::FrmConnectors::Riskified => { Ok(ConnectorEnum::Old(Box::new(connector::Riskified::new()))) } } } }
454
1,406
hyperswitch
crates/router/src/types/api/admin.rs
.rs
use std::collections::HashMap; #[cfg(feature = "v2")] pub use api_models::admin; pub use api_models::{ admin::{ MaskedHeaders, MerchantAccountCreate, MerchantAccountDeleteResponse, MerchantAccountResponse, MerchantAccountUpdate, MerchantConnectorCreate, MerchantConnectorDeleteResponse, MerchantConnectorDetails, MerchantConnectorDetailsWrap, MerchantConnectorId, MerchantConnectorResponse, MerchantDetails, MerchantId, PaymentMethodsEnabled, ProfileCreate, ProfileResponse, ProfileUpdate, ToggleAllKVRequest, ToggleAllKVResponse, ToggleKVRequest, ToggleKVResponse, WebhookDetails, }, organization::{ OrganizationCreateRequest, OrganizationId, OrganizationResponse, OrganizationUpdateRequest, }, }; use common_utils::{ext_traits::ValueExt, types::keymanager as km_types}; use diesel_models::organization::OrganizationBridge; use error_stack::ResultExt; use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; use masking::{ExposeInterface, PeekInterface, Secret}; use crate::{ consts, core::errors, routes::SessionState, types::{ domain::{ self, types::{self as domain_types, AsyncLift}, }, transformers::{ForeignInto, ForeignTryFrom}, ForeignFrom, }, utils, }; impl ForeignFrom<diesel_models::organization::Organization> for OrganizationResponse { fn foreign_from(org: diesel_models::organization::Organization) -> Self { Self { #[cfg(feature = "v2")] id: org.get_organization_id(), #[cfg(feature = "v1")] organization_id: org.get_organization_id(), organization_name: org.get_organization_name(), organization_details: org.organization_details, metadata: org.metadata, modified_at: org.modified_at, created_at: org.created_at, } } } #[cfg(feature = "v1")] impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse { type Error = error_stack::Report<errors::ParsingError>; fn foreign_try_from(item: domain::MerchantAccount) -> Result<Self, Self::Error> { let merchant_id = item.get_id().to_owned(); let primary_business_details: Vec<api_models::admin::PrimaryBusinessDetails> = item .primary_business_details .parse_value("primary_business_details")?; let pm_collect_link_config: Option<api_models::admin::BusinessCollectLinkConfig> = item .pm_collect_link_config .map(|config| config.parse_value("pm_collect_link_config")) .transpose()?; Ok(Self { merchant_id, merchant_name: item.merchant_name, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, merchant_details: item.merchant_details, webhook_details: item.webhook_details.clone().map(ForeignInto::foreign_into), routing_algorithm: item.routing_algorithm, sub_merchants_enabled: item.sub_merchants_enabled, parent_merchant_id: item.parent_merchant_id, publishable_key: Some(item.publishable_key), metadata: item.metadata, locker_id: item.locker_id, primary_business_details, frm_routing_algorithm: item.frm_routing_algorithm, #[cfg(feature = "payouts")] payout_routing_algorithm: item.payout_routing_algorithm, organization_id: item.organization_id, is_recon_enabled: item.is_recon_enabled, default_profile: item.default_profile, recon_status: item.recon_status, pm_collect_link_config, product_type: item.product_type, }) } } #[cfg(feature = "v2")] impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse { type Error = error_stack::Report<errors::ValidationError>; fn foreign_try_from(item: domain::MerchantAccount) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let id = item.get_id().to_owned(); let merchant_name = item .merchant_name .get_required_value("merchant_name")? .into_inner(); Ok(Self { id, merchant_name, merchant_details: item.merchant_details, publishable_key: item.publishable_key, metadata: item.metadata, organization_id: item.organization_id, recon_status: item.recon_status, product_type: item.product_type, }) } } #[cfg(feature = "v1")] impl ForeignTryFrom<domain::Profile> for ProfileResponse { type Error = error_stack::Report<errors::ParsingError>; fn foreign_try_from(item: domain::Profile) -> Result<Self, Self::Error> { let profile_id = item.get_id().to_owned(); let outgoing_webhook_custom_http_headers = item .outgoing_webhook_custom_http_headers .map(|headers| { headers .into_inner() .expose() .parse_value::<HashMap<String, Secret<String>>>( "HashMap<String, Secret<String>>", ) }) .transpose()?; let masked_outgoing_webhook_custom_http_headers = outgoing_webhook_custom_http_headers.map(MaskedHeaders::from_headers); Ok(Self { merchant_id: item.merchant_id, profile_id, profile_name: item.profile_name, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, webhook_details: item.webhook_details.map(ForeignInto::foreign_into), metadata: item.metadata, routing_algorithm: item.routing_algorithm, intent_fulfillment_time: item.intent_fulfillment_time, frm_routing_algorithm: item.frm_routing_algorithm, #[cfg(feature = "payouts")] payout_routing_algorithm: item.payout_routing_algorithm, applepay_verified_domains: item.applepay_verified_domains, payment_link_config: item.payment_link_config.map(ForeignInto::foreign_into), session_expiry: item.session_expiry, authentication_connector_details: item .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config: item.payout_link_config.map(ForeignInto::foreign_into), use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing, extended_card_info_config: item .extended_card_info_config .map(|config| config.expose().parse_value("ExtendedCardInfoConfig")) .transpose()?, collect_shipping_details_from_wallet_connector: item .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector: item .collect_billing_details_from_wallet_connector, always_collect_billing_details_from_wallet_connector: item .always_collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: item .always_collect_shipping_details_from_wallet_connector, is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers: masked_outgoing_webhook_custom_http_headers, tax_connector_id: item.tax_connector_id, is_tax_connector_enabled: item.is_tax_connector_enabled, is_network_tokenization_enabled: item.is_network_tokenization_enabled, is_auto_retries_enabled: item.is_auto_retries_enabled, max_auto_retries_enabled: item.max_auto_retries_enabled, always_request_extended_authorization: item.always_request_extended_authorization, is_click_to_pay_enabled: item.is_click_to_pay_enabled, authentication_product_ids: item.authentication_product_ids, card_testing_guard_config: item .card_testing_guard_config .map(ForeignInto::foreign_into), is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, force_3ds_challenge: item.force_3ds_challenge, is_debit_routing_enabled: Some(item.is_debit_routing_enabled), merchant_business_country: item.merchant_business_country, }) } } #[cfg(feature = "v2")] impl ForeignTryFrom<domain::Profile> for ProfileResponse { type Error = error_stack::Report<errors::ParsingError>; fn foreign_try_from(item: domain::Profile) -> Result<Self, Self::Error> { let id = item.get_id().to_owned(); let outgoing_webhook_custom_http_headers = item .outgoing_webhook_custom_http_headers .map(|headers| { headers .into_inner() .expose() .parse_value::<HashMap<String, Secret<String>>>( "HashMap<String, Secret<String>>", ) }) .transpose()?; let order_fulfillment_time = item .order_fulfillment_time .map(admin::OrderFulfillmentTime::try_new) .transpose() .change_context(errors::ParsingError::IntegerOverflow)?; let masked_outgoing_webhook_custom_http_headers = outgoing_webhook_custom_http_headers.map(MaskedHeaders::from_headers); Ok(Self { merchant_id: item.merchant_id, id, profile_name: item.profile_name, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, payment_response_hash_key: item.payment_response_hash_key, redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, webhook_details: item.webhook_details.map(ForeignInto::foreign_into), metadata: item.metadata, applepay_verified_domains: item.applepay_verified_domains, payment_link_config: item.payment_link_config.map(ForeignInto::foreign_into), session_expiry: item.session_expiry, authentication_connector_details: item .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config: item.payout_link_config.map(ForeignInto::foreign_into), use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing, extended_card_info_config: item .extended_card_info_config .map(|config| config.expose().parse_value("ExtendedCardInfoConfig")) .transpose()?, collect_shipping_details_from_wallet_connector_if_required: item .collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector_if_required: item .collect_billing_details_from_wallet_connector, always_collect_shipping_details_from_wallet_connector: item .always_collect_shipping_details_from_wallet_connector, always_collect_billing_details_from_wallet_connector: item .always_collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers: masked_outgoing_webhook_custom_http_headers, order_fulfillment_time, order_fulfillment_time_origin: item.order_fulfillment_time_origin, should_collect_cvv_during_payment: item.should_collect_cvv_during_payment, tax_connector_id: item.tax_connector_id, is_tax_connector_enabled: item.is_tax_connector_enabled, is_network_tokenization_enabled: item.is_network_tokenization_enabled, is_click_to_pay_enabled: item.is_click_to_pay_enabled, authentication_product_ids: item.authentication_product_ids, card_testing_guard_config: item .card_testing_guard_config .map(ForeignInto::foreign_into), is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, is_debit_routing_enabled: Some(item.is_debit_routing_enabled), merchant_business_country: item.merchant_business_country, }) } } #[cfg(feature = "v1")] pub async fn create_profile_from_merchant_account( state: &SessionState, merchant_account: domain::MerchantAccount, request: ProfileCreate, key_store: &MerchantKeyStore, ) -> Result<domain::Profile, error_stack::Report<errors::ApiErrorResponse>> { use common_utils::ext_traits::AsyncExt; use diesel_models::business_profile::CardTestingGuardConfig; use crate::core; // Generate a unique profile id let profile_id = common_utils::generate_profile_id_of_default_length(); let merchant_id = merchant_account.get_id().to_owned(); let current_time = common_utils::date_time::now(); let webhook_details = request.webhook_details.map(ForeignInto::foreign_into); let payment_response_hash_key = request .payment_response_hash_key .or(merchant_account.payment_response_hash_key) .unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64)); let payment_link_config = request.payment_link_config.map(ForeignInto::foreign_into); let key_manager_state = state.into(); let outgoing_webhook_custom_http_headers = request .outgoing_webhook_custom_http_headers .async_map(|headers| { core::payment_methods::cards::create_encrypted_data( &key_manager_state, key_store, headers, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?; let payout_link_config = request .payout_link_config .map(|payout_conf| match payout_conf.config.validate() { Ok(_) => Ok(payout_conf.foreign_into()), Err(e) => Err(error_stack::report!( errors::ApiErrorResponse::InvalidRequestData { message: e.to_string() } )), }) .transpose()?; let key = key_store.key.clone().into_inner(); let key_manager_state = state.into(); let card_testing_secret_key = Some(Secret::new(utils::generate_id( consts::FINGERPRINT_SECRET_LENGTH, "fs", ))); let card_testing_guard_config = match request.card_testing_guard_config { Some(card_testing_guard_config) => Some(CardTestingGuardConfig::foreign_from( card_testing_guard_config, )), None => Some(CardTestingGuardConfig { is_card_ip_blocking_enabled: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_STATUS, card_ip_blocking_threshold: common_utils::consts::DEFAULT_CARD_IP_BLOCKING_THRESHOLD, is_guest_user_card_blocking_enabled: common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS, guest_user_card_blocking_threshold: common_utils::consts::DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD, is_customer_id_blocking_enabled: common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_STATUS, customer_id_blocking_threshold: common_utils::consts::DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD, card_testing_guard_expiry: common_utils::consts::DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS, }), }; Ok(domain::Profile::from(domain::ProfileSetter { profile_id, merchant_id, profile_name: request.profile_name.unwrap_or("default".to_string()), created_at: current_time, modified_at: current_time, return_url: request .return_url .map(|return_url| return_url.to_string()) .or(merchant_account.return_url), enable_payment_response_hash: request .enable_payment_response_hash .unwrap_or(merchant_account.enable_payment_response_hash), payment_response_hash_key: Some(payment_response_hash_key), redirect_to_merchant_with_http_post: request .redirect_to_merchant_with_http_post .unwrap_or(merchant_account.redirect_to_merchant_with_http_post), webhook_details: webhook_details.or(merchant_account.webhook_details), metadata: request.metadata, routing_algorithm: None, intent_fulfillment_time: request .intent_fulfillment_time .map(i64::from) .or(merchant_account.intent_fulfillment_time) .or(Some(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME)), frm_routing_algorithm: request .frm_routing_algorithm .or(merchant_account.frm_routing_algorithm), #[cfg(feature = "payouts")] payout_routing_algorithm: request .payout_routing_algorithm .or(merchant_account.payout_routing_algorithm), #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, is_recon_enabled: merchant_account.is_recon_enabled, applepay_verified_domains: request.applepay_verified_domains, payment_link_config, session_expiry: request .session_expiry .map(i64::from) .or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)), authentication_connector_details: request .authentication_connector_details .map(ForeignInto::foreign_into), payout_link_config, is_connector_agnostic_mit_enabled: request.is_connector_agnostic_mit_enabled, is_extended_card_info_enabled: None, extended_card_info_config: None, use_billing_as_payment_method_billing: request .use_billing_as_payment_method_billing .or(Some(true)), collect_shipping_details_from_wallet_connector: request .collect_shipping_details_from_wallet_connector .or(Some(false)), collect_billing_details_from_wallet_connector: request .collect_billing_details_from_wallet_connector .or(Some(false)), always_collect_billing_details_from_wallet_connector: request .always_collect_billing_details_from_wallet_connector .or(Some(false)), always_collect_shipping_details_from_wallet_connector: request .always_collect_shipping_details_from_wallet_connector .or(Some(false)), outgoing_webhook_custom_http_headers, tax_connector_id: request.tax_connector_id, is_tax_connector_enabled: request.is_tax_connector_enabled, dynamic_routing_algorithm: None, is_network_tokenization_enabled: request.is_network_tokenization_enabled, is_auto_retries_enabled: request.is_auto_retries_enabled.unwrap_or_default(), max_auto_retries_enabled: request.max_auto_retries_enabled.map(i16::from), always_request_extended_authorization: request.always_request_extended_authorization, is_click_to_pay_enabled: request.is_click_to_pay_enabled, authentication_product_ids: request.authentication_product_ids, card_testing_guard_config, card_testing_secret_key: card_testing_secret_key .async_lift(|inner| async { domain_types::crypto_operation( &key_manager_state, common_utils::type_name!(domain::Profile), domain_types::CryptoOperation::EncryptOptional(inner), km_types::Identifier::Merchant(key_store.merchant_id.clone()), key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) }) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")?, is_clear_pan_retries_enabled: request.is_clear_pan_retries_enabled.unwrap_or_default(), force_3ds_challenge: request.force_3ds_challenge.unwrap_or_default(), is_debit_routing_enabled: request.is_debit_routing_enabled.unwrap_or_default(), merchant_business_country: request.merchant_business_country, })) }
4,011
1,407
hyperswitch
crates/router/src/types/api/fraud_check_v2.rs
.rs
pub use hyperswitch_domain_models::router_flow_types::fraud_check::{ Checkout, Fulfillment, RecordReturn, Sale, Transaction, }; pub use hyperswitch_interfaces::api::fraud_check_v2::{ FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2, FraudCheckTransactionV2, FraudCheckV2, };
85
1,408
hyperswitch
crates/router/src/types/api/payouts.rs
.rs
pub use api_models::payouts::{ AchBankTransfer, BacsBankTransfer, Bank as BankPayout, CardPayout, PaymentMethodTypeInfo, PayoutActionRequest, PayoutAttemptResponse, PayoutCreateRequest, PayoutCreateResponse, PayoutEnabledPaymentMethodsInfo, PayoutLinkResponse, PayoutListConstraints, PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse, PayoutMethodData, PayoutMethodDataResponse, PayoutRequest, PayoutRetrieveBody, PayoutRetrieveRequest, PixBankTransfer, RequiredFieldsOverrideRequest, SepaBankTransfer, Wallet as WalletPayout, }; pub use hyperswitch_domain_models::router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, }; pub use hyperswitch_interfaces::api::payouts::{ PayoutCancel, PayoutCreate, PayoutEligibility, PayoutFulfill, PayoutQuote, PayoutRecipient, PayoutRecipientAccount, PayoutSync, Payouts, }; pub use super::payouts_v2::{ PayoutCancelV2, PayoutCreateV2, PayoutEligibilityV2, PayoutFulfillV2, PayoutQuoteV2, PayoutRecipientAccountV2, PayoutRecipientV2, PayoutSyncV2, PayoutsV2, };
308
1,409
hyperswitch
crates/router/src/types/api/payment_methods.rs
.rs
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub use api_models::payment_methods::{ CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardNetworkTokenizeRequest, CardNetworkTokenizeResponse, CardType, CustomerPaymentMethod, CustomerPaymentMethodsListResponse, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, MigrateCardDetail, NetworkTokenDetailsPaymentMethod, NetworkTokenResponse, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate, PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodIntentConfirm, PaymentMethodIntentCreate, PaymentMethodListData, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodMigrate, PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodResponseData, PaymentMethodUpdate, PaymentMethodUpdateData, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, TotalPaymentMethodCountResponse, }; #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] pub use api_models::payment_methods::{ CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardNetworkTokenizeRequest, CardNetworkTokenizeResponse, CustomerPaymentMethod, CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, MigrateCardDetail, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate, PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodMigrate, PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData, TokenizeCardRequest, TokenizeDataRequest, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizePaymentMethodRequest, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, }; use error_stack::report; use crate::core::{ errors::{self, RouterResult}, payments::helpers::validate_payment_method_type_against_payment_method, }; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use crate::utils; pub(crate) trait PaymentMethodCreateExt { fn validate(&self) -> RouterResult<()>; } // convert self.payment_method_type to payment_method and compare it against self.payment_method #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] impl PaymentMethodCreateExt for PaymentMethodCreate { fn validate(&self) -> RouterResult<()> { if let Some(pm) = self.payment_method { if let Some(payment_method_type) = self.payment_method_type { if !validate_payment_method_type_against_payment_method(pm, payment_method_type) { return Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid 'payment_method_type' provided".to_string() }) .attach_printable("Invalid payment method type")); } } } Ok(()) } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl PaymentMethodCreateExt for PaymentMethodCreate { fn validate(&self) -> RouterResult<()> { utils::when( !validate_payment_method_type_against_payment_method( self.payment_method_type, self.payment_method_subtype, ), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid 'payment_method_type' provided".to_string() }) .attach_printable("Invalid payment method type")) }, )?; utils::when( !Self::validate_payment_method_data_against_payment_method( self.payment_method_type, self.payment_method_data.clone(), ), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid 'payment_method_data' provided".to_string() }) .attach_printable("Invalid payment method data")) }, )?; Ok(()) } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl PaymentMethodCreateExt for PaymentMethodIntentConfirm { fn validate(&self) -> RouterResult<()> { utils::when( !validate_payment_method_type_against_payment_method( self.payment_method_type, self.payment_method_subtype, ), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid 'payment_method_type' provided".to_string() }) .attach_printable("Invalid payment method type")) }, )?; utils::when( !Self::validate_payment_method_data_against_payment_method( self.payment_method_type, self.payment_method_data.clone(), ), || { Err(report!(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid 'payment_method_data' provided".to_string() }) .attach_printable("Invalid payment method data")) }, )?; Ok(()) } }
1,137
1,410
hyperswitch
crates/router/src/types/api/refunds_v2.rs
.rs
pub use hyperswitch_interfaces::api::refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2};
30
1,411
hyperswitch
crates/router/src/types/api/configs.rs
.rs
#[derive(Clone, serde::Serialize, Debug, serde::Deserialize)] pub struct Config { pub key: String, pub value: String, } #[derive(Clone, serde::Deserialize, Debug, serde::Serialize)] pub struct ConfigUpdate { #[serde(skip_deserializing)] pub key: String, pub value: String, }
71
1,412
hyperswitch
crates/router/src/types/api/webhook_events.rs
.rs
pub use api_models::webhook_events::{ EventListConstraints, EventListConstraintsInternal, EventListItemResponse, EventListRequestInternal, EventRetrieveResponse, OutgoingWebhookRequestContent, OutgoingWebhookResponseContent, TotalEventsResponse, WebhookDeliveryAttemptListRequestInternal, WebhookDeliveryRetryRequestInternal, };
69
1,413
hyperswitch
crates/router/src/types/api/poll.rs
.rs
use serde; #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PollId { pub poll_id: String, }
30
1,414
hyperswitch
crates/router/src/types/api/files.rs
.rs
use api_models::enums::FileUploadProvider; pub use hyperswitch_domain_models::router_flow_types::files::{Retrieve, Upload}; pub use hyperswitch_interfaces::api::files::{FilePurpose, FileUpload, RetrieveFile, UploadFile}; use masking::{Deserialize, Serialize}; use serde_with::serde_as; pub use super::files_v2::{FileUploadV2, RetrieveFileV2, UploadFileV2}; use crate::{ core::errors, types::{self, transformers::ForeignTryFrom}, }; #[derive(Default, Debug, Deserialize, Serialize)] pub struct FileId { pub file_id: String, } #[derive(Debug)] pub enum FileDataRequired { Required, NotRequired, } impl ForeignTryFrom<FileUploadProvider> for types::Connector { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(item: FileUploadProvider) -> Result<Self, Self::Error> { match item { FileUploadProvider::Stripe => Ok(Self::Stripe), FileUploadProvider::Checkout => Ok(Self::Checkout), FileUploadProvider::Router => Err(errors::ApiErrorResponse::NotSupported { message: "File upload provider is not a connector".to_owned(), } .into()), } } } impl ForeignTryFrom<&types::Connector> for FileUploadProvider { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from(item: &types::Connector) -> Result<Self, Self::Error> { match *item { types::Connector::Stripe => Ok(Self::Stripe), types::Connector::Checkout => Ok(Self::Checkout), _ => Err(errors::ApiErrorResponse::NotSupported { message: "Connector not supported as file provider".to_owned(), } .into()), } } } #[serde_as] #[derive(Debug, Clone, serde::Serialize)] pub struct CreateFileRequest { pub file: Vec<u8>, pub file_name: Option<String>, pub file_size: i32, #[serde_as(as = "serde_with::DisplayFromStr")] pub file_type: mime::Mime, pub purpose: FilePurpose, pub dispute_id: Option<String>, }
464
1,415
hyperswitch
crates/router/src/types/api/connector_onboarding/paypal.rs
.rs
use api_models::connector_onboarding as api; use error_stack::ResultExt; use crate::core::errors::{ApiErrorResponse, RouterResult}; #[derive(serde::Deserialize, Debug)] pub struct HateoasLink { pub href: String, pub rel: String, pub method: String, } #[derive(serde::Deserialize, Debug)] pub struct PartnerReferralResponse { pub links: Vec<HateoasLink>, } #[derive(serde::Serialize, Debug)] pub struct PartnerReferralRequest { pub tracking_id: String, pub operations: Vec<PartnerReferralOperations>, pub products: Vec<PayPalProducts>, pub capabilities: Vec<PayPalCapabilities>, pub partner_config_override: PartnerConfigOverride, pub legal_consents: Vec<LegalConsent>, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayPalProducts { Ppcp, AdvancedVaulting, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayPalCapabilities { PaypalWalletVaultingAdvanced, } #[derive(serde::Serialize, Debug)] pub struct PartnerReferralOperations { pub operation: PayPalReferralOperationType, pub api_integration_preference: PartnerReferralIntegrationPreference, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayPalReferralOperationType { ApiIntegration, } #[derive(serde::Serialize, Debug)] pub struct PartnerReferralIntegrationPreference { pub rest_api_integration: PartnerReferralRestApiIntegration, } #[derive(serde::Serialize, Debug)] pub struct PartnerReferralRestApiIntegration { pub integration_method: IntegrationMethod, pub integration_type: PayPalIntegrationType, pub third_party_details: PartnerReferralThirdPartyDetails, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum IntegrationMethod { Paypal, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayPalIntegrationType { ThirdParty, } #[derive(serde::Serialize, Debug)] pub struct PartnerReferralThirdPartyDetails { pub features: Vec<PayPalFeatures>, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum PayPalFeatures { Payment, Refund, Vault, AccessMerchantInformation, BillingAgreement, ReadSellerDispute, } #[derive(serde::Serialize, Debug)] pub struct PartnerConfigOverride { pub partner_logo_url: String, pub return_url: String, } #[derive(serde::Serialize, Debug)] pub struct LegalConsent { #[serde(rename = "type")] pub consent_type: LegalConsentType, pub granted: bool, } #[derive(serde::Serialize, Debug)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum LegalConsentType { ShareDataConsent, } impl PartnerReferralRequest { pub fn new(tracking_id: String, return_url: String) -> Self { Self { tracking_id, operations: vec![PartnerReferralOperations { operation: PayPalReferralOperationType::ApiIntegration, api_integration_preference: PartnerReferralIntegrationPreference { rest_api_integration: PartnerReferralRestApiIntegration { integration_method: IntegrationMethod::Paypal, integration_type: PayPalIntegrationType::ThirdParty, third_party_details: PartnerReferralThirdPartyDetails { features: vec![ PayPalFeatures::Payment, PayPalFeatures::Refund, PayPalFeatures::Vault, PayPalFeatures::AccessMerchantInformation, PayPalFeatures::BillingAgreement, PayPalFeatures::ReadSellerDispute, ], }, }, }, }], products: vec![PayPalProducts::Ppcp, PayPalProducts::AdvancedVaulting], capabilities: vec![PayPalCapabilities::PaypalWalletVaultingAdvanced], partner_config_override: PartnerConfigOverride { partner_logo_url: "https://hyperswitch.io/img/websiteIcon.svg".to_string(), return_url, }, legal_consents: vec![LegalConsent { consent_type: LegalConsentType::ShareDataConsent, granted: true, }], } } } #[derive(serde::Deserialize, Debug)] pub struct SellerStatusResponse { pub merchant_id: common_utils::id_type::MerchantId, pub links: Vec<HateoasLink>, } #[derive(serde::Deserialize, Debug)] pub struct SellerStatusDetailsResponse { pub merchant_id: common_utils::id_type::MerchantId, pub primary_email_confirmed: bool, pub payments_receivable: bool, pub products: Vec<SellerStatusProducts>, } #[derive(serde::Deserialize, Debug)] pub struct SellerStatusProducts { pub name: String, pub vetting_status: Option<VettingStatus>, } #[derive(serde::Deserialize, Debug, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum VettingStatus { NeedMoreData, Subscribed, Denied, } impl SellerStatusResponse { pub fn extract_merchant_details_url(self, paypal_base_url: &str) -> RouterResult<String> { self.links .first() .and_then(|link| link.href.strip_prefix('/')) .map(|link| format!("{}{}", paypal_base_url, link)) .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Merchant details not received in onboarding status") } } impl SellerStatusDetailsResponse { pub fn check_payments_receivable(&self) -> Option<api::PayPalOnboardingStatus> { if !self.payments_receivable { return Some(api::PayPalOnboardingStatus::PaymentsNotReceivable); } None } pub fn check_ppcp_custom_status(&self) -> Option<api::PayPalOnboardingStatus> { match self.get_ppcp_custom_status() { Some(VettingStatus::Denied) => Some(api::PayPalOnboardingStatus::PpcpCustomDenied), Some(VettingStatus::Subscribed) => None, _ => Some(api::PayPalOnboardingStatus::MorePermissionsNeeded), } } fn check_email_confirmation(&self) -> Option<api::PayPalOnboardingStatus> { if !self.primary_email_confirmed { return Some(api::PayPalOnboardingStatus::EmailNotVerified); } None } pub async fn get_eligibility_status(&self) -> RouterResult<api::PayPalOnboardingStatus> { Ok(self .check_payments_receivable() .or(self.check_email_confirmation()) .or(self.check_ppcp_custom_status()) .unwrap_or(api::PayPalOnboardingStatus::Success( api::PayPalOnboardingDone { payer_id: self.get_payer_id(), }, ))) } fn get_ppcp_custom_status(&self) -> Option<VettingStatus> { self.products .iter() .find(|product| product.name == "PPCP_CUSTOM") .and_then(|ppcp_custom| ppcp_custom.vetting_status.clone()) } fn get_payer_id(&self) -> common_utils::id_type::MerchantId { self.merchant_id.to_owned() } } impl PartnerReferralResponse { pub fn extract_action_url(self) -> RouterResult<String> { Ok(self .links .into_iter() .find(|hateoas_link| hateoas_link.rel == "action_url") .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Failed to get action_url from paypal response")? .href) } }
1,676
1,416
hyperswitch
crates/router/src/types/api/verify_connector/stripe.rs
.rs
use error_stack::ResultExt; use router_env::env; use super::VerifyConnector; use crate::{ connector, core::errors, services, types, types::api::verify_connector::BoxedConnectorIntegrationInterface, }; #[async_trait::async_trait] impl VerifyConnector for connector::Stripe { async fn handle_payment_error_response<F, ResourceCommonData, Req, Resp>( connector: BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>, error_response: types::Response, ) -> errors::RouterResponse<()> { let error = connector .get_error_response(error_response, None) .change_context(errors::ApiErrorResponse::InternalServerError)?; match (env::which(), error.code.as_str()) { // In situations where an attempt is made to process a payment using a // Stripe production key along with a test card (which verify_connector is using), // Stripe will respond with a "card_declined" error. In production, // when this scenario occurs we will send back an "Ok" response. (env::Env::Production, "card_declined") => Ok(services::ApplicationResponse::StatusOk), _ => Err(errors::ApiErrorResponse::InvalidRequestData { message: error.reason.unwrap_or(error.message), } .into()), } } }
279
1,417
hyperswitch
crates/router/src/types/api/verify_connector/paypal.rs
.rs
use error_stack::ResultExt; use super::{VerifyConnector, VerifyConnectorData}; use crate::{ connector, core::errors, routes::SessionState, services, types::{self, api}, }; #[async_trait::async_trait] impl VerifyConnector for connector::Paypal { async fn get_access_token( state: &SessionState, connector_data: VerifyConnectorData, ) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> { let token_data: types::AccessTokenRequestData = connector_data.connector_auth.clone().try_into()?; let router_data = connector_data.get_router_data(state, token_data, None); let request = connector_data .connector .get_connector_integration() .build_request(&router_data, &state.conf.connectors) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Payment request cannot be built".to_string(), })? .ok_or(errors::ApiErrorResponse::InternalServerError)?; let response = services::call_connector_api(&state.to_owned(), request, "get_access_token") .await .change_context(errors::ApiErrorResponse::InternalServerError)?; match response { Ok(res) => Some( connector_data .connector .get_connector_integration() .handle_response(&router_data, None, res) .change_context(errors::ApiErrorResponse::InternalServerError)? .response .map_err(|_| errors::ApiErrorResponse::InternalServerError.into()), ) .transpose(), Err(response_data) => { Self::handle_access_token_error_response::< api::AccessTokenAuth, types::AccessTokenFlowData, types::AccessTokenRequestData, types::AccessToken, >( connector_data.connector.get_connector_integration(), response_data, ) .await } } } }
389
1,418
hyperswitch
crates/router/src/types/domain/event.rs
.rs
use common_utils::{ crypto::{Encryptable, OptionalEncryptableSecretString}, encryption::Encryption, type_name, types::keymanager::{KeyManagerState, ToEncryptable}, }; use diesel_models::{ enums::{EventClass, EventObjectType, EventType, WebhookDeliveryAttempt}, events::{EventMetadata, EventUpdateInternal}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use rustc_hash::FxHashMap; use crate::{ errors::{CustomResult, ValidationError}, types::domain::types, }; #[derive(Clone, Debug, router_derive::ToEncryption)] pub struct Event { /// A string that uniquely identifies the event. pub event_id: String, /// Represents the type of event for the webhook. pub event_type: EventType, /// Represents the class of event for the webhook. pub event_class: EventClass, /// Indicates whether the current webhook delivery was successful. pub is_webhook_notified: bool, /// Reference to the object for which the webhook was created. pub primary_object_id: String, /// Type of the object type for which the webhook was created. pub primary_object_type: EventObjectType, /// The timestamp when the webhook was created. pub created_at: time::PrimitiveDateTime, /// Merchant Account identifier to which the object is associated with. pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Business Profile identifier to which the object is associated with. pub business_profile_id: Option<common_utils::id_type::ProfileId>, /// The timestamp when the primary object was created. pub primary_object_created_at: Option<time::PrimitiveDateTime>, /// This allows the event to be uniquely identified to prevent multiple processing. pub idempotent_event_id: Option<String>, /// Links to the initial attempt of the event. pub initial_attempt_id: Option<String>, /// This field contains the encrypted request data sent as part of the event. #[encrypt] pub request: Option<Encryptable<Secret<String>>>, /// This field contains the encrypted response data received as part of the event. #[encrypt] pub response: Option<Encryptable<Secret<String>>>, /// Represents the event delivery type. pub delivery_attempt: Option<WebhookDeliveryAttempt>, /// Holds any additional data related to the event. pub metadata: Option<EventMetadata>, /// Indicates whether the event was ultimately delivered. pub is_overall_delivery_successful: Option<bool>, } #[derive(Debug)] pub enum EventUpdate { UpdateResponse { is_webhook_notified: bool, response: OptionalEncryptableSecretString, }, OverallDeliveryStatusUpdate { is_overall_delivery_successful: bool, }, } impl From<EventUpdate> for EventUpdateInternal { fn from(event_update: EventUpdate) -> Self { match event_update { EventUpdate::UpdateResponse { is_webhook_notified, response, } => Self { is_webhook_notified: Some(is_webhook_notified), response: response.map(Into::into), is_overall_delivery_successful: None, }, EventUpdate::OverallDeliveryStatusUpdate { is_overall_delivery_successful, } => Self { is_webhook_notified: None, response: None, is_overall_delivery_successful: Some(is_overall_delivery_successful), }, } } } #[async_trait::async_trait] impl super::behaviour::Conversion for Event { type DstType = diesel_models::events::Event; type NewDstType = diesel_models::events::EventNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::events::Event { event_id: self.event_id, event_type: self.event_type, event_class: self.event_class, is_webhook_notified: self.is_webhook_notified, primary_object_id: self.primary_object_id, primary_object_type: self.primary_object_type, created_at: self.created_at, merchant_id: self.merchant_id, business_profile_id: self.business_profile_id, primary_object_created_at: self.primary_object_created_at, idempotent_event_id: self.idempotent_event_id, initial_attempt_id: self.initial_attempt_id, request: self.request.map(Into::into), response: self.response.map(Into::into), delivery_attempt: self.delivery_attempt, metadata: self.metadata, is_overall_delivery_successful: self.is_overall_delivery_successful, }) } async fn convert_back( state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: common_utils::types::keymanager::Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let decrypted = types::crypto_operation( state, type_name!(Self::DstType), types::CryptoOperation::BatchDecrypt(EncryptedEvent::to_encryptable(EncryptedEvent { request: item.request.clone(), response: item.response.clone(), })), key_manager_identifier, key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting event data".to_string(), })?; let encryptable_event = EncryptedEvent::from_encryptable(decrypted).change_context( ValidationError::InvalidValue { message: "Failed while decrypting event data".to_string(), }, )?; Ok(Self { event_id: item.event_id, event_type: item.event_type, event_class: item.event_class, is_webhook_notified: item.is_webhook_notified, primary_object_id: item.primary_object_id, primary_object_type: item.primary_object_type, created_at: item.created_at, merchant_id: item.merchant_id, business_profile_id: item.business_profile_id, primary_object_created_at: item.primary_object_created_at, idempotent_event_id: item.idempotent_event_id, initial_attempt_id: item.initial_attempt_id, request: encryptable_event.request, response: encryptable_event.response, delivery_attempt: item.delivery_attempt, metadata: item.metadata, is_overall_delivery_successful: item.is_overall_delivery_successful, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::events::EventNew { event_id: self.event_id, event_type: self.event_type, event_class: self.event_class, is_webhook_notified: self.is_webhook_notified, primary_object_id: self.primary_object_id, primary_object_type: self.primary_object_type, created_at: self.created_at, merchant_id: self.merchant_id, business_profile_id: self.business_profile_id, primary_object_created_at: self.primary_object_created_at, idempotent_event_id: self.idempotent_event_id, initial_attempt_id: self.initial_attempt_id, request: self.request.map(Into::into), response: self.response.map(Into::into), delivery_attempt: self.delivery_attempt, metadata: self.metadata, is_overall_delivery_successful: self.is_overall_delivery_successful, }) } }
1,572
1,419
hyperswitch
crates/router/src/types/domain/user.rs
.rs
use std::{ collections::HashSet, ops::{Deref, Not}, str::FromStr, }; use api_models::{ admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api, }; use common_enums::EntityType; use common_utils::{ crypto::Encryptable, id_type, new_type::MerchantName, pii, type_name, types::keymanager::Identifier, }; use diesel_models::{ enums::{TotpStatus, UserRoleVersion, UserStatus}, organization::{self as diesel_org, Organization, OrganizationBridge}, user as storage_user, user_role::{UserRole, UserRoleNew}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::api::ApplicationResponse; use masking::{ExposeInterface, PeekInterface, Secret}; use once_cell::sync::Lazy; use rand::distributions::{Alphanumeric, DistString}; use router_env::env; use time::PrimitiveDateTime; use unicode_segmentation::UnicodeSegmentation; #[cfg(feature = "keymanager_create")] use {base64::Engine, common_utils::types::keymanager::EncryptionTransferRequest}; use crate::{ consts, core::{ admin, errors::{UserErrors, UserResult}, }, db::GlobalStorageInterface, routes::SessionState, services::{self, authentication::UserFromToken}, types::{domain, transformers::ForeignFrom}, utils::user::password, }; pub mod dashboard_metadata; pub mod decision_manager; pub use decision_manager::*; pub mod user_authentication_method; use super::{types as domain_types, UserKeyStore}; #[derive(Clone)] pub struct UserName(Secret<String>); impl UserName { pub fn new(name: Secret<String>) -> UserResult<Self> { let name = name.expose(); let is_empty_or_whitespace = name.trim().is_empty(); let is_too_long = name.graphemes(true).count() > consts::user::MAX_NAME_LENGTH; let forbidden_characters = ['/', '(', ')', '"', '<', '>', '\\', '{', '}']; let contains_forbidden_characters = name.chars().any(|g| forbidden_characters.contains(&g)); if is_empty_or_whitespace || is_too_long || contains_forbidden_characters { Err(UserErrors::NameParsingError.into()) } else { Ok(Self(name.into())) } } pub fn get_secret(self) -> Secret<String> { self.0 } } impl TryFrom<pii::Email> for UserName { type Error = error_stack::Report<UserErrors>; fn try_from(value: pii::Email) -> UserResult<Self> { Self::new(Secret::new( value .peek() .split_once('@') .ok_or(UserErrors::InvalidEmailError)? .0 .to_string(), )) } } #[derive(Clone, Debug)] pub struct UserEmail(pii::Email); static BLOCKED_EMAIL: Lazy<HashSet<String>> = Lazy::new(|| { let blocked_emails_content = include_str!("../../utils/user/blocker_emails.txt"); let blocked_emails: HashSet<String> = blocked_emails_content .lines() .map(|s| s.trim().to_owned()) .collect(); blocked_emails }); impl UserEmail { pub fn new(email: Secret<String, pii::EmailStrategy>) -> UserResult<Self> { use validator::ValidateEmail; let email_string = email.expose().to_lowercase(); let email = pii::Email::from_str(&email_string).change_context(UserErrors::EmailParsingError)?; if email_string.validate_email() { let (_username, domain) = match email_string.as_str().split_once('@') { Some((u, d)) => (u, d), None => return Err(UserErrors::EmailParsingError.into()), }; if BLOCKED_EMAIL.contains(domain) { return Err(UserErrors::InvalidEmailError.into()); } Ok(Self(email)) } else { Err(UserErrors::EmailParsingError.into()) } } pub fn from_pii_email(email: pii::Email) -> UserResult<Self> { let email_string = email.expose().map(|inner| inner.to_lowercase()); Self::new(email_string) } pub fn into_inner(self) -> pii::Email { self.0 } pub fn get_inner(&self) -> &pii::Email { &self.0 } pub fn get_secret(self) -> Secret<String, pii::EmailStrategy> { (*self.0).clone() } pub fn extract_domain(&self) -> UserResult<&str> { let (_username, domain) = self .peek() .split_once('@') .ok_or(UserErrors::InternalServerError)?; Ok(domain) } } impl TryFrom<pii::Email> for UserEmail { type Error = error_stack::Report<UserErrors>; fn try_from(value: pii::Email) -> Result<Self, Self::Error> { Self::from_pii_email(value) } } impl Deref for UserEmail { type Target = Secret<String, pii::EmailStrategy>; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Clone)] pub struct UserPassword(Secret<String>); impl UserPassword { pub fn new(password: Secret<String>) -> UserResult<Self> { let password = password.expose(); let mut has_upper_case = false; let mut has_lower_case = false; let mut has_numeric_value = false; let mut has_special_character = false; let mut has_whitespace = false; for c in password.chars() { has_upper_case = has_upper_case || c.is_uppercase(); has_lower_case = has_lower_case || c.is_lowercase(); has_numeric_value = has_numeric_value || c.is_numeric(); has_special_character = has_special_character || !c.is_alphanumeric(); has_whitespace = has_whitespace || c.is_whitespace(); } let is_password_format_valid = has_upper_case && has_lower_case && has_numeric_value && has_special_character && !has_whitespace; let is_too_long = password.graphemes(true).count() > consts::user::MAX_PASSWORD_LENGTH; let is_too_short = password.graphemes(true).count() < consts::user::MIN_PASSWORD_LENGTH; if is_too_short || is_too_long || !is_password_format_valid { return Err(UserErrors::PasswordParsingError.into()); } Ok(Self(password.into())) } pub fn new_password_without_validation(password: Secret<String>) -> UserResult<Self> { let password = password.expose(); if password.is_empty() { return Err(UserErrors::PasswordParsingError.into()); } Ok(Self(password.into())) } pub fn get_secret(&self) -> Secret<String> { self.0.clone() } } #[derive(Clone)] pub struct UserCompanyName(String); impl UserCompanyName { pub fn new(company_name: String) -> UserResult<Self> { let company_name = company_name.trim(); let is_empty_or_whitespace = company_name.is_empty(); let is_too_long = company_name.graphemes(true).count() > consts::user::MAX_COMPANY_NAME_LENGTH; let is_all_valid_characters = company_name .chars() .all(|x| x.is_alphanumeric() || x.is_ascii_whitespace() || x == '_'); if is_empty_or_whitespace || is_too_long || !is_all_valid_characters { Err(UserErrors::CompanyNameParsingError.into()) } else { Ok(Self(company_name.to_string())) } } pub fn get_secret(self) -> String { self.0 } } #[derive(Clone)] pub struct NewUserOrganization(diesel_org::OrganizationNew); impl NewUserOrganization { pub async fn insert_org_in_db(self, state: SessionState) -> UserResult<Organization> { state .accounts_store .insert_organization(self.0) .await .map_err(|e| { if e.current_context().is_db_unique_violation() { e.change_context(UserErrors::DuplicateOrganizationId) } else { e.change_context(UserErrors::InternalServerError) } }) .attach_printable("Error while inserting organization") } pub fn get_organization_id(&self) -> id_type::OrganizationId { self.0.get_organization_id() } } impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserOrganization { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> { let new_organization = api_org::OrganizationNew::new(Some( UserCompanyName::new(value.company_name)?.get_secret(), )); let db_organization = ForeignFrom::foreign_from(new_organization); Ok(Self(db_organization)) } } impl From<user_api::SignUpRequest> for NewUserOrganization { fn from(_value: user_api::SignUpRequest) -> Self { let new_organization = api_org::OrganizationNew::new(None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } } impl From<user_api::ConnectAccountRequest> for NewUserOrganization { fn from(_value: user_api::ConnectAccountRequest) -> Self { let new_organization = api_org::OrganizationNew::new(None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } } impl From<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUserOrganization { fn from( (_value, org_id): (user_api::CreateInternalUserRequest, id_type::OrganizationId), ) -> Self { let new_organization = api_org::OrganizationNew { org_id, org_name: None, }; let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } } impl From<UserMerchantCreateRequestWithToken> for NewUserOrganization { fn from(value: UserMerchantCreateRequestWithToken) -> Self { Self(diesel_org::OrganizationNew::new( value.2.org_id, Some(value.1.company_name), )) } } type InviteeUserRequestWithInvitedUserToken = (user_api::InviteUserRequest, UserFromToken); impl From<InviteeUserRequestWithInvitedUserToken> for NewUserOrganization { fn from(_value: InviteeUserRequestWithInvitedUserToken) -> Self { let new_organization = api_org::OrganizationNew::new(None); let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } } impl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUserOrganization { fn from( (_value, merchant_account_identifier): ( user_api::CreateTenantUserRequest, MerchantAccountIdentifier, ), ) -> Self { let new_organization = api_org::OrganizationNew { org_id: merchant_account_identifier.org_id, org_name: None, }; let db_organization = ForeignFrom::foreign_from(new_organization); Self(db_organization) } } impl ForeignFrom<api_models::user::UserOrgMerchantCreateRequest> for diesel_models::organization::OrganizationNew { fn foreign_from(item: api_models::user::UserOrgMerchantCreateRequest) -> Self { let org_id = id_type::OrganizationId::default(); let api_models::user::UserOrgMerchantCreateRequest { organization_name, organization_details, metadata, .. } = item; let mut org_new_db = Self::new(org_id, Some(organization_name.expose())); org_new_db.organization_details = organization_details; org_new_db.metadata = metadata; org_new_db } } #[derive(Clone)] pub struct MerchantId(String); impl MerchantId { pub fn new(merchant_id: String) -> UserResult<Self> { let merchant_id = merchant_id.trim().to_lowercase().replace(' ', "_"); let is_empty_or_whitespace = merchant_id.is_empty(); let is_all_valid_characters = merchant_id.chars().all(|x| x.is_alphanumeric() || x == '_'); if is_empty_or_whitespace || !is_all_valid_characters { Err(UserErrors::MerchantIdParsingError.into()) } else { Ok(Self(merchant_id.to_string())) } } pub fn get_secret(&self) -> String { self.0.clone() } } impl TryFrom<MerchantId> for id_type::MerchantId { type Error = error_stack::Report<UserErrors>; fn try_from(value: MerchantId) -> Result<Self, Self::Error> { Self::try_from(std::borrow::Cow::from(value.0)) .change_context(UserErrors::MerchantIdParsingError) .attach_printable("Could not convert user merchant_id to merchant_id type") } } #[derive(Clone)] pub struct NewUserMerchant { merchant_id: id_type::MerchantId, company_name: Option<UserCompanyName>, new_organization: NewUserOrganization, product_type: Option<common_enums::MerchantProductType>, } impl TryFrom<UserCompanyName> for MerchantName { // We should ideally not get this error because all the validations are done for company name type Error = error_stack::Report<UserErrors>; fn try_from(company_name: UserCompanyName) -> Result<Self, Self::Error> { Self::try_new(company_name.get_secret()).change_context(UserErrors::CompanyNameParsingError) } } impl NewUserMerchant { pub fn get_company_name(&self) -> Option<String> { self.company_name.clone().map(UserCompanyName::get_secret) } pub fn get_merchant_id(&self) -> id_type::MerchantId { self.merchant_id.clone() } pub fn get_new_organization(&self) -> NewUserOrganization { self.new_organization.clone() } pub fn get_product_type(&self) -> Option<common_enums::MerchantProductType> { self.product_type } pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> { if state .store .get_merchant_key_store_by_merchant_id( &(&state).into(), &self.get_merchant_id(), &state.store.get_master_key().to_vec().into(), ) .await .is_ok() { return Err(UserErrors::MerchantAccountCreationError(format!( "Merchant with {:?} already exists", self.get_merchant_id() )) .into()); } Ok(()) } #[cfg(feature = "v2")] fn create_merchant_account_request(&self) -> UserResult<admin_api::MerchantAccountCreate> { let merchant_name = if let Some(company_name) = self.company_name.clone() { MerchantName::try_from(company_name) } else { MerchantName::try_new("merchant".to_string()) .change_context(UserErrors::InternalServerError) .attach_printable("merchant name validation failed") } .map(Secret::new)?; Ok(admin_api::MerchantAccountCreate { merchant_name, organization_id: self.new_organization.get_organization_id(), metadata: None, merchant_details: None, product_type: self.get_product_type(), }) } #[cfg(feature = "v1")] fn create_merchant_account_request(&self) -> UserResult<admin_api::MerchantAccountCreate> { Ok(admin_api::MerchantAccountCreate { merchant_id: self.get_merchant_id(), metadata: None, locker_id: None, return_url: None, merchant_name: self.get_company_name().map(Secret::new), webhook_details: None, publishable_key: None, organization_id: Some(self.new_organization.get_organization_id()), merchant_details: None, routing_algorithm: None, parent_merchant_id: None, sub_merchants_enabled: None, frm_routing_algorithm: None, #[cfg(feature = "payouts")] payout_routing_algorithm: None, primary_business_details: None, payment_response_hash_key: None, enable_payment_response_hash: None, redirect_to_merchant_with_http_post: None, pm_collect_link_config: None, product_type: self.get_product_type(), }) } #[cfg(feature = "v1")] pub async fn create_new_merchant_and_insert_in_db( &self, state: SessionState, ) -> UserResult<domain::MerchantAccount> { self.check_if_already_exists_in_db(state.clone()).await?; let merchant_account_create_request = self .create_merchant_account_request() .attach_printable("unable to construct merchant account create request")?; let ApplicationResponse::Json(merchant_account_response) = Box::pin( admin::create_merchant_account(state.clone(), merchant_account_create_request), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while creating a merchant")? else { return Err(UserErrors::InternalServerError.into()); }; let key_manager_state = &(&state).into(); let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_account_response.merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve merchant key store by merchant_id")?; let merchant_account = state .store .find_merchant_account_by_merchant_id( key_manager_state, &merchant_account_response.merchant_id, &merchant_key_store, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve merchant account by merchant_id")?; Ok(merchant_account) } #[cfg(feature = "v2")] pub async fn create_new_merchant_and_insert_in_db( &self, state: SessionState, ) -> UserResult<domain::MerchantAccount> { self.check_if_already_exists_in_db(state.clone()).await?; let merchant_account_create_request = self .create_merchant_account_request() .attach_printable("unable to construct merchant account create request")?; let ApplicationResponse::Json(merchant_account_response) = Box::pin( admin::create_merchant_account(state.clone(), merchant_account_create_request), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while creating a merchant")? else { return Err(UserErrors::InternalServerError.into()); }; let profile_create_request = admin_api::ProfileCreate { profile_name: consts::user::DEFAULT_PROFILE_NAME.to_string(), ..Default::default() }; let key_manager_state = &(&state).into(); let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_account_response.id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve merchant key store by merchant_id")?; let merchant_account = state .store .find_merchant_account_by_merchant_id( key_manager_state, &merchant_account_response.id, &merchant_key_store, ) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve merchant account by merchant_id")?; Box::pin(admin::create_profile( state, profile_create_request, merchant_account.clone(), merchant_key_store, )) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error while creating a profile")?; Ok(merchant_account) } } impl TryFrom<user_api::SignUpRequest> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::SignUpRequest) -> UserResult<Self> { let merchant_id = id_type::MerchantId::new_from_unix_timestamp(); let new_organization = NewUserOrganization::from(value); let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE); Ok(Self { company_name: None, merchant_id, new_organization, product_type, }) } } impl TryFrom<user_api::ConnectAccountRequest> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::ConnectAccountRequest) -> UserResult<Self> { let merchant_id = id_type::MerchantId::new_from_unix_timestamp(); let new_organization = NewUserOrganization::from(value); let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE); Ok(Self { company_name: None, merchant_id, new_organization, product_type, }) } } impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> { let company_name = Some(UserCompanyName::new(value.company_name.clone())?); let merchant_id = MerchantId::new(value.company_name.clone())?; let new_organization = NewUserOrganization::try_from(value)?; let product_type = Some(consts::user::DEFAULT_PRODUCT_TYPE); Ok(Self { company_name, merchant_id: id_type::MerchantId::try_from(merchant_id)?, new_organization, product_type, }) } } impl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from( value: (user_api::CreateInternalUserRequest, id_type::OrganizationId), ) -> UserResult<Self> { let merchant_id = id_type::MerchantId::get_internal_user_merchant_id( consts::user_role::INTERNAL_USER_MERCHANT_ID, ); let new_organization = NewUserOrganization::from(value); Ok(Self { company_name: None, merchant_id, new_organization, product_type: None, }) } } impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from(value: InviteeUserRequestWithInvitedUserToken) -> UserResult<Self> { let merchant_id = value.clone().1.merchant_id; let new_organization = NewUserOrganization::from(value); Ok(Self { company_name: None, merchant_id, new_organization, product_type: None, }) } } impl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUserMerchant { fn from(value: (user_api::CreateTenantUserRequest, MerchantAccountIdentifier)) -> Self { let merchant_id = value.1.merchant_id.clone(); let new_organization = NewUserOrganization::from(value); Self { company_name: None, merchant_id, new_organization, product_type: None, } } } type UserMerchantCreateRequestWithToken = (UserFromStorage, user_api::UserMerchantCreate, UserFromToken); impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant { type Error = error_stack::Report<UserErrors>; fn try_from(value: UserMerchantCreateRequestWithToken) -> UserResult<Self> { let merchant_id = if matches!(env::which(), env::Env::Production) { id_type::MerchantId::try_from(MerchantId::new(value.1.company_name.clone())?)? } else { id_type::MerchantId::new_from_unix_timestamp() }; let (user_from_storage, user_merchant_create, user_from_token) = value; Ok(Self { merchant_id, company_name: Some(UserCompanyName::new( user_merchant_create.company_name.clone(), )?), product_type: user_merchant_create.product_type, new_organization: NewUserOrganization::from(( user_from_storage, user_merchant_create, user_from_token, )), }) } } #[derive(Debug, Clone)] pub struct MerchantAccountIdentifier { pub merchant_id: id_type::MerchantId, pub org_id: id_type::OrganizationId, } #[derive(Clone)] pub struct NewUser { user_id: String, name: UserName, email: UserEmail, password: Option<NewUserPassword>, new_merchant: NewUserMerchant, } #[derive(Clone)] pub struct NewUserPassword { password: UserPassword, is_temporary: bool, } impl Deref for NewUserPassword { type Target = UserPassword; fn deref(&self) -> &Self::Target { &self.password } } impl NewUser { pub fn get_user_id(&self) -> String { self.user_id.clone() } pub fn get_email(&self) -> UserEmail { self.email.clone() } pub fn get_name(&self) -> Secret<String> { self.name.clone().get_secret() } pub fn get_new_merchant(&self) -> NewUserMerchant { self.new_merchant.clone() } pub fn get_password(&self) -> Option<UserPassword> { self.password .as_ref() .map(|password| password.deref().clone()) } pub async fn insert_user_in_db( &self, db: &dyn GlobalStorageInterface, ) -> UserResult<UserFromStorage> { match db.insert_user(self.clone().try_into()?).await { Ok(user) => Ok(user.into()), Err(e) => { if e.current_context().is_db_unique_violation() { Err(e.change_context(UserErrors::UserExists)) } else { Err(e.change_context(UserErrors::InternalServerError)) } } } .attach_printable("Error while inserting user") } pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> { if state .global_store .find_user_by_email(&self.get_email()) .await .is_ok() { return Err(report!(UserErrors::UserExists)); } Ok(()) } pub async fn insert_user_and_merchant_in_db( &self, state: SessionState, ) -> UserResult<UserFromStorage> { self.check_if_already_exists_in_db(state.clone()).await?; let db = state.global_store.as_ref(); let merchant_id = self.get_new_merchant().get_merchant_id(); self.new_merchant .create_new_merchant_and_insert_in_db(state.clone()) .await?; let created_user = self.insert_user_in_db(db).await; if created_user.is_err() { let _ = admin::merchant_account_delete(state, merchant_id).await; }; created_user } pub fn get_no_level_user_role( self, role_id: String, user_status: UserStatus, ) -> NewUserRole<NoLevel> { let now = common_utils::date_time::now(); let user_id = self.get_user_id(); NewUserRole { status: user_status, created_by: user_id.clone(), last_modified_by: user_id.clone(), user_id, role_id, created_at: now, last_modified: now, entity: NoLevel, } } pub async fn insert_org_level_user_role_in_db( self, state: SessionState, role_id: String, user_status: UserStatus, ) -> UserResult<UserRole> { let org_id = self .get_new_merchant() .get_new_organization() .get_organization_id(); let org_user_role = self .get_no_level_user_role(role_id, user_status) .add_entity(OrganizationLevel { tenant_id: state.tenant.tenant_id.clone(), org_id, }); org_user_role.insert_in_v2(&state).await } } impl TryFrom<NewUser> for storage_user::UserNew { type Error = error_stack::Report<UserErrors>; fn try_from(value: NewUser) -> UserResult<Self> { let hashed_password = value .password .as_ref() .map(|password| password::generate_password_hash(password.get_secret())) .transpose()?; let now = common_utils::date_time::now(); Ok(Self { user_id: value.get_user_id(), name: value.get_name(), email: value.get_email().into_inner(), password: hashed_password, is_verified: false, created_at: Some(now), last_modified_at: Some(now), totp_status: TotpStatus::NotSet, totp_secret: None, totp_recovery_codes: None, last_password_modified_at: value .password .and_then(|password_inner| password_inner.is_temporary.not().then_some(now)), }) } } impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::SignUpWithMerchantIdRequest) -> UserResult<Self> { let email = value.email.clone().try_into()?; let name = UserName::new(value.name.clone())?; let password = NewUserPassword { password: UserPassword::new(value.password.clone())?, is_temporary: false, }; let user_id = uuid::Uuid::new_v4().to_string(); let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self { name, email, password: Some(password), user_id, new_merchant, }) } } impl TryFrom<user_api::SignUpRequest> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::SignUpRequest) -> UserResult<Self> { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.email.clone().try_into()?; let name = UserName::try_from(value.email.clone())?; let password = NewUserPassword { password: UserPassword::new(value.password.clone())?, is_temporary: false, }; let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self { user_id, name, email, password: Some(password), new_merchant, }) } } impl TryFrom<user_api::ConnectAccountRequest> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from(value: user_api::ConnectAccountRequest) -> UserResult<Self> { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.email.clone().try_into()?; let name = UserName::try_from(value.email.clone())?; let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self { user_id, name, email, password: None, new_merchant, }) } } impl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from( (value, org_id): (user_api::CreateInternalUserRequest, id_type::OrganizationId), ) -> UserResult<Self> { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.email.clone().try_into()?; let name = UserName::new(value.name.clone())?; let password = NewUserPassword { password: UserPassword::new(value.password.clone())?, is_temporary: false, }; let new_merchant = NewUserMerchant::try_from((value, org_id))?; Ok(Self { user_id, name, email, password: Some(password), new_merchant, }) } } impl TryFrom<UserMerchantCreateRequestWithToken> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from(value: UserMerchantCreateRequestWithToken) -> Result<Self, Self::Error> { let user = value.0.clone(); let new_merchant = NewUserMerchant::try_from(value)?; let password = user .0 .password .map(UserPassword::new_password_without_validation) .transpose()? .map(|password| NewUserPassword { password, is_temporary: false, }); Ok(Self { user_id: user.0.user_id, name: UserName::new(user.0.name)?, email: user.0.email.clone().try_into()?, password, new_merchant, }) } } impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from(value: InviteeUserRequestWithInvitedUserToken) -> UserResult<Self> { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.0.email.clone().try_into()?; let name = UserName::new(value.0.name.clone())?; let password = cfg!(not(feature = "email")).then_some(NewUserPassword { password: UserPassword::new(password::get_temp_password())?, is_temporary: true, }); let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self { user_id, name, email, password, new_merchant, }) } } impl TryFrom<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUser { type Error = error_stack::Report<UserErrors>; fn try_from( (value, merchant_account_identifier): ( user_api::CreateTenantUserRequest, MerchantAccountIdentifier, ), ) -> UserResult<Self> { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.email.clone().try_into()?; let name = UserName::new(value.name.clone())?; let password = NewUserPassword { password: UserPassword::new(value.password.clone())?, is_temporary: false, }; let new_merchant = NewUserMerchant::from((value, merchant_account_identifier)); Ok(Self { user_id, name, email, password: Some(password), new_merchant, }) } } #[derive(Clone)] pub struct UserFromStorage(pub storage_user::User); impl From<storage_user::User> for UserFromStorage { fn from(value: storage_user::User) -> Self { Self(value) } } impl UserFromStorage { pub fn get_user_id(&self) -> &str { self.0.user_id.as_str() } pub fn compare_password(&self, candidate: &Secret<String>) -> UserResult<()> { if let Some(password) = self.0.password.as_ref() { match password::is_correct_password(candidate, password) { Ok(true) => Ok(()), Ok(false) => Err(UserErrors::InvalidCredentials.into()), Err(e) => Err(e), } } else { Err(UserErrors::InvalidCredentials.into()) } } pub fn get_name(&self) -> Secret<String> { self.0.name.clone() } pub fn get_email(&self) -> pii::Email { self.0.email.clone() } #[cfg(feature = "email")] pub fn get_verification_days_left(&self, state: &SessionState) -> UserResult<Option<i64>> { if self.0.is_verified { return Ok(None); } let allowed_unverified_duration = time::Duration::days(state.conf.email.allowed_unverified_days); let user_created = self.0.created_at.date(); let last_date_for_verification = user_created .checked_add(allowed_unverified_duration) .ok_or(UserErrors::InternalServerError)?; let today = common_utils::date_time::now().date(); if today >= last_date_for_verification { return Err(UserErrors::UnverifiedUser.into()); } let days_left_for_verification = last_date_for_verification - today; Ok(Some(days_left_for_verification.whole_days())) } pub fn is_verified(&self) -> bool { self.0.is_verified } pub fn is_password_rotate_required(&self, state: &SessionState) -> UserResult<bool> { let last_password_modified_at = if let Some(last_password_modified_at) = self.0.last_password_modified_at { last_password_modified_at.date() } else { return Ok(true); }; let password_change_duration = time::Duration::days(state.conf.user.password_validity_in_days.into()); let last_date_for_password_rotate = last_password_modified_at .checked_add(password_change_duration) .ok_or(UserErrors::InternalServerError)?; let today = common_utils::date_time::now().date(); let days_left_for_password_rotate = last_date_for_password_rotate - today; Ok(days_left_for_password_rotate.whole_days() < 0) } pub async fn get_or_create_key_store(&self, state: &SessionState) -> UserResult<UserKeyStore> { let master_key = state.store.get_master_key(); let key_manager_state = &state.into(); let key_store_result = state .global_store .get_user_key_store_by_user_id( key_manager_state, self.get_user_id(), &master_key.to_vec().into(), ) .await; if let Ok(key_store) = key_store_result { Ok(key_store) } else if key_store_result .as_ref() .map_err(|e| e.current_context().is_db_not_found()) .err() .unwrap_or(false) { let key = services::generate_aes256_key() .change_context(UserErrors::InternalServerError) .attach_printable("Unable to generate aes 256 key")?; #[cfg(feature = "keymanager_create")] { common_utils::keymanager::transfer_key_to_key_manager( key_manager_state, EncryptionTransferRequest { identifier: Identifier::User(self.get_user_id().to_string()), key: consts::BASE64_ENGINE.encode(key), }, ) .await .change_context(UserErrors::InternalServerError)?; } let key_store = UserKeyStore { user_id: self.get_user_id().to_string(), key: domain_types::crypto_operation( key_manager_state, type_name!(UserKeyStore), domain_types::CryptoOperation::Encrypt(key.to_vec().into()), Identifier::User(self.get_user_id().to_string()), master_key, ) .await .and_then(|val| val.try_into_operation()) .change_context(UserErrors::InternalServerError)?, created_at: common_utils::date_time::now(), }; state .global_store .insert_user_key_store(key_manager_state, key_store, &master_key.to_vec().into()) .await .change_context(UserErrors::InternalServerError) } else { Err(key_store_result .err() .map(|e| e.change_context(UserErrors::InternalServerError)) .unwrap_or(UserErrors::InternalServerError.into())) } } pub fn get_totp_status(&self) -> TotpStatus { self.0.totp_status } pub fn get_recovery_codes(&self) -> Option<Vec<Secret<String>>> { self.0.totp_recovery_codes.clone() } pub async fn decrypt_and_get_totp_secret( &self, state: &SessionState, ) -> UserResult<Option<Secret<String>>> { if self.0.totp_secret.is_none() { return Ok(None); } let key_manager_state = &state.into(); let user_key_store = state .global_store .get_user_key_store_by_user_id( key_manager_state, self.get_user_id(), &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError)?; Ok(domain_types::crypto_operation::<String, masking::WithType>( key_manager_state, type_name!(storage_user::User), domain_types::CryptoOperation::DecryptOptional(self.0.totp_secret.clone()), Identifier::User(user_key_store.user_id.clone()), user_key_store.key.peek(), ) .await .and_then(|val| val.try_into_optionaloperation()) .change_context(UserErrors::InternalServerError)? .map(Encryptable::into_inner)) } } impl ForeignFrom<UserStatus> for user_role_api::UserStatus { fn foreign_from(value: UserStatus) -> Self { match value { UserStatus::Active => Self::Active, UserStatus::InvitationSent => Self::InvitationSent, } } } #[derive(Clone)] pub struct RoleName(String); impl RoleName { pub fn new(name: String) -> UserResult<Self> { let is_empty_or_whitespace = name.trim().is_empty(); let is_too_long = name.graphemes(true).count() > consts::user_role::MAX_ROLE_NAME_LENGTH; if is_empty_or_whitespace || is_too_long || name.contains(' ') { Err(UserErrors::RoleNameParsingError.into()) } else { Ok(Self(name.to_lowercase())) } } pub fn get_role_name(self) -> String { self.0 } } #[derive(serde::Serialize, serde::Deserialize, Debug)] pub struct RecoveryCodes(pub Vec<Secret<String>>); impl RecoveryCodes { pub fn generate_new() -> Self { let mut rand = rand::thread_rng(); let recovery_codes = (0..consts::user::RECOVERY_CODES_COUNT) .map(|_| { let code_part_1 = Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2); let code_part_2 = Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2); Secret::new(format!("{}-{}", code_part_1, code_part_2)) }) .collect::<Vec<_>>(); Self(recovery_codes) } pub fn get_hashed(&self) -> UserResult<Vec<Secret<String>>> { self.0 .iter() .cloned() .map(password::generate_password_hash) .collect::<Result<Vec<_>, _>>() } pub fn into_inner(self) -> Vec<Secret<String>> { self.0 } } // This is for easier construction #[derive(Clone)] pub struct NoLevel; #[derive(Clone)] pub struct TenantLevel { pub tenant_id: id_type::TenantId, } #[derive(Clone)] pub struct OrganizationLevel { pub tenant_id: id_type::TenantId, pub org_id: id_type::OrganizationId, } #[derive(Clone)] pub struct MerchantLevel { pub tenant_id: id_type::TenantId, pub org_id: id_type::OrganizationId, pub merchant_id: id_type::MerchantId, } #[derive(Clone)] pub struct ProfileLevel { pub tenant_id: id_type::TenantId, pub org_id: id_type::OrganizationId, pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, } #[derive(Clone)] pub struct NewUserRole<E: Clone> { pub user_id: String, pub role_id: String, pub status: UserStatus, pub created_by: String, pub last_modified_by: String, pub created_at: PrimitiveDateTime, pub last_modified: PrimitiveDateTime, pub entity: E, } impl NewUserRole<NoLevel> { pub fn add_entity<T>(self, entity: T) -> NewUserRole<T> where T: Clone, { NewUserRole { entity, user_id: self.user_id, role_id: self.role_id, status: self.status, created_by: self.created_by, last_modified_by: self.last_modified_by, created_at: self.created_at, last_modified: self.last_modified, } } } pub struct EntityInfo { tenant_id: id_type::TenantId, org_id: Option<id_type::OrganizationId>, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, entity_id: String, entity_type: EntityType, } impl From<TenantLevel> for EntityInfo { fn from(value: TenantLevel) -> Self { Self { entity_id: value.tenant_id.get_string_repr().to_owned(), entity_type: EntityType::Tenant, tenant_id: value.tenant_id, org_id: None, merchant_id: None, profile_id: None, } } } impl From<OrganizationLevel> for EntityInfo { fn from(value: OrganizationLevel) -> Self { Self { entity_id: value.org_id.get_string_repr().to_owned(), entity_type: EntityType::Organization, tenant_id: value.tenant_id, org_id: Some(value.org_id), merchant_id: None, profile_id: None, } } } impl From<MerchantLevel> for EntityInfo { fn from(value: MerchantLevel) -> Self { Self { entity_id: value.merchant_id.get_string_repr().to_owned(), entity_type: EntityType::Merchant, tenant_id: value.tenant_id, org_id: Some(value.org_id), merchant_id: Some(value.merchant_id), profile_id: None, } } } impl From<ProfileLevel> for EntityInfo { fn from(value: ProfileLevel) -> Self { Self { entity_id: value.profile_id.get_string_repr().to_owned(), entity_type: EntityType::Profile, tenant_id: value.tenant_id, org_id: Some(value.org_id), merchant_id: Some(value.merchant_id), profile_id: Some(value.profile_id), } } } impl<E> NewUserRole<E> where E: Clone + Into<EntityInfo>, { fn convert_to_new_v2_role(self, entity: EntityInfo) -> UserRoleNew { UserRoleNew { user_id: self.user_id, role_id: self.role_id, status: self.status, created_by: self.created_by, last_modified_by: self.last_modified_by, created_at: self.created_at, last_modified: self.last_modified, org_id: entity.org_id, merchant_id: entity.merchant_id, profile_id: entity.profile_id, entity_id: Some(entity.entity_id), entity_type: Some(entity.entity_type), version: UserRoleVersion::V2, tenant_id: entity.tenant_id, } } pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> { let entity = self.entity.clone(); let new_v2_role = self.convert_to_new_v2_role(entity.into()); state .global_store .insert_user_role(new_v2_role) .await .change_context(UserErrors::InternalServerError) } }
10,142
1,420
hyperswitch
crates/router/src/types/domain/payments.rs
.rs
pub use hyperswitch_domain_models::payment_method_data::{ AliPayQr, ApplePayFlow, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod, BankDebitData, BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardDetail, CardRedirectData, CardToken, CashappQr, CryptoData, GcashRedirection, GiftCardData, GiftCardDetails, GoPayRedirection, GooglePayPaymentMethodInfo, GooglePayRedirectData, GooglePayThirdPartySdkData, GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, KakaoPayRedirection, MbWayRedirection, MifinityData, NetworkTokenData, OpenBankingData, PayLaterData, PaymentMethodData, RealTimePaymentData, SamsungPayWalletData, SepaAndBacsBillingDetails, SwishQrData, TokenizedBankDebitValue1, TokenizedBankDebitValue2, TokenizedBankRedirectValue1, TokenizedBankRedirectValue2, TokenizedBankTransferValue1, TokenizedBankTransferValue2, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, TouchNGoRedirection, UpiCollectData, UpiData, UpiIntentData, VoucherData, WalletData, WeChatPayQr, };
301
1,421
hyperswitch
crates/router/src/types/domain/address.rs
.rs
use async_trait::async_trait; use common_utils::{ crypto::{self, Encryptable}, date_time, encryption::Encryption, errors::{CustomResult, ValidationError}, id_type, pii, type_name, types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, }; use diesel_models::{address::AddressUpdateInternal, enums}; use error_stack::ResultExt; use masking::{PeekInterface, Secret, SwitchStrategy}; use rustc_hash::FxHashMap; use time::{OffsetDateTime, PrimitiveDateTime}; use super::{behaviour, types}; #[derive(Clone, Debug, serde::Serialize, router_derive::ToEncryption)] pub struct Address { pub address_id: String, pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, #[encrypt] pub line1: Option<Encryptable<Secret<String>>>, #[encrypt] pub line2: Option<Encryptable<Secret<String>>>, #[encrypt] pub line3: Option<Encryptable<Secret<String>>>, #[encrypt] pub state: Option<Encryptable<Secret<String>>>, #[encrypt] pub zip: Option<Encryptable<Secret<String>>>, #[encrypt] pub first_name: Option<Encryptable<Secret<String>>>, #[encrypt] pub last_name: Option<Encryptable<Secret<String>>>, #[encrypt] pub phone_number: Option<Encryptable<Secret<String>>>, pub country_code: Option<String>, #[serde(skip_serializing)] #[serde(with = "custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(skip_serializing)] #[serde(with = "custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub merchant_id: id_type::MerchantId, pub updated_by: String, #[encrypt] pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>, } /// Based on the flow, appropriate address has to be used /// In case of Payments, The `PaymentAddress`[PaymentAddress] has to be used /// which contains only the `Address`[Address] object and `payment_id` and optional `customer_id` #[derive(Debug, Clone)] pub struct PaymentAddress { pub address: Address, pub payment_id: id_type::PaymentId, // This is present in `PaymentAddress` because even `payouts` uses `PaymentAddress` pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, Clone)] pub struct CustomerAddress { pub address: Address, pub customer_id: id_type::CustomerId, } #[async_trait] impl behaviour::Conversion for CustomerAddress { type DstType = diesel_models::address::Address; type NewDstType = diesel_models::address::AddressNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let converted_address = Address::convert(self.address).await?; Ok(diesel_models::address::Address { customer_id: Some(self.customer_id), payment_id: None, ..converted_address }) } async fn convert_back( state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> { let customer_id = other .customer_id .clone() .ok_or(ValidationError::MissingRequiredField { field_name: "customer_id".to_string(), })?; let address = Address::convert_back(state, other, key, key_manager_identifier).await?; Ok(Self { address, customer_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let address_new = Address::construct_new(self.address).await?; Ok(Self::NewDstType { customer_id: Some(self.customer_id), payment_id: None, ..address_new }) } } #[async_trait] impl behaviour::Conversion for PaymentAddress { type DstType = diesel_models::address::Address; type NewDstType = diesel_models::address::AddressNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { let converted_address = Address::convert(self.address).await?; Ok(diesel_models::address::Address { customer_id: self.customer_id, payment_id: Some(self.payment_id), ..converted_address }) } async fn convert_back( state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> { let payment_id = other .payment_id .clone() .ok_or(ValidationError::MissingRequiredField { field_name: "payment_id".to_string(), })?; let customer_id = other.customer_id.clone(); let address = Address::convert_back(state, other, key, key_manager_identifier).await?; Ok(Self { address, payment_id, customer_id, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let address_new = Address::construct_new(self.address).await?; Ok(Self::NewDstType { customer_id: self.customer_id, payment_id: Some(self.payment_id), ..address_new }) } } #[async_trait] impl behaviour::Conversion for Address { type DstType = diesel_models::address::Address; type NewDstType = diesel_models::address::AddressNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::address::Address { address_id: self.address_id, city: self.city, country: self.country, line1: self.line1.map(Encryption::from), line2: self.line2.map(Encryption::from), line3: self.line3.map(Encryption::from), state: self.state.map(Encryption::from), zip: self.zip.map(Encryption::from), first_name: self.first_name.map(Encryption::from), last_name: self.last_name.map(Encryption::from), phone_number: self.phone_number.map(Encryption::from), country_code: self.country_code, created_at: self.created_at, modified_at: self.modified_at, merchant_id: self.merchant_id, updated_by: self.updated_by, email: self.email.map(Encryption::from), payment_id: None, customer_id: None, }) } async fn convert_back( state: &KeyManagerState, other: Self::DstType, key: &Secret<Vec<u8>>, _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> { let identifier = Identifier::Merchant(other.merchant_id.clone()); let decrypted: FxHashMap<String, Encryptable<Secret<String>>> = types::crypto_operation( state, type_name!(Self::DstType), types::CryptoOperation::BatchDecrypt(EncryptedAddress::to_encryptable( EncryptedAddress { line1: other.line1, line2: other.line2, line3: other.line3, state: other.state, zip: other.zip, first_name: other.first_name, last_name: other.last_name, phone_number: other.phone_number, email: other.email, }, )), identifier.clone(), key.peek(), ) .await .and_then(|val| val.try_into_batchoperation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting".to_string(), })?; let encryptable_address = EncryptedAddress::from_encryptable(decrypted).change_context( ValidationError::InvalidValue { message: "Failed while decrypting".to_string(), }, )?; Ok(Self { address_id: other.address_id, city: other.city, country: other.country, line1: encryptable_address.line1, line2: encryptable_address.line2, line3: encryptable_address.line3, state: encryptable_address.state, zip: encryptable_address.zip, first_name: encryptable_address.first_name, last_name: encryptable_address.last_name, phone_number: encryptable_address.phone_number, country_code: other.country_code, created_at: other.created_at, modified_at: other.modified_at, updated_by: other.updated_by, merchant_id: other.merchant_id, email: encryptable_address.email.map(|email| { let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new( email.clone().into_inner().switch_strategy(), email.into_encrypted(), ); encryptable }), }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { let now = date_time::now(); Ok(Self::NewDstType { address_id: self.address_id, city: self.city, country: self.country, line1: self.line1.map(Encryption::from), line2: self.line2.map(Encryption::from), line3: self.line3.map(Encryption::from), state: self.state.map(Encryption::from), zip: self.zip.map(Encryption::from), first_name: self.first_name.map(Encryption::from), last_name: self.last_name.map(Encryption::from), phone_number: self.phone_number.map(Encryption::from), country_code: self.country_code, merchant_id: self.merchant_id, created_at: now, modified_at: now, updated_by: self.updated_by, email: self.email.map(Encryption::from), customer_id: None, payment_id: None, }) } } #[derive(Debug, Clone)] pub enum AddressUpdate { Update { city: Option<String>, country: Option<enums::CountryAlpha2>, line1: crypto::OptionalEncryptableSecretString, line2: crypto::OptionalEncryptableSecretString, line3: crypto::OptionalEncryptableSecretString, state: crypto::OptionalEncryptableSecretString, zip: crypto::OptionalEncryptableSecretString, first_name: crypto::OptionalEncryptableSecretString, last_name: crypto::OptionalEncryptableSecretString, phone_number: crypto::OptionalEncryptableSecretString, country_code: Option<String>, updated_by: String, email: crypto::OptionalEncryptableEmail, }, } impl From<AddressUpdate> for AddressUpdateInternal { fn from(address_update: AddressUpdate) -> Self { match address_update { AddressUpdate::Update { city, country, line1, line2, line3, state, zip, first_name, last_name, phone_number, country_code, updated_by, email, } => Self { city, country, line1: line1.map(Encryption::from), line2: line2.map(Encryption::from), line3: line3.map(Encryption::from), state: state.map(Encryption::from), zip: zip.map(Encryption::from), first_name: first_name.map(Encryption::from), last_name: last_name.map(Encryption::from), phone_number: phone_number.map(Encryption::from), country_code, modified_at: date_time::convert_to_pdt(OffsetDateTime::now_utc()), updated_by, email: email.map(Encryption::from), }, } } }
2,505
1,422
hyperswitch
crates/router/src/types/domain/user_key_store.rs
.rs
use common_utils::{ crypto::Encryptable, date_time, type_name, types::keymanager::{Identifier, KeyManagerState}, }; use error_stack::ResultExt; use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; use masking::{PeekInterface, Secret}; use time::PrimitiveDateTime; use crate::errors::{CustomResult, ValidationError}; #[derive(Clone, Debug, serde::Serialize)] pub struct UserKeyStore { pub user_id: String, pub key: Encryptable<Secret<Vec<u8>>>, pub created_at: PrimitiveDateTime, } #[async_trait::async_trait] impl super::behaviour::Conversion for UserKeyStore { type DstType = diesel_models::user_key_store::UserKeyStore; type NewDstType = diesel_models::user_key_store::UserKeyStoreNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::user_key_store::UserKeyStore { key: self.key.into(), user_id: self.user_id, created_at: self.created_at, }) } async fn convert_back( state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { let identifier = Identifier::User(item.user_id.clone()); Ok(Self { key: crypto_operation( state, type_name!(Self::DstType), CryptoOperation::Decrypt(item.key), identifier, key.peek(), ) .await .and_then(|val| val.try_into_operation()) .change_context(ValidationError::InvalidValue { message: "Failed while decrypting customer data".to_string(), })?, user_id: item.user_id, created_at: item.created_at, }) } async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { Ok(diesel_models::user_key_store::UserKeyStoreNew { user_id: self.user_id, key: self.key.into(), created_at: date_time::now(), }) } }
470
1,423
hyperswitch
crates/router/src/types/domain/types.rs
.rs
use common_utils::types::keymanager::KeyManagerState; pub use hyperswitch_domain_models::type_encryption::{ crypto_operation, AsyncLift, CryptoOperation, Lift, OptionalEncryptableJsonType, }; impl From<&crate::SessionState> for KeyManagerState { fn from(state: &crate::SessionState) -> Self { let conf = state.conf.key_manager.get_inner(); Self { global_tenant_id: state.conf.multitenancy.global_tenant.tenant_id.clone(), tenant_id: state.tenant.tenant_id.clone(), enabled: conf.enabled, url: conf.url.clone(), client_idle_timeout: state.conf.proxy.idle_pool_connection_timeout, #[cfg(feature = "km_forward_x_request_id")] request_id: state.request_id, #[cfg(feature = "keymanager_mtls")] cert: conf.cert.clone(), #[cfg(feature = "keymanager_mtls")] ca: conf.ca.clone(), } } }
204
1,424
hyperswitch
crates/router/src/types/domain/merchant_connector_account.rs
.rs
pub use hyperswitch_domain_models::merchant_connector_account::*;
11
1,425
hyperswitch
crates/router/src/types/domain/user/decision_manager.rs
.rs
use common_enums::TokenPurpose; use common_utils::id_type; use diesel_models::{enums::UserStatus, user_role::UserRole}; use error_stack::ResultExt; use masking::Secret; use super::UserFromStorage; use crate::{ core::errors::{UserErrors, UserResult}, db::user_role::ListUserRolesByUserIdPayload, routes::SessionState, services::authentication as auth, utils, }; #[derive(Eq, PartialEq, Clone, Copy)] pub enum UserFlow { SPTFlow(SPTFlow), JWTFlow(JWTFlow), } impl UserFlow { async fn is_required( &self, user: &UserFromStorage, path: &[TokenPurpose], state: &SessionState, user_tenant_id: &id_type::TenantId, ) -> UserResult<bool> { match self { Self::SPTFlow(flow) => flow.is_required(user, path, state, user_tenant_id).await, Self::JWTFlow(flow) => flow.is_required(user, state).await, } } } #[derive(Eq, PartialEq, Clone, Copy)] pub enum SPTFlow { AuthSelect, SSO, TOTP, VerifyEmail, AcceptInvitationFromEmail, ForceSetPassword, MerchantSelect, ResetPassword, } impl SPTFlow { async fn is_required( &self, user: &UserFromStorage, path: &[TokenPurpose], state: &SessionState, user_tenant_id: &id_type::TenantId, ) -> UserResult<bool> { match self { // Auth Self::AuthSelect => Ok(true), Self::SSO => Ok(true), // TOTP Self::TOTP => Ok(!path.contains(&TokenPurpose::SSO)), // Main email APIs Self::AcceptInvitationFromEmail | Self::ResetPassword => Ok(true), Self::VerifyEmail => Ok(true), // Final Checks Self::ForceSetPassword => user .is_password_rotate_required(state) .map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)), Self::MerchantSelect => Ok(state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user.get_user_id(), tenant_id: user_tenant_id, org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::Active), limit: Some(1), }) .await .change_context(UserErrors::InternalServerError)? .is_empty()), } } pub async fn generate_spt( self, state: &SessionState, next_flow: &NextFlow, ) -> UserResult<Secret<String>> { auth::SinglePurposeToken::new_token( next_flow.user.get_user_id().to_string(), self.into(), next_flow.origin.clone(), &state.conf, next_flow.path.to_vec(), Some(state.tenant.tenant_id.clone()), ) .await .map(|token| token.into()) } } #[derive(Eq, PartialEq, Clone, Copy)] pub enum JWTFlow { UserInfo, } impl JWTFlow { async fn is_required( &self, _user: &UserFromStorage, _state: &SessionState, ) -> UserResult<bool> { Ok(true) } pub async fn generate_jwt( self, state: &SessionState, next_flow: &NextFlow, user_role: &UserRole, ) -> UserResult<Secret<String>> { let org_id = utils::user_role::get_single_org_id(state, user_role).await?; let merchant_id = utils::user_role::get_single_merchant_id(state, user_role, &org_id).await?; let profile_id = utils::user_role::get_single_profile_id(state, user_role, &merchant_id).await?; auth::AuthToken::new_token( next_flow.user.get_user_id().to_string(), merchant_id, user_role.role_id.clone(), &state.conf, org_id, profile_id, Some(user_role.tenant_id.clone()), ) .await .map(|token| token.into()) } } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum Origin { #[serde(rename = "sign_in_with_sso")] SignInWithSSO, SignIn, SignUp, MagicLink, VerifyEmail, AcceptInvitationFromEmail, ResetPassword, } impl Origin { fn get_flows(&self) -> &'static [UserFlow] { match self { Self::SignInWithSSO => &SIGNIN_WITH_SSO_FLOW, Self::SignIn => &SIGNIN_FLOW, Self::SignUp => &SIGNUP_FLOW, Self::VerifyEmail => &VERIFY_EMAIL_FLOW, Self::MagicLink => &MAGIC_LINK_FLOW, Self::AcceptInvitationFromEmail => &ACCEPT_INVITATION_FROM_EMAIL_FLOW, Self::ResetPassword => &RESET_PASSWORD_FLOW, } } } const SIGNIN_WITH_SSO_FLOW: [UserFlow; 2] = [ UserFlow::SPTFlow(SPTFlow::MerchantSelect), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; const SIGNIN_FLOW: [UserFlow; 4] = [ UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), UserFlow::SPTFlow(SPTFlow::MerchantSelect), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; const SIGNUP_FLOW: [UserFlow; 4] = [ UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), UserFlow::SPTFlow(SPTFlow::MerchantSelect), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; const MAGIC_LINK_FLOW: [UserFlow; 5] = [ UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::VerifyEmail), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), UserFlow::SPTFlow(SPTFlow::MerchantSelect), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; const VERIFY_EMAIL_FLOW: [UserFlow; 5] = [ UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::VerifyEmail), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), UserFlow::SPTFlow(SPTFlow::MerchantSelect), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 6] = [ UserFlow::SPTFlow(SPTFlow::AuthSelect), UserFlow::SPTFlow(SPTFlow::SSO), UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::AcceptInvitationFromEmail), UserFlow::SPTFlow(SPTFlow::ForceSetPassword), UserFlow::JWTFlow(JWTFlow::UserInfo), ]; const RESET_PASSWORD_FLOW: [UserFlow; 2] = [ UserFlow::SPTFlow(SPTFlow::TOTP), UserFlow::SPTFlow(SPTFlow::ResetPassword), ]; pub struct CurrentFlow { origin: Origin, current_flow_index: usize, path: Vec<TokenPurpose>, tenant_id: Option<id_type::TenantId>, } impl CurrentFlow { pub fn new( token: auth::UserFromSinglePurposeToken, current_flow: UserFlow, ) -> UserResult<Self> { let flows = token.origin.get_flows(); let index = flows .iter() .position(|flow| flow == &current_flow) .ok_or(UserErrors::InternalServerError)?; let mut path = token.path; path.push(current_flow.into()); Ok(Self { origin: token.origin, current_flow_index: index, path, tenant_id: token.tenant_id, }) } pub async fn next(self, user: UserFromStorage, state: &SessionState) -> UserResult<NextFlow> { let flows = self.origin.get_flows(); let remaining_flows = flows.iter().skip(self.current_flow_index + 1); for flow in remaining_flows { if flow .is_required( &user, &self.path, state, self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), ) .await? { return Ok(NextFlow { origin: self.origin.clone(), next_flow: *flow, user, path: self.path, tenant_id: self.tenant_id, }); } } Err(UserErrors::InternalServerError.into()) } } pub struct NextFlow { origin: Origin, next_flow: UserFlow, user: UserFromStorage, path: Vec<TokenPurpose>, tenant_id: Option<id_type::TenantId>, } impl NextFlow { pub async fn from_origin( origin: Origin, user: UserFromStorage, state: &SessionState, ) -> UserResult<Self> { let flows = origin.get_flows(); let path = vec![]; for flow in flows { if flow .is_required(&user, &path, state, &state.tenant.tenant_id) .await? { return Ok(Self { origin, next_flow: *flow, user, path, tenant_id: Some(state.tenant.tenant_id.clone()), }); } } Err(UserErrors::InternalServerError.into()) } pub fn get_flow(&self) -> UserFlow { self.next_flow } pub async fn get_token(&self, state: &SessionState) -> UserResult<Secret<String>> { match self.next_flow { UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(state, self).await, UserFlow::JWTFlow(jwt_flow) => { #[cfg(feature = "email")] { self.user.get_verification_days_left(state)?; } let user_role = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: self.user.get_user_id(), tenant_id: self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::Active), limit: Some(1), }) .await .change_context(UserErrors::InternalServerError)? .pop() .ok_or(UserErrors::InternalServerError)?; utils::user_role::set_role_info_in_cache_by_user_role(state, &user_role).await; jwt_flow.generate_jwt(state, self, &user_role).await } } } pub async fn get_token_with_user_role( &self, state: &SessionState, user_role: &UserRole, ) -> UserResult<Secret<String>> { match self.next_flow { UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(state, self).await, UserFlow::JWTFlow(jwt_flow) => { #[cfg(feature = "email")] { self.user.get_verification_days_left(state)?; } utils::user_role::set_role_info_in_cache_by_user_role(state, user_role).await; jwt_flow.generate_jwt(state, self, user_role).await } } } pub async fn skip(self, user: UserFromStorage, state: &SessionState) -> UserResult<Self> { let flows = self.origin.get_flows(); let index = flows .iter() .position(|flow| flow == &self.get_flow()) .ok_or(UserErrors::InternalServerError)?; let remaining_flows = flows.iter().skip(index + 1); for flow in remaining_flows { if flow .is_required(&user, &self.path, state, &state.tenant.tenant_id) .await? { return Ok(Self { origin: self.origin.clone(), next_flow: *flow, user, path: self.path, tenant_id: Some(state.tenant.tenant_id.clone()), }); } } Err(UserErrors::InternalServerError.into()) } } impl From<UserFlow> for TokenPurpose { fn from(value: UserFlow) -> Self { match value { UserFlow::SPTFlow(flow) => flow.into(), UserFlow::JWTFlow(flow) => flow.into(), } } } impl From<SPTFlow> for TokenPurpose { fn from(value: SPTFlow) -> Self { match value { SPTFlow::AuthSelect => Self::AuthSelect, SPTFlow::SSO => Self::SSO, SPTFlow::TOTP => Self::TOTP, SPTFlow::VerifyEmail => Self::VerifyEmail, SPTFlow::AcceptInvitationFromEmail => Self::AcceptInvitationFromEmail, SPTFlow::MerchantSelect => Self::AcceptInvite, SPTFlow::ResetPassword => Self::ResetPassword, SPTFlow::ForceSetPassword => Self::ForceSetPassword, } } } impl From<JWTFlow> for TokenPurpose { fn from(value: JWTFlow) -> Self { match value { JWTFlow::UserInfo => Self::UserInfo, } } } impl From<SPTFlow> for UserFlow { fn from(value: SPTFlow) -> Self { Self::SPTFlow(value) } } impl From<JWTFlow> for UserFlow { fn from(value: JWTFlow) -> Self { Self::JWTFlow(value) } }
3,040
1,426
hyperswitch
crates/router/src/types/domain/user/user_authentication_method.rs
.rs
use common_enums::{Owner, UserAuthType}; use diesel_models::UserAuthenticationMethod; use once_cell::sync::Lazy; pub static DEFAULT_USER_AUTH_METHOD: Lazy<UserAuthenticationMethod> = Lazy::new(|| UserAuthenticationMethod { id: String::from("hyperswitch_default"), auth_id: String::from("hyperswitch"), owner_id: String::from("hyperswitch"), owner_type: Owner::Tenant, auth_type: UserAuthType::Password, private_config: None, public_config: None, allow_signup: true, created_at: common_utils::date_time::now(), last_modified_at: common_utils::date_time::now(), email_domain: String::from("hyperswitch"), });
160
1,427
hyperswitch
crates/router/src/types/domain/user/dashboard_metadata.rs
.rs
use api_models::user::dashboard_metadata as api; use diesel_models::enums::DashboardMetadata as DBEnum; use masking::Secret; use time::PrimitiveDateTime; pub enum MetaData { ProductionAgreement(ProductionAgreementValue), SetupProcessor(api::SetupProcessor), ConfigureEndpoint(bool), SetupComplete(bool), FirstProcessorConnected(api::ProcessorConnected), SecondProcessorConnected(api::ProcessorConnected), ConfiguredRouting(api::ConfiguredRouting), TestPayment(api::TestPayment), IntegrationMethod(api::IntegrationMethod), ConfigurationType(api::ConfigurationType), IntegrationCompleted(bool), StripeConnected(api::ProcessorConnected), PaypalConnected(api::ProcessorConnected), SPRoutingConfigured(api::ConfiguredRouting), Feedback(api::Feedback), ProdIntent(api::ProdIntent), SPTestPayment(bool), DownloadWoocom(bool), ConfigureWoocom(bool), SetupWoocomWebhook(bool), IsMultipleConfiguration(bool), IsChangePasswordRequired(bool), OnboardingSurvey(api::OnboardingSurvey), ReconStatus(api::ReconStatus), } impl From<&MetaData> for DBEnum { fn from(value: &MetaData) -> Self { match value { MetaData::ProductionAgreement(_) => Self::ProductionAgreement, MetaData::SetupProcessor(_) => Self::SetupProcessor, MetaData::ConfigureEndpoint(_) => Self::ConfigureEndpoint, MetaData::SetupComplete(_) => Self::SetupComplete, MetaData::FirstProcessorConnected(_) => Self::FirstProcessorConnected, MetaData::SecondProcessorConnected(_) => Self::SecondProcessorConnected, MetaData::ConfiguredRouting(_) => Self::ConfiguredRouting, MetaData::TestPayment(_) => Self::TestPayment, MetaData::IntegrationMethod(_) => Self::IntegrationMethod, MetaData::ConfigurationType(_) => Self::ConfigurationType, MetaData::IntegrationCompleted(_) => Self::IntegrationCompleted, MetaData::StripeConnected(_) => Self::StripeConnected, MetaData::PaypalConnected(_) => Self::PaypalConnected, MetaData::SPRoutingConfigured(_) => Self::SpRoutingConfigured, MetaData::Feedback(_) => Self::Feedback, MetaData::ProdIntent(_) => Self::ProdIntent, MetaData::SPTestPayment(_) => Self::SpTestPayment, MetaData::DownloadWoocom(_) => Self::DownloadWoocom, MetaData::ConfigureWoocom(_) => Self::ConfigureWoocom, MetaData::SetupWoocomWebhook(_) => Self::SetupWoocomWebhook, MetaData::IsMultipleConfiguration(_) => Self::IsMultipleConfiguration, MetaData::IsChangePasswordRequired(_) => Self::IsChangePasswordRequired, MetaData::OnboardingSurvey(_) => Self::OnboardingSurvey, MetaData::ReconStatus(_) => Self::ReconStatus, } } } #[derive(Debug, serde::Serialize)] pub struct ProductionAgreementValue { pub version: String, pub ip_address: Secret<String, common_utils::pii::IpAddress>, pub timestamp: PrimitiveDateTime, }
643
1,428
hyperswitch
crates/router/src/compatibility/stripe.rs
.rs
pub mod app; pub mod customers; pub mod payment_intents; pub mod refunds; pub mod setup_intents; pub mod webhooks; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use actix_web::{web, Scope}; pub mod errors; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::routes; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] pub struct StripeApis; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl StripeApis { pub fn server(state: routes::AppState) -> Scope { let max_depth = 10; let strict = false; web::scope("/vs/v1") .app_data(web::Data::new(serde_qs::Config::new(max_depth, strict))) .service(app::SetupIntents::server(state.clone())) .service(app::PaymentIntents::server(state.clone())) .service(app::Refunds::server(state.clone())) .service(app::Customers::server(state.clone())) .service(app::Webhooks::server(state.clone())) .service(app::Mandates::server(state)) } }
290
1,429
hyperswitch
crates/router/src/compatibility/wrap.rs
.rs
use std::{future::Future, sync::Arc, time::Instant}; use actix_web::{HttpRequest, HttpResponse, Responder}; use common_utils::errors::{CustomResult, ErrorSwitch}; use router_env::{instrument, tracing, Tag}; use serde::Serialize; use crate::{ core::{api_locking, errors}, events::api_logs::ApiEventMetric, routes::{ app::{AppStateInfo, ReqState}, metrics, AppState, SessionState, }, services::{self, api, authentication as auth, logger}, }; #[instrument(skip(request, payload, state, func, api_authentication))] pub async fn compatibility_api_wrap<'a, 'b, U, T, Q, F, Fut, S, E, E2>( flow: impl router_env::types::FlowMetric, state: Arc<AppState>, request: &'a HttpRequest, payload: T, func: F, api_authentication: &dyn auth::AuthenticateAndFetch<U, SessionState>, lock_action: api_locking::LockAction, ) -> HttpResponse where F: Fn(SessionState, U, T, ReqState) -> Fut, Fut: Future<Output = CustomResult<api::ApplicationResponse<Q>, E2>>, E2: ErrorSwitch<E> + std::error::Error + Send + Sync + 'static, Q: Serialize + std::fmt::Debug + 'a + ApiEventMetric, S: TryFrom<Q> + Serialize, E: Serialize + error_stack::Context + actix_web::ResponseError + Clone, error_stack::Report<E>: services::EmbedError, errors::ApiErrorResponse: ErrorSwitch<E>, T: std::fmt::Debug + Serialize + ApiEventMetric, { let request_method = request.method().as_str(); let url_path = request.path(); tracing::Span::current().record("request_method", request_method); tracing::Span::current().record("request_url_path", url_path); let start_instant = Instant::now(); logger::info!(tag = ?Tag::BeginRequest, payload = ?payload); let server_wrap_util_res = metrics::request::record_request_time_metric( api::server_wrap_util( &flow, state.clone().into(), request.headers(), request, payload, func, api_authentication, lock_action, ), &flow, ) .await .map(|response| { logger::info!(api_response =? response); response }); let res = match server_wrap_util_res { Ok(api::ApplicationResponse::Json(response)) => { let response = S::try_from(response); match response { Ok(response) => match serde_json::to_string(&response) { Ok(res) => api::http_response_json(res), Err(_) => api::http_response_err( r#"{ "error": { "message": "Error serializing response from connector" } }"#, ), }, Err(_) => api::http_response_err( r#"{ "error": { "message": "Error converting juspay response to stripe response" } }"#, ), } } Ok(api::ApplicationResponse::JsonWithHeaders((response, headers))) => { let response = S::try_from(response); match response { Ok(response) => match serde_json::to_string(&response) { Ok(res) => api::http_response_json_with_headers(res, headers, None), Err(_) => api::http_response_err( r#"{ "error": { "message": "Error serializing response from connector" } }"#, ), }, Err(_) => api::http_response_err( r#"{ "error": { "message": "Error converting juspay response to stripe response" } }"#, ), } } Ok(api::ApplicationResponse::StatusOk) => api::http_response_ok(), Ok(api::ApplicationResponse::TextPlain(text)) => api::http_response_plaintext(text), Ok(api::ApplicationResponse::FileData((file_data, content_type))) => { api::http_response_file_data(file_data, content_type) } Ok(api::ApplicationResponse::JsonForRedirection(response)) => { match serde_json::to_string(&response) { Ok(res) => api::http_redirect_response(res, response), Err(_) => api::http_response_err( r#"{ "error": { "message": "Error serializing response from connector" } }"#, ), } } Ok(api::ApplicationResponse::Form(redirection_data)) => { let config = state.conf(); api::build_redirection_form( &redirection_data.redirect_form, redirection_data.payment_method_data, redirection_data.amount, redirection_data.currency, config, ) .respond_to(request) .map_into_boxed_body() } Ok(api::ApplicationResponse::GenericLinkForm(boxed_generic_link_data)) => { let link_type = (boxed_generic_link_data).data.to_string(); match services::generic_link_response::build_generic_link_html( boxed_generic_link_data.data, boxed_generic_link_data.locale, ) { Ok(rendered_html) => api::http_response_html_data(rendered_html, None), Err(_) => { api::http_response_err(format!("Error while rendering {} HTML page", link_type)) } } } Ok(api::ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => { match *boxed_payment_link_data { api::PaymentLinkAction::PaymentLinkFormData(payment_link_data) => { match api::build_payment_link_html(payment_link_data) { Ok(rendered_html) => api::http_response_html_data(rendered_html, None), Err(_) => api::http_response_err( r#"{ "error": { "message": "Error while rendering payment link html page" } }"#, ), } } api::PaymentLinkAction::PaymentLinkStatus(payment_link_data) => { match api::get_payment_link_status(payment_link_data) { Ok(rendered_html) => api::http_response_html_data(rendered_html, None), Err(_) => api::http_response_err( r#"{ "error": { "message": "Error while rendering payment link status page" } }"#, ), } } } } Err(error) => api::log_and_return_error_response(error), }; let response_code = res.status().as_u16(); let end_instant = Instant::now(); let request_duration = end_instant.saturating_duration_since(start_instant); logger::info!( tag = ?Tag::EndRequest, status_code = response_code, time_taken_ms = request_duration.as_millis(), ); res }
1,481
1,430
hyperswitch
crates/router/src/compatibility/stripe/webhooks.rs
.rs
#[cfg(feature = "payouts")] use api_models::payouts as payout_models; use api_models::{ enums::{Currency, DisputeStatus, MandateStatus}, webhooks::{self as api}, }; #[cfg(feature = "payouts")] use common_utils::pii::{self, Email}; use common_utils::{crypto::SignMessage, date_time, ext_traits::Encode}; use error_stack::ResultExt; use router_env::logger; use serde::Serialize; use super::{ payment_intents::types::StripePaymentIntentResponse, refunds::types::StripeRefundResponse, }; use crate::{ core::{ errors, webhooks::types::{OutgoingWebhookPayloadWithSignature, OutgoingWebhookType}, }, headers, services::request::Maskable, }; #[derive(Serialize, Debug)] pub struct StripeOutgoingWebhook { id: String, #[serde(rename = "type")] stype: &'static str, object: &'static str, data: StripeWebhookObject, created: u64, // api_version: "2019-11-05", // not used } impl OutgoingWebhookType for StripeOutgoingWebhook { fn get_outgoing_webhooks_signature( &self, payment_response_hash_key: Option<impl AsRef<[u8]>>, ) -> errors::CustomResult<OutgoingWebhookPayloadWithSignature, errors::WebhooksFlowError> { let timestamp = self.created; let payment_response_hash_key = payment_response_hash_key .ok_or(errors::WebhooksFlowError::MerchantConfigNotFound) .attach_printable("For stripe compatibility payment_response_hash_key is mandatory")?; let webhook_signature_payload = self .encode_to_string_of_json() .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed) .attach_printable("failed encoding outgoing webhook payload")?; let new_signature_payload = format!("{timestamp}.{webhook_signature_payload}"); let v1 = hex::encode( common_utils::crypto::HmacSha256::sign_message( &common_utils::crypto::HmacSha256, payment_response_hash_key.as_ref(), new_signature_payload.as_bytes(), ) .change_context(errors::WebhooksFlowError::OutgoingWebhookSigningFailed) .attach_printable("Failed to sign the message")?, ); let t = timestamp; let signature = Some(format!("t={t},v1={v1}")); Ok(OutgoingWebhookPayloadWithSignature { payload: webhook_signature_payload.into(), signature, }) } fn add_webhook_header(header: &mut Vec<(String, Maskable<String>)>, signature: String) { header.push(( headers::STRIPE_COMPATIBLE_WEBHOOK_SIGNATURE.to_string(), signature.into(), )) } } #[derive(Serialize, Debug)] #[serde(tag = "type", content = "object", rename_all = "snake_case")] pub enum StripeWebhookObject { PaymentIntent(Box<StripePaymentIntentResponse>), Refund(StripeRefundResponse), Dispute(StripeDisputeResponse), Mandate(StripeMandateResponse), #[cfg(feature = "payouts")] Payout(StripePayoutResponse), } #[derive(Serialize, Debug)] pub struct StripeDisputeResponse { pub id: String, pub amount: String, pub currency: Currency, pub payment_intent: common_utils::id_type::PaymentId, pub reason: Option<String>, pub status: StripeDisputeStatus, } #[derive(Serialize, Debug)] pub struct StripeMandateResponse { pub mandate_id: String, pub status: StripeMandateStatus, pub payment_method_id: String, pub payment_method: String, } #[cfg(feature = "payouts")] #[derive(Clone, Serialize, Debug)] pub struct StripePayoutResponse { pub id: String, pub amount: i64, pub currency: String, pub payout_type: Option<common_enums::PayoutType>, pub status: StripePayoutStatus, pub name: Option<masking::Secret<String>>, pub email: Option<Email>, pub phone: Option<masking::Secret<String>>, pub phone_country_code: Option<String>, pub created: Option<i64>, pub metadata: Option<pii::SecretSerdeValue>, pub entity_type: common_enums::PayoutEntityType, pub recurring: bool, pub error_message: Option<String>, pub error_code: Option<String>, } #[cfg(feature = "payouts")] #[derive(Clone, Serialize, Debug)] #[serde(rename_all = "snake_case")] pub enum StripePayoutStatus { PayoutSuccess, PayoutFailure, PayoutProcessing, PayoutCancelled, PayoutInitiated, PayoutExpired, PayoutReversed, } #[cfg(feature = "payouts")] impl From<common_enums::PayoutStatus> for StripePayoutStatus { fn from(status: common_enums::PayoutStatus) -> Self { match status { common_enums::PayoutStatus::Success => Self::PayoutSuccess, common_enums::PayoutStatus::Failed => Self::PayoutFailure, common_enums::PayoutStatus::Cancelled => Self::PayoutCancelled, common_enums::PayoutStatus::Initiated => Self::PayoutInitiated, common_enums::PayoutStatus::Expired => Self::PayoutExpired, common_enums::PayoutStatus::Reversed => Self::PayoutReversed, common_enums::PayoutStatus::Pending | common_enums::PayoutStatus::Ineligible | common_enums::PayoutStatus::RequiresCreation | common_enums::PayoutStatus::RequiresFulfillment | common_enums::PayoutStatus::RequiresPayoutMethodData | common_enums::PayoutStatus::RequiresVendorAccountCreation | common_enums::PayoutStatus::RequiresConfirmation => Self::PayoutProcessing, } } } #[cfg(feature = "payouts")] impl From<payout_models::PayoutCreateResponse> for StripePayoutResponse { fn from(res: payout_models::PayoutCreateResponse) -> Self { let (name, email, phone, phone_country_code) = match res.customer { Some(customer) => ( customer.name, customer.email, customer.phone, customer.phone_country_code, ), None => (None, None, None, None), }; Self { id: res.payout_id, amount: res.amount.get_amount_as_i64(), currency: res.currency.to_string(), payout_type: res.payout_type, status: StripePayoutStatus::from(res.status), name, email, phone, phone_country_code, created: res.created.map(|t| t.assume_utc().unix_timestamp()), metadata: res.metadata, entity_type: res.entity_type, recurring: res.recurring, error_message: res.error_message, error_code: res.error_code, } } } #[derive(Serialize, Debug)] #[serde(rename_all = "snake_case")] pub enum StripeMandateStatus { Active, Inactive, Pending, } #[derive(Serialize, Debug)] #[serde(rename_all = "snake_case")] pub enum StripeDisputeStatus { WarningNeedsResponse, WarningUnderReview, WarningClosed, NeedsResponse, UnderReview, ChargeRefunded, Won, Lost, } impl From<api_models::disputes::DisputeResponse> for StripeDisputeResponse { fn from(res: api_models::disputes::DisputeResponse) -> Self { Self { id: res.dispute_id, amount: res.amount, currency: res.currency, payment_intent: res.payment_id, reason: res.connector_reason, status: StripeDisputeStatus::from(res.dispute_status), } } } impl From<api_models::mandates::MandateResponse> for StripeMandateResponse { fn from(res: api_models::mandates::MandateResponse) -> Self { Self { mandate_id: res.mandate_id, payment_method: res.payment_method, payment_method_id: res.payment_method_id, status: StripeMandateStatus::from(res.status), } } } impl From<MandateStatus> for StripeMandateStatus { fn from(status: MandateStatus) -> Self { match status { MandateStatus::Active => Self::Active, MandateStatus::Inactive | MandateStatus::Revoked => Self::Inactive, MandateStatus::Pending => Self::Pending, } } } impl From<DisputeStatus> for StripeDisputeStatus { fn from(status: DisputeStatus) -> Self { match status { DisputeStatus::DisputeOpened => Self::WarningNeedsResponse, DisputeStatus::DisputeExpired => Self::Lost, DisputeStatus::DisputeAccepted => Self::Lost, DisputeStatus::DisputeCancelled => Self::WarningClosed, DisputeStatus::DisputeChallenged => Self::WarningUnderReview, DisputeStatus::DisputeWon => Self::Won, DisputeStatus::DisputeLost => Self::Lost, } } } fn get_stripe_event_type(event_type: api_models::enums::EventType) -> &'static str { match event_type { api_models::enums::EventType::PaymentSucceeded => "payment_intent.succeeded", api_models::enums::EventType::PaymentFailed => "payment_intent.payment_failed", api_models::enums::EventType::PaymentProcessing => "payment_intent.processing", api_models::enums::EventType::PaymentCancelled => "payment_intent.canceled", // the below are not really stripe compatible because stripe doesn't provide this api_models::enums::EventType::ActionRequired => "action.required", api_models::enums::EventType::RefundSucceeded => "refund.succeeded", api_models::enums::EventType::RefundFailed => "refund.failed", api_models::enums::EventType::DisputeOpened => "dispute.failed", api_models::enums::EventType::DisputeExpired => "dispute.expired", api_models::enums::EventType::DisputeAccepted => "dispute.accepted", api_models::enums::EventType::DisputeCancelled => "dispute.cancelled", api_models::enums::EventType::DisputeChallenged => "dispute.challenged", api_models::enums::EventType::DisputeWon => "dispute.won", api_models::enums::EventType::DisputeLost => "dispute.lost", api_models::enums::EventType::MandateActive => "mandate.active", api_models::enums::EventType::MandateRevoked => "mandate.revoked", // as per this doc https://stripe.com/docs/api/events/types#event_types-payment_intent.amount_capturable_updated api_models::enums::EventType::PaymentAuthorized => { "payment_intent.amount_capturable_updated" } // stripe treats partially captured payments as succeeded. api_models::enums::EventType::PaymentCaptured => "payment_intent.succeeded", api_models::enums::EventType::PayoutSuccess => "payout.paid", api_models::enums::EventType::PayoutFailed => "payout.failed", api_models::enums::EventType::PayoutInitiated => "payout.created", api_models::enums::EventType::PayoutCancelled => "payout.canceled", api_models::enums::EventType::PayoutProcessing => "payout.created", api_models::enums::EventType::PayoutExpired => "payout.failed", api_models::enums::EventType::PayoutReversed => "payout.reconciliation_completed", } } impl From<api::OutgoingWebhook> for StripeOutgoingWebhook { fn from(value: api::OutgoingWebhook) -> Self { Self { id: value.event_id, stype: get_stripe_event_type(value.event_type), data: StripeWebhookObject::from(value.content), object: "event", // put this conversion it into a function created: u64::try_from(value.timestamp.assume_utc().unix_timestamp()).unwrap_or_else( |error| { logger::error!( %error, "incorrect value for `webhook.timestamp` provided {}", value.timestamp ); // Current timestamp converted to Unix timestamp should have a positive value // for many years to come u64::try_from(date_time::now().assume_utc().unix_timestamp()) .unwrap_or_default() }, ), } } } impl From<api::OutgoingWebhookContent> for StripeWebhookObject { fn from(value: api::OutgoingWebhookContent) -> Self { match value { api::OutgoingWebhookContent::PaymentDetails(payment) => { Self::PaymentIntent(Box::new((*payment).into())) } api::OutgoingWebhookContent::RefundDetails(refund) => Self::Refund((*refund).into()), api::OutgoingWebhookContent::DisputeDetails(dispute) => { Self::Dispute((*dispute).into()) } api::OutgoingWebhookContent::MandateDetails(mandate) => { Self::Mandate((*mandate).into()) } #[cfg(feature = "payouts")] api::OutgoingWebhookContent::PayoutDetails(payout) => Self::Payout((*payout).into()), } } }
2,944
1,431
hyperswitch
crates/router/src/compatibility/stripe/payment_intents.rs
.rs
pub mod types; use actix_web::{web, HttpRequest, HttpResponse}; use api_models::payments as payment_types; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use error_stack::report; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use router_env::Tag; use router_env::{instrument, tracing, Flow}; use crate::{ compatibility::{stripe::errors, wrap}, core::payments, routes::{self}, services::{api, authentication as auth}, }; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::{ core::api_locking::GetLockingInput, logger, routes::payments::get_or_generate_payment_id, types::api as api_types, }; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate, payment_id))] pub async fn payment_intents_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let payload: types::StripePaymentIntentRequest = match qs_config .deserialize_bytes(&form_payload) .map_err(|err| report!(errors::StripeErrorCode::from(err))) { Ok(p) => p, Err(err) => return api::log_and_return_error_response(err), }; tracing::Span::current().record( "payment_id", payload .id .as_ref() .map(|payment_id| payment_id.get_string_repr()) .unwrap_or_default(), ); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload); let mut create_payment_req: payment_types::PaymentsRequest = match payload.try_into() { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; if let Err(err) = get_or_generate_payment_id(&mut create_payment_req) { return api::log_and_return_error_response(err); } let flow = Flow::PaymentsCreate; let locking_action = create_payment_req.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, create_payment_req, |state, auth: auth::AuthenticationData, req, req_state| { let eligible_connectors = req.connector.clone(); payments::payments_core::< api_types::Authorize, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Authorize>, >( state, req_state, auth.merchant_account, None, auth.key_store, payments::PaymentCreate, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, eligible_connectors, hyperswitch_domain_models::payments::HeaderPayload::default(), auth.platform_merchant_account, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), locking_action, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))] pub async fn payment_intents_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::PaymentId>, query_payload: web::Query<types::StripePaymentRetrieveBody>, ) -> HttpResponse { let payload = payment_types::PaymentsRetrieveRequest { resource_id: api_types::PaymentIdType::PaymentIntentId(path.into_inner()), merchant_id: None, force_sync: true, connector: None, param: None, merchant_connector_details: None, client_secret: query_payload.client_secret.clone(), expand_attempts: None, expand_captures: None, }; let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = Flow::PaymentsRetrieveForceSync; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, payload, req_state| { payments::payments_core::< api_types::PSync, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::PSync>, >( state, req_state, auth.merchant_account, None, auth.key_store, payments::PaymentStatus, payload, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), auth.platform_merchant_account, ) }, &*auth_type, locking_action, )) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow))] pub async fn payment_intents_retrieve_with_gateway_creds( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let json_payload: payment_types::PaymentRetrieveBodyWithCredentials = match qs_config .deserialize_bytes(&form_payload) .map_err(|err| report!(errors::StripeErrorCode::from(err))) { Ok(p) => p, Err(err) => return api::log_and_return_error_response(err), }; let payload = payment_types::PaymentsRetrieveRequest { resource_id: payment_types::PaymentIdType::PaymentIntentId(json_payload.payment_id), merchant_id: json_payload.merchant_id.clone(), force_sync: json_payload.force_sync.unwrap_or(false), merchant_connector_details: json_payload.merchant_connector_details.clone(), ..Default::default() }; let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers()) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = match json_payload.force_sync { Some(true) => Flow::PaymentsRetrieveForceSync, _ => Flow::PaymentsRetrieve, }; tracing::Span::current().record("flow", flow.to_string()); let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { payments::payments_core::< api_types::PSync, payment_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::PSync>, >( state, req_state, auth.merchant_account, None, auth.key_store, payments::PaymentStatus, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), auth.platform_merchant_account, ) }, &*auth_type, locking_action, )) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate))] pub async fn payment_intents_update( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let payment_id = path.into_inner(); let stripe_payload: types::StripePaymentIntentRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let mut payload: payment_types::PaymentsRequest = match stripe_payload.try_into() { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id)); let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers()) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = Flow::PaymentsUpdate; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let eligible_connectors = req.connector.clone(); payments::payments_core::< api_types::Authorize, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Authorize>, >( state, req_state, auth.merchant_account, None, auth.key_store, payments::PaymentUpdate, req, auth_flow, payments::CallConnectorAction::Trigger, eligible_connectors, hyperswitch_domain_models::payments::HeaderPayload::default(), auth.platform_merchant_account, ) }, &*auth_type, locking_action, )) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm, payment_id))] pub async fn payment_intents_confirm( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let payment_id = path.into_inner(); let stripe_payload: types::StripePaymentIntentRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; tracing::Span::current().record( "payment_id", stripe_payload.id.as_ref().map(|id| id.get_string_repr()), ); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload); let mut payload: payment_types::PaymentsRequest = match stripe_payload.try_into() { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id)); payload.confirm = Some(true); let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; let flow = Flow::PaymentsConfirm; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { let eligible_connectors = req.connector.clone(); payments::payments_core::< api_types::Authorize, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Authorize>, >( state, req_state, auth.merchant_account, None, auth.key_store, payments::PaymentConfirm, req, auth_flow, payments::CallConnectorAction::Trigger, eligible_connectors, hyperswitch_domain_models::payments::HeaderPayload::default(), auth.platform_merchant_account, ) }, &*auth_type, locking_action, )) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCapture, payment_id))] pub async fn payment_intents_capture( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let stripe_payload: payment_types::PaymentsCaptureRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; tracing::Span::current().record("payment_id", stripe_payload.payment_id.get_string_repr()); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload); let payload = payment_types::PaymentsCaptureRequest { payment_id: path.into_inner(), ..stripe_payload }; let flow = Flow::PaymentsCapture; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth: auth::AuthenticationData, payload, req_state| { payments::payments_core::< api_types::Capture, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Capture>, >( state, req_state, auth.merchant_account, None, auth.key_store, payments::PaymentCapture, payload, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), auth.platform_merchant_account, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), locking_action, )) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCancel, payment_id))] pub async fn payment_intents_cancel( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let payment_id = path.into_inner(); let stripe_payload: types::StripePaymentCancelRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; tracing::Span::current().record("payment_id", payment_id.get_string_repr()); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload); let mut payload: payment_types::PaymentsCancelRequest = stripe_payload.into(); payload.payment_id = payment_id; let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers()) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = Flow::PaymentsCancel; let locking_action = payload.get_locking_input(flow.clone()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { payments::payments_core::< api_types::Void, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::Void>, >( state, req_state, auth.merchant_account, None, auth.key_store, payments::PaymentCancel, req, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), auth.platform_merchant_account, ) }, &*auth_type, locking_action, )) .await } #[instrument(skip_all, fields(flow = ?Flow::PaymentsList))] #[cfg(feature = "olap")] pub async fn payment_intent_list( state: web::Data<routes::AppState>, req: HttpRequest, payload: web::Query<types::StripePaymentListConstraints>, ) -> HttpResponse { let payload = match payment_types::PaymentListConstraints::try_from(payload.into_inner()) { Ok(p) => p, Err(err) => return api::log_and_return_error_response(err), }; use crate::core::api_locking; let flow = Flow::PaymentsList; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripePaymentIntentListResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth: auth::AuthenticationData, req, _| { payments::list_payments(state, auth.merchant_account, None, auth.key_store, req) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) .await }
4,104
1,432
hyperswitch
crates/router/src/compatibility/stripe/customers.rs
.rs
pub mod types; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use actix_web::{web, HttpRequest, HttpResponse}; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use common_utils::id_type; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use error_stack::report; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use router_env::{instrument, tracing, Flow}; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::{ compatibility::{stripe::errors, wrap}, core::{api_locking, customers, payment_methods::cards}, routes, services::{api, authentication as auth}, types::api::{customers as customer_types, payment_methods}, }; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "customer_v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))] pub async fn customer_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let payload: types::CreateCustomerRequest = match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let create_cust_req: customer_types::CustomerRequest = payload.into(); let flow = Flow::CustomersCreate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::CreateCustomerResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, create_cust_req, |state, auth: auth::AuthenticationData, req, _| { customers::create_customer(state, auth.merchant_account, auth.key_store, req) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "customer_v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))] pub async fn customer_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<id_type::CustomerId>, ) -> HttpResponse { let customer_id = path.into_inner(); let flow = Flow::CustomersRetrieve; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::CustomerRetrieveResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, customer_id, |state, auth: auth::AuthenticationData, customer_id, _| { customers::retrieve_customer( state, auth.merchant_account, None, auth.key_store, customer_id, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "customer_v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))] pub async fn customer_update( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, path: web::Path<id_type::CustomerId>, form_payload: web::Bytes, ) -> HttpResponse { let payload: types::CustomerUpdateRequest = match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let customer_id = path.into_inner().clone(); let request = customer_types::CustomerUpdateRequest::from(payload); let request_internal = customer_types::CustomerUpdateRequestInternal { customer_id, request, }; let flow = Flow::CustomersUpdate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::CustomerUpdateResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, request_internal, |state, auth: auth::AuthenticationData, request_internal, _| { customers::update_customer( state, auth.merchant_account, request_internal, auth.key_store, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "customer_v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))] pub async fn customer_delete( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<id_type::CustomerId>, ) -> HttpResponse { let customer_id = path.into_inner(); let flow = Flow::CustomersDelete; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::CustomerDeleteResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, customer_id, |state, auth: auth::AuthenticationData, customer_id, _| { customers::delete_customer(state, auth.merchant_account, customer_id, auth.key_store) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "customer_v2"), not(feature = "payment_methods_v2") ))] #[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))] pub async fn list_customer_payment_method_api( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<id_type::CustomerId>, json_payload: web::Query<payment_methods::PaymentMethodListRequest>, ) -> HttpResponse { let payload = json_payload.into_inner(); let customer_id = path.into_inner(); let flow = Flow::CustomerPaymentMethodsList; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::CustomerPaymentMethodListResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth: auth::AuthenticationData, req, _| { cards::do_list_customer_pm_fetch_customer_if_not_passed( state, auth.merchant_account, auth.key_store, Some(req), Some(&customer_id), None, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) .await }
1,663
1,433
hyperswitch
crates/router/src/compatibility/stripe/setup_intents.rs
.rs
pub mod types; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use actix_web::{web, HttpRequest, HttpResponse}; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use api_models::payments as payment_types; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use error_stack::report; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use router_env::{instrument, tracing, Flow}; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::{ compatibility::{ stripe::{errors, payment_intents::types as stripe_payment_types}, wrap, }, core::{api_locking, payments}, routes, services::{api, authentication as auth}, types::api as api_types, }; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate))] pub async fn setup_intents_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let payload: types::StripeSetupIntentRequest = match qs_config.deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let create_payment_req: payment_types::PaymentsRequest = match payment_types::PaymentsRequest::try_from(payload) { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; let flow = Flow::PaymentsCreate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, create_payment_req, |state, auth: auth::AuthenticationData, req, req_state| { payments::payments_core::< api_types::SetupMandate, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::SetupMandate>, >( state, req_state, auth.merchant_account, None, auth.key_store, payments::PaymentCreate, req, api::AuthFlow::Merchant, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), auth.platform_merchant_account, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) .await } #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))] pub async fn setup_intents_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::PaymentId>, query_payload: web::Query<stripe_payment_types::StripePaymentRetrieveBody>, ) -> HttpResponse { let payload = payment_types::PaymentsRetrieveRequest { resource_id: api_types::PaymentIdType::PaymentIntentId(path.into_inner()), merchant_id: None, force_sync: true, connector: None, param: None, merchant_connector_details: None, client_secret: query_payload.client_secret.clone(), expand_attempts: None, expand_captures: None, }; let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(report!(err)), }; let flow = Flow::PaymentsRetrieveForceSync; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, payload, req_state| { payments::payments_core::< api_types::PSync, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::PSync>, >( state, req_state, auth.merchant_account, None, auth.key_store, payments::PaymentStatus, payload, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), auth.platform_merchant_account, ) }, &*auth_type, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate))] pub async fn setup_intents_update( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let setup_id = path.into_inner(); let stripe_payload: types::StripeSetupIntentRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let mut payload: payment_types::PaymentsRequest = match payment_types::PaymentsRequest::try_from(stripe_payload) { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; let flow = Flow::PaymentsUpdate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { payments::payments_core::< api_types::SetupMandate, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::SetupMandate>, >( state, req_state, auth.merchant_account, None, auth.key_store, payments::PaymentUpdate, req, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), auth.platform_merchant_account, ) }, &*auth_type, api_locking::LockAction::NotApplicable, )) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm))] pub async fn setup_intents_confirm( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, path: web::Path<common_utils::id_type::PaymentId>, ) -> HttpResponse { let setup_id = path.into_inner(); let stripe_payload: types::StripeSetupIntentRequest = match qs_config .deserialize_bytes(&form_payload) { Ok(p) => p, Err(err) => { return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err))) } }; let mut payload: payment_types::PaymentsRequest = match payment_types::PaymentsRequest::try_from(stripe_payload) { Ok(req) => req, Err(err) => return api::log_and_return_error_response(err), }; payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id)); payload.confirm = Some(true); let (auth_type, auth_flow) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { Ok(auth) => auth, Err(err) => return api::log_and_return_error_response(err), }; let flow = Flow::PaymentsConfirm; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeSetupIntentResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, payload, |state, auth, req, req_state| { payments::payments_core::< api_types::SetupMandate, api_types::PaymentsResponse, _, _, _, payments::PaymentData<api_types::SetupMandate>, >( state, req_state, auth.merchant_account, None, auth.key_store, payments::PaymentConfirm, req, auth_flow, payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), auth.platform_merchant_account, ) }, &*auth_type, api_locking::LockAction::NotApplicable, )) .await }
2,164
1,434
hyperswitch
crates/router/src/compatibility/stripe/refunds.rs
.rs
pub mod types; use actix_web::{web, HttpRequest, HttpResponse}; use error_stack::report; use router_env::{instrument, tracing, Flow, Tag}; use crate::{ compatibility::{stripe::errors, wrap}, core::{api_locking, refunds}, logger, routes, services::{api, authentication as auth}, types::api::refunds as refund_types, }; #[instrument(skip_all, fields(flow = ?Flow::RefundsCreate, payment_id))] pub async fn refund_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let payload: types::StripeCreateRefundRequest = match qs_config .deserialize_bytes(&form_payload) .map_err(|err| report!(errors::StripeErrorCode::from(err))) { Ok(p) => p, Err(err) => return api::log_and_return_error_response(err), }; tracing::Span::current().record("payment_id", payload.payment_intent.get_string_repr()); logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload); let create_refund_req: refund_types::RefundRequest = payload.into(); let flow = Flow::RefundsCreate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeRefundResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, create_refund_req, |state, auth: auth::AuthenticationData, req, _| { refunds::refund_create_core(state, auth.merchant_account, None, auth.key_store, req) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow))] pub async fn refund_retrieve_with_gateway_creds( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { let refund_request: refund_types::RefundsRetrieveRequest = match qs_config .deserialize_bytes(&form_payload) .map_err(|err| report!(errors::StripeErrorCode::from(err))) { Ok(payload) => payload, Err(err) => return api::log_and_return_error_response(err), }; let flow = match refund_request.force_sync { Some(true) => Flow::RefundsRetrieveForceSync, _ => Flow::RefundsRetrieve, }; tracing::Span::current().record("flow", flow.to_string()); Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeRefundResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, refund_request, |state, auth: auth::AuthenticationData, refund_request, _| { refunds::refund_response_wrapper( state, auth.merchant_account, None, auth.key_store, refund_request, refunds::refund_retrieve_core_with_refund_id, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieveForceSync))] pub async fn refund_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { let refund_request = refund_types::RefundsRetrieveRequest { refund_id: path.into_inner(), force_sync: Some(true), merchant_connector_details: None, }; let flow = Flow::RefundsRetrieveForceSync; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeRefundResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, refund_request, |state, auth: auth::AuthenticationData, refund_request, _| { refunds::refund_response_wrapper( state, auth.merchant_account, None, auth.key_store, refund_request, refunds::refund_retrieve_core_with_refund_id, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) .await } #[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))] pub async fn refund_update( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<String>, form_payload: web::Form<types::StripeUpdateRefundRequest>, ) -> HttpResponse { let mut payload = form_payload.into_inner(); payload.refund_id = path.into_inner(); let create_refund_update_req: refund_types::RefundUpdateRequest = payload.into(); let flow = Flow::RefundsUpdate; Box::pin(wrap::compatibility_api_wrap::< _, _, _, _, _, types::StripeRefundResponse, errors::StripeErrorCode, _, >( flow, state.into_inner(), &req, create_refund_update_req, |state, auth: auth::AuthenticationData, req, _| { refunds::refund_update_core(state, auth.merchant_account, req) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, )) .await }
1,240
1,435
hyperswitch
crates/router/src/compatibility/stripe/errors.rs
.rs
use common_utils::errors::ErrorSwitch; use hyperswitch_domain_models::errors::api_error_response as errors; use crate::core::errors::CustomersErrorResponse; #[derive(Debug, router_derive::ApiError, Clone)] #[error(error_type_enum = StripeErrorType)] pub enum StripeErrorCode { /* "error": { "message": "Invalid API Key provided: sk_jkjgs****nlgs", "type": "invalid_request_error" } */ #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_01", message = "Invalid API Key provided" )] Unauthorized, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL.")] InvalidRequestUrl, #[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Missing required param: {field_name}.")] ParameterMissing { field_name: String, param: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "parameter_unknown", message = "{field_name} contains invalid data. Expected format is {expected_format}." )] ParameterUnknown { field_name: String, expected_format: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_06", message = "The refund amount exceeds the amount captured.")] RefundAmountExceedsPaymentAmount { param: String }, #[error(error_type = StripeErrorType::ApiError, code = "payment_intent_authentication_failure", message = "Payment failed while processing with connector. Retry payment.")] PaymentIntentAuthenticationFailure { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::ApiError, code = "payment_intent_payment_attempt_failed", message = "Capture attempt failed while processing with connector.")] PaymentIntentPaymentAttemptFailed { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::ApiError, code = "dispute_failure", message = "Dispute failed while processing with connector. Retry operation.")] DisputeFailed { data: Option<serde_json::Value> }, #[error(error_type = StripeErrorType::CardError, code = "expired_card", message = "Card Expired. Please use another card")] ExpiredCard, #[error(error_type = StripeErrorType::CardError, code = "invalid_card_type", message = "Card data is invalid")] InvalidCardType, #[error( error_type = StripeErrorType::ConnectorError, code = "invalid_wallet_token", message = "Invalid {wallet_name} wallet token" )] InvalidWalletToken { wallet_name: String }, #[error(error_type = StripeErrorType::ApiError, code = "refund_failed", message = "refund has failed")] RefundFailed, // stripe error code #[error(error_type = StripeErrorType::ApiError, code = "payout_failed", message = "payout has failed")] PayoutFailed, #[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")] InternalServerError, #[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")] DuplicateRefundRequest, #[error(error_type = StripeErrorType::InvalidRequestError, code = "active_mandate", message = "Customer has active mandate")] MandateActive, #[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_redacted", message = "Customer has redacted")] CustomerRedacted, #[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_already_exists", message = "Customer with the given customer_id already exists")] DuplicateCustomer, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such refund")] RefundNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "client_secret_invalid", message = "Expected client secret to be included in the request")] ClientSecretNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such customer")] CustomerNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such config")] ConfigNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "Duplicate config")] DuplicateConfig, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment")] PaymentNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment method")] PaymentMethodNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "{message}")] GenericNotFoundError { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "{message}")] GenericDuplicateError { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such merchant account")] MerchantAccountNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such resource ID")] ResourceIdNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "Merchant connector account does not exist in our records")] MerchantConnectorAccountNotFound { id: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "invalid_request", message = "The merchant connector account is disabled")] MerchantConnectorAccountDisabled, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such mandate")] MandateNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such API key")] ApiKeyNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payout")] PayoutNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such event")] EventNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "Duplicate payout request")] DuplicatePayout { payout_id: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Return url is not available")] ReturnUrlUnavailable, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate merchant account")] DuplicateMerchantAccount, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")] DuplicateMerchantConnectorAccount { profile_id: String, connector_label: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate payment method")] DuplicatePaymentMethod, #[error(error_type = StripeErrorType::InvalidRequestError, code = "" , message = "deserialization failed: {error_message}")] SerdeQsError { error_message: String, param: Option<String>, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_intent_invalid_parameter" , message = "The client_secret provided does not match the client_secret associated with the PaymentIntent.")] PaymentIntentInvalidParameter { param: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_05", message = "{message}" )] InvalidRequestData { message: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "IR_10", message = "{message}" )] PreconditionFailed { message: String }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment has not succeeded yet" )] PaymentFailed, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "The verification did not succeeded" )] VerificationFailed { data: Option<serde_json::Value> }, #[error( error_type = StripeErrorType::InvalidRequestError, code = "", message = "Reached maximum refund attempts" )] MaximumRefundCount, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID.")] DuplicateMandate, #[error(error_type= StripeErrorType::InvalidRequestError, code = "", message = "Successful payment not found for the given payment id")] SuccessfulPaymentNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Address does not exist in our records.")] AddressNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "This PaymentIntent could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}.")] PaymentIntentUnexpectedState { current_flow: String, field_name: String, current_value: String, states: String, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The mandate information is invalid. {message}")] PaymentIntentMandateInvalid { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment with the specified payment_id already exists in our records.")] DuplicatePayment { payment_id: common_utils::id_type::PaymentId, }, #[error(error_type = StripeErrorType::ConnectorError, code = "", message = "{code}: {message}")] ExternalConnectorError { code: String, message: String, connector: String, status_code: u16, }, #[error(error_type = StripeErrorType::CardError, code = "", message = "{code}: {message}")] PaymentBlockedError { code: u16, message: String, status: String, reason: String, }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "The connector provided in the request is incorrect or not available")] IncorrectConnectorNameGiven, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "No such {object}: '{id}'")] ResourceMissing { object: String, id: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File validation failed")] FileValidationFailed, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not found in the request")] MissingFile, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File puropse not found in the request")] MissingFilePurpose, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File content type not found")] MissingFileContentType, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Dispute id not found in the request")] MissingDisputeId, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File does not exists in our records")] FileNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not available")] FileNotAvailable, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Not Supported because provider is not Router")] FileProviderNotSupported, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "There was an issue with processing webhooks")] WebhookProcessingError, #[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_method_unactivated", message = "The operation cannot be performed as the payment method used has not been activated. Activate the payment method in the Dashboard, then try again.")] PaymentMethodUnactivated, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "{message}")] HyperswitchUnprocessableEntity { message: String }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "{message}")] CurrencyNotSupported { message: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Payment Link does not exist in our records")] PaymentLinkNotFound, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Resource Busy. Please try again later")] LockTimeout, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Merchant connector account is configured with invalid {config}")] InvalidConnectorConfiguration { config: String }, #[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert currency to minor unit")] CurrencyConversionFailed, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")] PaymentMethodDeleteFailed, #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Extended card info does not exist")] ExtendedCardInfoNotFound, #[error(error_type = StripeErrorType::InvalidRequestError, code = "not_configured", message = "{message}")] LinkConfigurationError { message: String }, #[error(error_type = StripeErrorType::ConnectorError, code = "CE", message = "{reason} as data mismatched for {field_names}")] IntegrityCheckFailed { reason: String, field_names: String, connector_transaction_id: Option<String>, }, #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_28", message = "Invalid tenant")] InvalidTenant, #[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert amount to {amount_type} type")] AmountConversionFailed { amount_type: &'static str }, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Bad Request")] PlatformBadRequest, #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Unauthorized Request")] PlatformUnauthorizedRequest, // [#216]: https://github.com/juspay/hyperswitch/issues/216 // Implement the remaining stripe error codes /* AccountCountryInvalidAddress, AccountErrorCountryChangeRequiresAdditionalSteps, AccountInformationMismatch, AccountInvalid, AccountNumberInvalid, AcssDebitSessionIncomplete, AlipayUpgradeRequired, AmountTooLarge, AmountTooSmall, ApiKeyExpired, AuthenticationRequired, BalanceInsufficient, BankAccountBadRoutingNumbers, BankAccountDeclined, BankAccountExists, BankAccountUnusable, BankAccountUnverified, BankAccountVerificationFailed, BillingInvalidMandate, BitcoinUpgradeRequired, CardDeclineRateLimitExceeded, CardDeclined, CardholderPhoneNumberRequired, ChargeAlreadyCaptured, ChargeAlreadyRefunded, ChargeDisputed, ChargeExceedsSourceLimit, ChargeExpiredForCapture, ChargeInvalidParameter, ClearingCodeUnsupported, CountryCodeInvalid, CountryUnsupported, CouponExpired, CustomerMaxPaymentMethods, CustomerMaxSubscriptions, DebitNotAuthorized, EmailInvalid, ExpiredCard, IdempotencyKeyInUse, IncorrectAddress, IncorrectCvc, IncorrectNumber, IncorrectZip, InstantPayoutsConfigDisabled, InstantPayoutsCurrencyDisabled, InstantPayoutsLimitExceeded, InstantPayoutsUnsupported, InsufficientFunds, IntentInvalidState, IntentVerificationMethodMissing, InvalidCardType, InvalidCharacters, InvalidChargeAmount, InvalidCvc, InvalidExpiryMonth, InvalidExpiryYear, InvalidNumber, InvalidSourceUsage, InvoiceNoCustomerLineItems, InvoiceNoPaymentMethodTypes, InvoiceNoSubscriptionLineItems, InvoiceNotEditable, InvoiceOnBehalfOfNotEditable, InvoicePaymentIntentRequiresAction, InvoiceUpcomingNone, LivemodeMismatch, LockTimeout, Missing, NoAccount, NotAllowedOnStandardAccount, OutOfInventory, ParameterInvalidEmpty, ParameterInvalidInteger, ParameterInvalidStringBlank, ParameterInvalidStringEmpty, ParametersExclusive, PaymentIntentActionRequired, PaymentIntentIncompatiblePaymentMethod, PaymentIntentInvalidParameter, PaymentIntentKonbiniRejectedConfirmationNumber, PaymentIntentPaymentAttemptExpired, PaymentIntentUnexpectedState, PaymentMethodBankAccountAlreadyVerified, PaymentMethodBankAccountBlocked, PaymentMethodBillingDetailsAddressMissing, PaymentMethodCurrencyMismatch, PaymentMethodInvalidParameter, PaymentMethodInvalidParameterTestmode, PaymentMethodMicrodepositFailed, PaymentMethodMicrodepositVerificationAmountsInvalid, PaymentMethodMicrodepositVerificationAmountsMismatch, PaymentMethodMicrodepositVerificationAttemptsExceeded, PaymentMethodMicrodepositVerificationDescriptorCodeMismatch, PaymentMethodMicrodepositVerificationTimeout, PaymentMethodProviderDecline, PaymentMethodProviderTimeout, PaymentMethodUnexpectedState, PaymentMethodUnsupportedType, PayoutsNotAllowed, PlatformAccountRequired, PlatformApiKeyExpired, PostalCodeInvalid, ProcessingError, ProductInactive, RateLimit, ReferToCustomer, RefundDisputedPayment, ResourceAlreadyExists, ResourceMissing, ReturnIntentAlreadyProcessed, RoutingNumberInvalid, SecretKeyRequired, SepaUnsupportedAccount, SetupAttemptFailed, SetupIntentAuthenticationFailure, SetupIntentInvalidParameter, SetupIntentSetupAttemptExpired, SetupIntentUnexpectedState, ShippingCalculationFailed, SkuInactive, StateUnsupported, StatusTransitionInvalid, TaxIdInvalid, TaxesCalculationFailed, TerminalLocationCountryUnsupported, TestmodeChargesOnly, TlsVersionUnsupported, TokenInUse, TransferSourceBalanceParametersMismatch, TransfersNotAllowed, */ } impl ::core::fmt::Display for StripeErrorCode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{{\"error\": {}}}", serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string()) ) } } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "snake_case")] #[allow(clippy::enum_variant_names)] pub enum StripeErrorType { ApiError, CardError, InvalidRequestError, ConnectorError, HyperswitchError, } impl From<errors::ApiErrorResponse> for StripeErrorCode { fn from(value: errors::ApiErrorResponse) -> Self { match value { errors::ApiErrorResponse::Unauthorized | errors::ApiErrorResponse::InvalidJwtToken | errors::ApiErrorResponse::GenericUnauthorized { .. } | errors::ApiErrorResponse::AccessForbidden { .. } | errors::ApiErrorResponse::InvalidCookie | errors::ApiErrorResponse::InvalidEphemeralKey | errors::ApiErrorResponse::CookieNotFound => Self::Unauthorized, errors::ApiErrorResponse::InvalidRequestUrl | errors::ApiErrorResponse::InvalidHttpMethod | errors::ApiErrorResponse::InvalidCardIin | errors::ApiErrorResponse::InvalidCardIinLength => Self::InvalidRequestUrl, errors::ApiErrorResponse::MissingRequiredField { field_name } => { Self::ParameterMissing { field_name: field_name.to_string(), param: field_name.to_string(), } } errors::ApiErrorResponse::UnprocessableEntity { message } => { Self::HyperswitchUnprocessableEntity { message } } errors::ApiErrorResponse::MissingRequiredFields { field_names } => { // Instead of creating a new error variant in StripeErrorCode for MissingRequiredFields, converted vec<&str> to String Self::ParameterMissing { field_name: field_names.clone().join(", "), param: field_names.clone().join(", "), } } errors::ApiErrorResponse::GenericNotFoundError { message } => { Self::GenericNotFoundError { message } } errors::ApiErrorResponse::GenericDuplicateError { message } => { Self::GenericDuplicateError { message } } // parameter unknown, invalid request error // actually if we type wrong values in address we get this error. Stripe throws parameter unknown. I don't know if stripe is validating email and stuff errors::ApiErrorResponse::InvalidDataFormat { field_name, expected_format, } => Self::ParameterUnknown { field_name, expected_format, }, errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount => { Self::RefundAmountExceedsPaymentAmount { param: "amount".to_owned(), } } errors::ApiErrorResponse::PaymentAuthorizationFailed { data } | errors::ApiErrorResponse::PaymentAuthenticationFailed { data } => { Self::PaymentIntentAuthenticationFailure { data } } errors::ApiErrorResponse::VerificationFailed { data } => { Self::VerificationFailed { data } } errors::ApiErrorResponse::PaymentCaptureFailed { data } => { Self::PaymentIntentPaymentAttemptFailed { data } } errors::ApiErrorResponse::DisputeFailed { data } => Self::DisputeFailed { data }, errors::ApiErrorResponse::InvalidCardData { data: _ } => Self::InvalidCardType, // Maybe it is better to de generalize this router error errors::ApiErrorResponse::CardExpired { data: _ } => Self::ExpiredCard, errors::ApiErrorResponse::RefundNotPossible { connector: _ } => Self::RefundFailed, errors::ApiErrorResponse::RefundFailed { data: _ } => Self::RefundFailed, // Nothing at stripe to map errors::ApiErrorResponse::PayoutFailed { data: _ } => Self::PayoutFailed, errors::ApiErrorResponse::MandateUpdateFailed | errors::ApiErrorResponse::MandateSerializationFailed | errors::ApiErrorResponse::MandateDeserializationFailed | errors::ApiErrorResponse::InternalServerError | errors::ApiErrorResponse::HealthCheckError { .. } => Self::InternalServerError, // not a stripe code errors::ApiErrorResponse::ExternalConnectorError { code, message, connector, status_code, .. } => Self::ExternalConnectorError { code, message, connector, status_code, }, errors::ApiErrorResponse::IncorrectConnectorNameGiven => { Self::IncorrectConnectorNameGiven } errors::ApiErrorResponse::MandateActive => Self::MandateActive, //not a stripe code errors::ApiErrorResponse::CustomerRedacted => Self::CustomerRedacted, //not a stripe code errors::ApiErrorResponse::ConfigNotFound => Self::ConfigNotFound, // not a stripe code errors::ApiErrorResponse::DuplicateConfig => Self::DuplicateConfig, // not a stripe code errors::ApiErrorResponse::DuplicateRefundRequest => Self::DuplicateRefundRequest, errors::ApiErrorResponse::DuplicatePayout { payout_id } => { Self::DuplicatePayout { payout_id } } errors::ApiErrorResponse::RefundNotFound => Self::RefundNotFound, errors::ApiErrorResponse::CustomerNotFound => Self::CustomerNotFound, errors::ApiErrorResponse::PaymentNotFound => Self::PaymentNotFound, errors::ApiErrorResponse::PaymentMethodNotFound => Self::PaymentMethodNotFound, errors::ApiErrorResponse::ClientSecretNotGiven | errors::ApiErrorResponse::ClientSecretExpired => Self::ClientSecretNotFound, errors::ApiErrorResponse::MerchantAccountNotFound => Self::MerchantAccountNotFound, errors::ApiErrorResponse::PaymentLinkNotFound => Self::PaymentLinkNotFound, errors::ApiErrorResponse::ResourceIdNotFound => Self::ResourceIdNotFound, errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id } => { Self::MerchantConnectorAccountNotFound { id } } errors::ApiErrorResponse::MandateNotFound => Self::MandateNotFound, errors::ApiErrorResponse::ApiKeyNotFound => Self::ApiKeyNotFound, errors::ApiErrorResponse::PayoutNotFound => Self::PayoutNotFound, errors::ApiErrorResponse::EventNotFound => Self::EventNotFound, errors::ApiErrorResponse::MandateValidationFailed { reason } => { Self::PaymentIntentMandateInvalid { message: reason } } errors::ApiErrorResponse::ReturnUrlUnavailable => Self::ReturnUrlUnavailable, errors::ApiErrorResponse::DuplicateMerchantAccount => Self::DuplicateMerchantAccount, errors::ApiErrorResponse::DuplicateMerchantConnectorAccount { profile_id, connector_label, } => Self::DuplicateMerchantConnectorAccount { profile_id, connector_label, }, errors::ApiErrorResponse::DuplicatePaymentMethod => Self::DuplicatePaymentMethod, errors::ApiErrorResponse::PaymentBlockedError { code, message, status, reason, } => Self::PaymentBlockedError { code, message, status, reason, }, errors::ApiErrorResponse::ClientSecretInvalid => Self::PaymentIntentInvalidParameter { param: "client_secret".to_owned(), }, errors::ApiErrorResponse::InvalidRequestData { message } => { Self::InvalidRequestData { message } } errors::ApiErrorResponse::PreconditionFailed { message } => { Self::PreconditionFailed { message } } errors::ApiErrorResponse::InvalidDataValue { field_name } => Self::ParameterMissing { field_name: field_name.to_string(), param: field_name.to_string(), }, errors::ApiErrorResponse::MaximumRefundCount => Self::MaximumRefundCount, errors::ApiErrorResponse::PaymentNotSucceeded => Self::PaymentFailed, errors::ApiErrorResponse::DuplicateMandate => Self::DuplicateMandate, errors::ApiErrorResponse::SuccessfulPaymentNotFound => Self::SuccessfulPaymentNotFound, errors::ApiErrorResponse::AddressNotFound => Self::AddressNotFound, errors::ApiErrorResponse::NotImplemented { .. } => Self::Unauthorized, errors::ApiErrorResponse::FlowNotSupported { .. } => Self::InternalServerError, errors::ApiErrorResponse::PaymentUnexpectedState { current_flow, field_name, current_value, states, } => Self::PaymentIntentUnexpectedState { current_flow, field_name, current_value, states, }, errors::ApiErrorResponse::DuplicatePayment { payment_id } => { Self::DuplicatePayment { payment_id } } errors::ApiErrorResponse::DisputeNotFound { dispute_id } => Self::ResourceMissing { object: "dispute".to_owned(), id: dispute_id, }, errors::ApiErrorResponse::AuthenticationNotFound { id } => Self::ResourceMissing { object: "authentication".to_owned(), id, }, errors::ApiErrorResponse::ProfileNotFound { id } => Self::ResourceMissing { object: "business_profile".to_owned(), id, }, errors::ApiErrorResponse::PollNotFound { id } => Self::ResourceMissing { object: "poll".to_owned(), id, }, errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: _ } => { Self::InternalServerError } errors::ApiErrorResponse::FileValidationFailed { .. } => Self::FileValidationFailed, errors::ApiErrorResponse::MissingFile => Self::MissingFile, errors::ApiErrorResponse::MissingFilePurpose => Self::MissingFilePurpose, errors::ApiErrorResponse::MissingFileContentType => Self::MissingFileContentType, errors::ApiErrorResponse::MissingDisputeId => Self::MissingDisputeId, errors::ApiErrorResponse::FileNotFound => Self::FileNotFound, errors::ApiErrorResponse::FileNotAvailable => Self::FileNotAvailable, errors::ApiErrorResponse::MerchantConnectorAccountDisabled => { Self::MerchantConnectorAccountDisabled } errors::ApiErrorResponse::NotSupported { .. } => Self::InternalServerError, errors::ApiErrorResponse::CurrencyNotSupported { message } => { Self::CurrencyNotSupported { message } } errors::ApiErrorResponse::FileProviderNotSupported { .. } => { Self::FileProviderNotSupported } errors::ApiErrorResponse::WebhookBadRequest | errors::ApiErrorResponse::WebhookResourceNotFound | errors::ApiErrorResponse::WebhookProcessingFailure | errors::ApiErrorResponse::WebhookAuthenticationFailed | errors::ApiErrorResponse::WebhookUnprocessableEntity | errors::ApiErrorResponse::WebhookInvalidMerchantSecret => { Self::WebhookProcessingError } errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration => { Self::PaymentMethodUnactivated } errors::ApiErrorResponse::ResourceBusy => Self::PaymentMethodUnactivated, errors::ApiErrorResponse::InvalidConnectorConfiguration { config } => { Self::InvalidConnectorConfiguration { config } } errors::ApiErrorResponse::CurrencyConversionFailed => Self::CurrencyConversionFailed, errors::ApiErrorResponse::PaymentMethodDeleteFailed => Self::PaymentMethodDeleteFailed, errors::ApiErrorResponse::InvalidWalletToken { wallet_name } => { Self::InvalidWalletToken { wallet_name } } errors::ApiErrorResponse::ExtendedCardInfoNotFound => Self::ExtendedCardInfoNotFound, errors::ApiErrorResponse::LinkConfigurationError { message } => { Self::LinkConfigurationError { message } } errors::ApiErrorResponse::IntegrityCheckFailed { reason, field_names, connector_transaction_id, } => Self::IntegrityCheckFailed { reason, field_names, connector_transaction_id, }, errors::ApiErrorResponse::InvalidTenant { tenant_id: _ } | errors::ApiErrorResponse::MissingTenantId => Self::InvalidTenant, errors::ApiErrorResponse::AmountConversionFailed { amount_type } => { Self::AmountConversionFailed { amount_type } } errors::ApiErrorResponse::PlatformAccountAuthNotSupported => Self::PlatformBadRequest, errors::ApiErrorResponse::InvalidPlatformOperation => Self::PlatformUnauthorizedRequest, } } } impl actix_web::ResponseError for StripeErrorCode { fn status_code(&self) -> reqwest::StatusCode { use reqwest::StatusCode; match self { Self::Unauthorized | Self::PlatformUnauthorizedRequest => StatusCode::UNAUTHORIZED, Self::InvalidRequestUrl | Self::GenericNotFoundError { .. } => StatusCode::NOT_FOUND, Self::ParameterUnknown { .. } | Self::HyperswitchUnprocessableEntity { .. } => { StatusCode::UNPROCESSABLE_ENTITY } Self::ParameterMissing { .. } | Self::RefundAmountExceedsPaymentAmount { .. } | Self::PaymentIntentAuthenticationFailure { .. } | Self::PaymentIntentPaymentAttemptFailed { .. } | Self::ExpiredCard | Self::InvalidCardType | Self::DuplicateRefundRequest | Self::DuplicatePayout { .. } | Self::RefundNotFound | Self::CustomerNotFound | Self::ConfigNotFound | Self::DuplicateConfig | Self::ClientSecretNotFound | Self::PaymentNotFound | Self::PaymentMethodNotFound | Self::MerchantAccountNotFound | Self::MerchantConnectorAccountNotFound { .. } | Self::MerchantConnectorAccountDisabled | Self::MandateNotFound | Self::ApiKeyNotFound | Self::PayoutNotFound | Self::EventNotFound | Self::DuplicateMerchantAccount | Self::DuplicateMerchantConnectorAccount { .. } | Self::DuplicatePaymentMethod | Self::PaymentFailed | Self::VerificationFailed { .. } | Self::DisputeFailed { .. } | Self::MaximumRefundCount | Self::PaymentIntentInvalidParameter { .. } | Self::SerdeQsError { .. } | Self::InvalidRequestData { .. } | Self::InvalidWalletToken { .. } | Self::PreconditionFailed { .. } | Self::DuplicateMandate | Self::SuccessfulPaymentNotFound | Self::AddressNotFound | Self::ResourceIdNotFound | Self::PaymentIntentMandateInvalid { .. } | Self::PaymentIntentUnexpectedState { .. } | Self::DuplicatePayment { .. } | Self::GenericDuplicateError { .. } | Self::IncorrectConnectorNameGiven | Self::ResourceMissing { .. } | Self::FileValidationFailed | Self::MissingFile | Self::MissingFileContentType | Self::MissingFilePurpose | Self::MissingDisputeId | Self::FileNotFound | Self::FileNotAvailable | Self::FileProviderNotSupported | Self::CurrencyNotSupported { .. } | Self::DuplicateCustomer | Self::PaymentMethodUnactivated | Self::InvalidConnectorConfiguration { .. } | Self::CurrencyConversionFailed | Self::PaymentMethodDeleteFailed | Self::ExtendedCardInfoNotFound | Self::PlatformBadRequest | Self::LinkConfigurationError { .. } => StatusCode::BAD_REQUEST, Self::RefundFailed | Self::PayoutFailed | Self::PaymentLinkNotFound | Self::InternalServerError | Self::MandateActive | Self::CustomerRedacted | Self::WebhookProcessingError | Self::InvalidTenant | Self::AmountConversionFailed { .. } => StatusCode::INTERNAL_SERVER_ERROR, Self::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE, Self::ExternalConnectorError { status_code, .. } => { StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR) } Self::IntegrityCheckFailed { .. } => StatusCode::INTERNAL_SERVER_ERROR, Self::PaymentBlockedError { code, .. } => { StatusCode::from_u16(*code).unwrap_or(StatusCode::OK) } Self::LockTimeout => StatusCode::LOCKED, } } fn error_response(&self) -> actix_web::HttpResponse { use actix_web::http::header; actix_web::HttpResponseBuilder::new(self.status_code()) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .body(self.to_string()) } } impl From<serde_qs::Error> for StripeErrorCode { fn from(item: serde_qs::Error) -> Self { match item { serde_qs::Error::Custom(s) => Self::SerdeQsError { error_message: s, param: None, }, serde_qs::Error::Parse(param, position) => Self::SerdeQsError { error_message: format!( "parsing failed with error: '{param}' at position: {position}" ), param: Some(param), }, serde_qs::Error::Unsupported => Self::SerdeQsError { error_message: "Given request format is not supported".to_owned(), param: None, }, serde_qs::Error::FromUtf8(_) => Self::SerdeQsError { error_message: "Failed to parse request to from utf-8".to_owned(), param: None, }, serde_qs::Error::Io(_) => Self::SerdeQsError { error_message: "Failed to parse request".to_owned(), param: None, }, serde_qs::Error::ParseInt(_) => Self::SerdeQsError { error_message: "Failed to parse integer in request".to_owned(), param: None, }, serde_qs::Error::Utf8(_) => Self::SerdeQsError { error_message: "Failed to convert utf8 to string".to_owned(), param: None, }, } } } impl ErrorSwitch<StripeErrorCode> for errors::ApiErrorResponse { fn switch(&self) -> StripeErrorCode { self.clone().into() } } impl crate::services::EmbedError for error_stack::Report<StripeErrorCode> {} impl ErrorSwitch<StripeErrorCode> for CustomersErrorResponse { fn switch(&self) -> StripeErrorCode { use StripeErrorCode as SC; match self { Self::CustomerRedacted => SC::CustomerRedacted, Self::InternalServerError => SC::InternalServerError, Self::MandateActive => SC::MandateActive, Self::CustomerNotFound => SC::CustomerNotFound, Self::CustomerAlreadyExists => SC::DuplicateCustomer, } } }
7,998
1,436
hyperswitch
crates/router/src/compatibility/stripe/app.rs
.rs
use actix_web::{web, Scope}; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use super::customers::*; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use super::{payment_intents::*, setup_intents::*}; use super::{refunds::*, webhooks::*}; use crate::routes::{self, mandates, webhooks}; pub struct PaymentIntents; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl PaymentIntents { pub fn server(state: routes::AppState) -> Scope { let mut route = web::scope("/payment_intents").app_data(web::Data::new(state)); #[cfg(feature = "olap")] { route = route.service(web::resource("/list").route(web::get().to(payment_intent_list))) } route = route .service(web::resource("").route(web::post().to(payment_intents_create))) .service( web::resource("/sync") .route(web::post().to(payment_intents_retrieve_with_gateway_creds)), ) .service( web::resource("/{payment_id}") .route(web::get().to(payment_intents_retrieve)) .route(web::post().to(payment_intents_update)), ) .service( web::resource("/{payment_id}/confirm") .route(web::post().to(payment_intents_confirm)), ) .service( web::resource("/{payment_id}/capture") .route(web::post().to(payment_intents_capture)), ) .service( web::resource("/{payment_id}/cancel").route(web::post().to(payment_intents_cancel)), ); route } } pub struct SetupIntents; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl SetupIntents { pub fn server(state: routes::AppState) -> Scope { web::scope("/setup_intents") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(setup_intents_create))) .service( web::resource("/{setup_id}") .route(web::get().to(setup_intents_retrieve)) .route(web::post().to(setup_intents_update)), ) .service( web::resource("/{setup_id}/confirm").route(web::post().to(setup_intents_confirm)), ) } } pub struct Refunds; impl Refunds { pub fn server(config: routes::AppState) -> Scope { web::scope("/refunds") .app_data(web::Data::new(config)) .service(web::resource("").route(web::post().to(refund_create))) .service( web::resource("/sync").route(web::post().to(refund_retrieve_with_gateway_creds)), ) .service( web::resource("/{refund_id}") .route(web::get().to(refund_retrieve)) .route(web::post().to(refund_update)), ) } } pub struct Customers; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl Customers { pub fn server(config: routes::AppState) -> Scope { web::scope("/customers") .app_data(web::Data::new(config)) .service(web::resource("").route(web::post().to(customer_create))) .service( web::resource("/{customer_id}") .route(web::get().to(customer_retrieve)) .route(web::post().to(customer_update)) .route(web::delete().to(customer_delete)), ) .service( web::resource("/{customer_id}/payment_methods") .route(web::get().to(list_customer_payment_method_api)), ) } } pub struct Webhooks; impl Webhooks { pub fn server(config: routes::AppState) -> Scope { web::scope("/webhooks") .app_data(web::Data::new(config)) .service( web::resource("/{merchant_id}/{connector_name}") .route( web::post().to(webhooks::receive_incoming_webhook::<StripeOutgoingWebhook>), ) .route( web::get().to(webhooks::receive_incoming_webhook::<StripeOutgoingWebhook>), ), ) } } pub struct Mandates; impl Mandates { pub fn server(config: routes::AppState) -> Scope { web::scope("/payment_methods") .app_data(web::Data::new(config)) .service(web::resource("/{id}/detach").route(web::post().to(mandates::revoke_mandate))) } }
1,030
1,437
hyperswitch
crates/router/src/compatibility/stripe/payment_intents/types.rs
.rs
use std::str::FromStr; use api_models::payments; use common_utils::{ crypto::Encryptable, date_time, ext_traits::StringExt, id_type, pii::{IpAddress, SecretSerdeValue, UpiVpaMaskingStrategy}, types::MinorUnit, }; use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{ compatibility::stripe::refunds::types as stripe_refunds, connector::utils::AddressData, consts, core::errors, pii::{Email, PeekInterface}, types::{ api::{admin, enums as api_enums}, transformers::{ForeignFrom, ForeignTryFrom}, }, }; #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeBillingDetails { pub address: Option<AddressDetails>, pub email: Option<Email>, pub name: Option<String>, pub phone: Option<masking::Secret<String>>, } impl From<StripeBillingDetails> for payments::Address { fn from(details: StripeBillingDetails) -> Self { Self { phone: Some(payments::PhoneDetails { number: details.phone, country_code: details.address.as_ref().and_then(|address| { address.country.as_ref().map(|country| country.to_string()) }), }), email: details.email, address: details.address.map(|address| payments::AddressDetails { city: address.city, country: address.country, line1: address.line1, line2: address.line2, zip: address.postal_code, state: address.state, first_name: None, line3: None, last_name: None, }), } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeCard { pub number: cards::CardNumber, pub exp_month: masking::Secret<String>, pub exp_year: masking::Secret<String>, pub cvc: masking::Secret<String>, pub holder_name: Option<masking::Secret<String>>, } // ApplePay wallet param is not available in stripe Docs #[derive(Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum StripeWallet { ApplePay(payments::ApplePayWalletData), } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripeUpi { pub vpa_id: masking::Secret<String, UpiVpaMaskingStrategy>, } #[derive(Debug, Default, Serialize, PartialEq, Eq, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodType { #[default] Card, Wallet, Upi, BankRedirect, RealTimePayment, } impl From<StripePaymentMethodType> for api_enums::PaymentMethod { fn from(item: StripePaymentMethodType) -> Self { match item { StripePaymentMethodType::Card => Self::Card, StripePaymentMethodType::Wallet => Self::Wallet, StripePaymentMethodType::Upi => Self::Upi, StripePaymentMethodType::BankRedirect => Self::BankRedirect, StripePaymentMethodType::RealTimePayment => Self::RealTimePayment, } } } #[derive(Default, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct StripePaymentMethodData { #[serde(rename = "type")] pub stype: StripePaymentMethodType, pub billing_details: Option<StripeBillingDetails>, #[serde(flatten)] pub payment_method_details: Option<StripePaymentMethodDetails>, // enum pub metadata: Option<SecretSerdeValue>, } #[derive(PartialEq, Eq, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodDetails { Card(StripeCard), Wallet(StripeWallet), Upi(StripeUpi), } impl From<StripeCard> for payments::Card { fn from(card: StripeCard) -> Self { Self { card_number: card.number, card_exp_month: card.exp_month, card_exp_year: card.exp_year, card_holder_name: card.holder_name, card_cvc: card.cvc, card_issuer: None, card_network: None, bank_code: None, card_issuing_country: None, card_type: None, nick_name: None, } } } impl From<StripeWallet> for payments::WalletData { fn from(wallet: StripeWallet) -> Self { match wallet { StripeWallet::ApplePay(data) => Self::ApplePay(data), } } } impl From<StripeUpi> for payments::UpiData { fn from(upi_data: StripeUpi) -> Self { Self::UpiCollect(payments::UpiCollectData { vpa_id: Some(upi_data.vpa_id), }) } } impl From<StripePaymentMethodDetails> for payments::PaymentMethodData { fn from(item: StripePaymentMethodDetails) -> Self { match item { StripePaymentMethodDetails::Card(card) => Self::Card(payments::Card::from(card)), StripePaymentMethodDetails::Wallet(wallet) => { Self::Wallet(payments::WalletData::from(wallet)) } StripePaymentMethodDetails::Upi(upi) => Self::Upi(payments::UpiData::from(upi)), } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct Shipping { pub address: AddressDetails, pub name: Option<masking::Secret<String>>, pub carrier: Option<String>, pub phone: Option<masking::Secret<String>>, pub tracking_number: Option<masking::Secret<String>>, } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct AddressDetails { pub city: Option<String>, pub country: Option<api_enums::CountryAlpha2>, pub line1: Option<masking::Secret<String>>, pub line2: Option<masking::Secret<String>>, pub postal_code: Option<masking::Secret<String>>, pub state: Option<masking::Secret<String>>, } impl From<Shipping> for payments::Address { fn from(details: Shipping) -> Self { Self { phone: Some(payments::PhoneDetails { number: details.phone, country_code: details.address.country.map(|country| country.to_string()), }), email: None, address: Some(payments::AddressDetails { city: details.address.city, country: details.address.country, line1: details.address.line1, line2: details.address.line2, zip: details.address.postal_code, state: details.address.state, first_name: details.name, line3: None, last_name: None, }), } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct MandateData { pub customer_acceptance: CustomerAcceptance, pub mandate_type: Option<StripeMandateType>, pub amount: Option<i64>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub start_date: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub end_date: Option<PrimitiveDateTime>, } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)] pub struct CustomerAcceptance { #[serde(rename = "type")] pub acceptance_type: Option<AcceptanceType>, pub accepted_at: Option<PrimitiveDateTime>, pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone)] #[serde(rename_all = "lowercase")] pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { pub ip_address: masking::Secret<String, IpAddress>, pub user_agent: String, } #[derive(Deserialize, Clone, Debug)] pub struct StripePaymentIntentRequest { pub id: Option<id_type::PaymentId>, pub amount: Option<i64>, // amount in cents, hence passed as integer pub connector: Option<Vec<api_enums::RoutableConnectors>>, pub currency: Option<String>, #[serde(rename = "amount_to_capture")] pub amount_capturable: Option<i64>, pub confirm: Option<bool>, pub capture_method: Option<api_enums::CaptureMethod>, pub customer: Option<id_type::CustomerId>, pub description: Option<String>, pub payment_method_data: Option<StripePaymentMethodData>, pub receipt_email: Option<Email>, pub return_url: Option<url::Url>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub shipping: Option<Shipping>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, pub metadata: Option<serde_json::Value>, pub client_secret: Option<masking::Secret<String>>, pub payment_method_options: Option<StripePaymentMethodOptions>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, pub mandate: Option<String>, pub off_session: Option<bool>, pub payment_method_types: Option<api_enums::PaymentMethodType>, pub receipt_ipaddress: Option<String>, pub user_agent: Option<String>, pub mandate_data: Option<MandateData>, pub automatic_payment_methods: Option<SecretSerdeValue>, // not used pub payment_method: Option<String>, // not used pub confirmation_method: Option<String>, // not used pub error_on_requires_action: Option<String>, // not used pub radar_options: Option<SecretSerdeValue>, // not used pub connector_metadata: Option<payments::ConnectorMetadata>, } impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentIntentRequest) -> errors::RouterResult<Self> { let routable_connector: Option<api_enums::RoutableConnectors> = item.connector.and_then(|v| v.into_iter().next()); let routing = routable_connector .map(|connector| { api_models::routing::RoutingAlgorithm::Single(Box::new( api_models::routing::RoutableConnectorChoice { choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, connector, merchant_connector_id: None, }, )) }) .map(|r| { serde_json::to_value(r) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("converting to routing failed") }) .transpose()?; let ip_address = item .receipt_ipaddress .map(|ip| std::net::IpAddr::from_str(ip.as_str())) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "receipt_ipaddress".to_string(), expected_format: "127.0.0.1".to_string(), })?; let amount = item.amount.map(|amount| MinorUnit::new(amount).into()); let payment_method_data = item.payment_method_data.as_ref().map(|pmd| { let billing = pmd.billing_details.clone().map(payments::Address::from); let payment_method_data = match pmd.payment_method_details.as_ref() { Some(spmd) => Some(payments::PaymentMethodData::from(spmd.to_owned())), None => get_pmd_based_on_payment_method_type( item.payment_method_types, billing.clone().map(From::from), ), }; payments::PaymentMethodDataRequest { payment_method_data, billing, } }); let request = Ok(Self { payment_id: item.id.map(payments::PaymentIdType::PaymentIntentId), amount, currency: item .currency .as_ref() .map(|c| c.to_uppercase().parse_enum("currency")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "currency", })?, capture_method: item.capture_method, amount_to_capture: item.amount_capturable.map(MinorUnit::new), confirm: item.confirm, customer_id: item.customer, email: item.receipt_email, phone: item.shipping.as_ref().and_then(|s| s.phone.clone()), description: item.description, return_url: item.return_url, payment_method_data, payment_method: item .payment_method_data .as_ref() .map(|pmd| api_enums::PaymentMethod::from(pmd.stype.to_owned())), shipping: item .shipping .as_ref() .map(|s| payments::Address::from(s.to_owned())), billing: item .payment_method_data .and_then(|pmd| pmd.billing_details.map(payments::Address::from)), statement_descriptor_name: item.statement_descriptor, statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: item.metadata, client_secret: item.client_secret.map(|s| s.peek().clone()), authentication_type: match item.payment_method_options { Some(pmo) => { let StripePaymentMethodOptions::Card { request_three_d_secure, }: StripePaymentMethodOptions = pmo; Some(api_enums::AuthenticationType::foreign_from( request_three_d_secure, )) } None => None, }, mandate_data: ForeignTryFrom::foreign_try_from(( item.mandate_data, item.currency.to_owned(), ))?, merchant_connector_details: item.merchant_connector_details, setup_future_usage: item.setup_future_usage, mandate_id: item.mandate, off_session: item.off_session, payment_method_type: item.payment_method_types, routing, browser_info: Some( serde_json::to_value(crate::types::BrowserInformation { ip_address, user_agent: item.user_agent, ..Default::default() }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("convert to browser info failed")?, ), connector_metadata: item.connector_metadata, ..Self::default() }); request } } #[derive(Clone, Default, Eq, PartialEq, Serialize, Deserialize, Debug)] #[serde(rename_all = "snake_case")] pub enum StripePaymentStatus { Succeeded, Canceled, #[default] Processing, RequiresAction, RequiresPaymentMethod, RequiresConfirmation, RequiresCapture, } impl From<api_enums::IntentStatus> for StripePaymentStatus { fn from(item: api_enums::IntentStatus) -> Self { match item { api_enums::IntentStatus::Succeeded | api_enums::IntentStatus::PartiallyCaptured => { Self::Succeeded } api_enums::IntentStatus::Failed => Self::Canceled, api_enums::IntentStatus::Processing => Self::Processing, api_enums::IntentStatus::RequiresCustomerAction | api_enums::IntentStatus::RequiresMerchantAction => Self::RequiresAction, api_enums::IntentStatus::RequiresPaymentMethod => Self::RequiresPaymentMethod, api_enums::IntentStatus::RequiresConfirmation => Self::RequiresConfirmation, api_enums::IntentStatus::RequiresCapture | api_enums::IntentStatus::PartiallyCapturedAndCapturable => Self::RequiresCapture, api_enums::IntentStatus::Cancelled => Self::Canceled, } } } #[derive(Debug, Serialize, Deserialize, Copy, Clone, strum::Display)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CancellationReason { Duplicate, Fraudulent, RequestedByCustomer, Abandoned, } #[derive(Debug, Deserialize, Serialize, Copy, Clone)] pub struct StripePaymentCancelRequest { cancellation_reason: Option<CancellationReason>, } impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest { fn from(item: StripePaymentCancelRequest) -> Self { Self { cancellation_reason: item.cancellation_reason.map(|c| c.to_string()), ..Self::default() } } } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct StripePaymentIntentResponse { pub id: id_type::PaymentId, pub object: &'static str, pub amount: i64, pub amount_received: Option<i64>, pub amount_capturable: i64, pub currency: String, pub status: StripePaymentStatus, pub client_secret: Option<masking::Secret<String>>, pub created: Option<i64>, pub customer: Option<id_type::CustomerId>, pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>, pub mandate: Option<String>, pub metadata: Option<serde_json::Value>, pub charges: Charges, pub connector: Option<String>, pub description: Option<String>, pub mandate_data: Option<payments::MandateData>, pub setup_future_usage: Option<api_models::enums::FutureUsage>, pub off_session: Option<bool>, pub authentication_type: Option<api_models::enums::AuthenticationType>, pub next_action: Option<StripeNextAction>, pub cancellation_reason: Option<String>, pub payment_method: Option<api_models::enums::PaymentMethod>, pub payment_method_data: Option<payments::PaymentMethodDataResponse>, pub shipping: Option<payments::Address>, pub billing: Option<payments::Address>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, pub payment_token: Option<String>, pub email: Option<Email>, pub phone: Option<masking::Secret<String>>, pub statement_descriptor_suffix: Option<String>, pub statement_descriptor_name: Option<String>, pub capture_method: Option<api_models::enums::CaptureMethod>, pub name: Option<masking::Secret<String>>, pub last_payment_error: Option<LastPaymentError>, pub connector_transaction_id: Option<String>, } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct LastPaymentError { charge: Option<String>, code: Option<String>, decline_code: Option<String>, message: String, param: Option<String>, payment_method: StripePaymentMethod, #[serde(rename = "type")] error_type: String, } impl From<payments::PaymentsResponse> for StripePaymentIntentResponse { fn from(resp: payments::PaymentsResponse) -> Self { Self { object: "payment_intent", id: resp.payment_id, status: StripePaymentStatus::from(resp.status), amount: resp.amount.get_amount_as_i64(), amount_capturable: resp.amount_capturable.get_amount_as_i64(), amount_received: resp.amount_received.map(|amt| amt.get_amount_as_i64()), connector: resp.connector, client_secret: resp.client_secret, created: resp.created.map(|t| t.assume_utc().unix_timestamp()), currency: resp.currency.to_lowercase(), customer: resp.customer_id, description: resp.description, refunds: resp .refunds .map(|a| a.into_iter().map(Into::into).collect()), mandate: resp.mandate_id, mandate_data: resp.mandate_data, setup_future_usage: resp.setup_future_usage, off_session: resp.off_session, capture_on: resp.capture_on, capture_method: resp.capture_method, payment_method: resp.payment_method, payment_method_data: resp .payment_method_data .and_then(|pmd| pmd.payment_method_data), payment_token: resp.payment_token, shipping: resp.shipping, billing: resp.billing, email: resp.email.map(|inner| inner.into()), name: resp.name.map(Encryptable::into_inner), phone: resp.phone.map(Encryptable::into_inner), authentication_type: resp.authentication_type, statement_descriptor_name: resp.statement_descriptor_name, statement_descriptor_suffix: resp.statement_descriptor_suffix, next_action: into_stripe_next_action(resp.next_action, resp.return_url), cancellation_reason: resp.cancellation_reason, metadata: resp.metadata, charges: Charges::new(), last_payment_error: resp.error_code.map(|code| LastPaymentError { charge: None, code: Some(code.to_owned()), decline_code: None, message: resp .error_message .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), param: None, payment_method: StripePaymentMethod { payment_method_id: "place_holder_id".to_string(), object: "payment_method", card: None, created: u64::try_from(date_time::now().assume_utc().unix_timestamp()) .unwrap_or_default(), method_type: "card".to_string(), livemode: false, }, error_type: code, }), connector_transaction_id: resp.connector_transaction_id, } } } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct StripePaymentMethod { #[serde(rename = "id")] payment_method_id: String, object: &'static str, card: Option<StripeCard>, created: u64, #[serde(rename = "type")] method_type: String, livemode: bool, } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct Charges { object: &'static str, data: Vec<String>, has_more: bool, total_count: i32, url: String, } impl Charges { pub fn new() -> Self { Self { object: "list", data: vec![], has_more: false, total_count: 0, url: "http://placeholder".to_string(), } } } #[derive(Clone, Debug, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct StripePaymentListConstraints { pub customer: Option<id_type::CustomerId>, pub starting_after: Option<id_type::PaymentId>, pub ending_before: Option<id_type::PaymentId>, #[serde(default = "default_limit")] pub limit: u32, pub created: Option<i64>, #[serde(rename = "created[lt]")] pub created_lt: Option<i64>, #[serde(rename = "created[gt]")] pub created_gt: Option<i64>, #[serde(rename = "created[lte]")] pub created_lte: Option<i64>, #[serde(rename = "created[gte]")] pub created_gte: Option<i64>, } fn default_limit() -> u32 { 10 } impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> { Ok(Self { customer_id: item.customer, starting_after: item.starting_after, ending_before: item.ending_before, limit: item.limit, created: from_timestamp_to_datetime(item.created)?, created_lt: from_timestamp_to_datetime(item.created_lt)?, created_gt: from_timestamp_to_datetime(item.created_gt)?, created_lte: from_timestamp_to_datetime(item.created_lte)?, created_gte: from_timestamp_to_datetime(item.created_gte)?, }) } } #[inline] fn from_timestamp_to_datetime( time: Option<i64>, ) -> Result<Option<PrimitiveDateTime>, errors::ApiErrorResponse> { if let Some(time) = time { let time = time::OffsetDateTime::from_unix_timestamp(time).map_err(|_| { errors::ApiErrorResponse::InvalidRequestData { message: "Error while converting timestamp".to_string(), } })?; Ok(Some(PrimitiveDateTime::new(time.date(), time.time()))) } else { Ok(None) } } #[derive(Default, Eq, PartialEq, Serialize)] pub struct StripePaymentIntentListResponse { pub object: String, pub url: String, pub has_more: bool, pub data: Vec<StripePaymentIntentResponse>, } impl From<payments::PaymentListResponse> for StripePaymentIntentListResponse { fn from(it: payments::PaymentListResponse) -> Self { Self { object: "list".to_string(), url: "/v1/payment_intents".to_string(), has_more: false, data: it.data.into_iter().map(Into::into).collect(), } } } #[derive(PartialEq, Eq, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodOptions { Card { request_three_d_secure: Option<Request3DS>, }, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripeMandateType { SingleUse, MultiUse, } #[derive(PartialEq, Eq, Clone, Default, Deserialize, Serialize, Debug)] pub struct MandateOption { #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub accepted_at: Option<PrimitiveDateTime>, pub user_agent: Option<String>, pub ip_address: Option<masking::Secret<String, IpAddress>>, pub mandate_type: Option<StripeMandateType>, pub amount: Option<i64>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub start_date: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub end_date: Option<PrimitiveDateTime>, } impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments::MandateData> { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( (mandate_data, currency): (Option<MandateData>, Option<String>), ) -> errors::RouterResult<Self> { let currency = currency .ok_or( errors::ApiErrorResponse::MissingRequiredField { field_name: "currency", } .into(), ) .and_then(|c| { c.to_uppercase().parse_enum("currency").change_context( errors::ApiErrorResponse::InvalidDataValue { field_name: "currency", }, ) })?; let mandate_data = mandate_data.map(|mandate| payments::MandateData { mandate_type: match mandate.mandate_type { Some(item) => match item { StripeMandateType::SingleUse => Some(payments::MandateType::SingleUse( payments::MandateAmountData { amount: MinorUnit::new(mandate.amount.unwrap_or_default()), currency, start_date: mandate.start_date, end_date: mandate.end_date, metadata: None, }, )), StripeMandateType::MultiUse => Some(payments::MandateType::MultiUse(Some( payments::MandateAmountData { amount: MinorUnit::new(mandate.amount.unwrap_or_default()), currency, start_date: mandate.start_date, end_date: mandate.end_date, metadata: None, }, ))), }, None => Some(payments::MandateType::MultiUse(Some( payments::MandateAmountData { amount: MinorUnit::new(mandate.amount.unwrap_or_default()), currency, start_date: mandate.start_date, end_date: mandate.end_date, metadata: None, }, ))), }, customer_acceptance: Some(payments::CustomerAcceptance { acceptance_type: payments::AcceptanceType::Online, accepted_at: mandate.customer_acceptance.accepted_at, online: mandate .customer_acceptance .online .map(|online| payments::OnlineMandate { ip_address: Some(online.ip_address), user_agent: online.user_agent, }), }), update_mandate_id: None, }); Ok(mandate_data) } } #[derive(Default, Eq, PartialEq, Serialize, Deserialize, Clone, Debug)] #[serde(rename_all = "snake_case")] pub enum Request3DS { #[default] Automatic, Any, } impl ForeignFrom<Option<Request3DS>> for api_models::enums::AuthenticationType { fn foreign_from(item: Option<Request3DS>) -> Self { match item.unwrap_or_default() { Request3DS::Automatic => Self::NoThreeDs, Request3DS::Any => Self::ThreeDs, } } } #[derive(Default, Eq, PartialEq, Serialize, Debug)] pub struct RedirectUrl { pub return_url: Option<String>, pub url: Option<String>, } #[derive(Eq, PartialEq, serde::Serialize, Debug)] #[serde(tag = "type", rename_all = "snake_case")] pub enum StripeNextAction { RedirectToUrl { redirect_to_url: RedirectUrl, }, DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: payments::BankTransferNextStepsData, }, ThirdPartySdkSessionToken { session_token: Option<payments::SessionToken>, }, QrCodeInformation { image_data_url: Option<url::Url>, display_to_timestamp: Option<i64>, qr_code_url: Option<url::Url>, border_color: Option<String>, display_text: Option<String>, }, FetchQrCodeInformation { qr_code_fetch_url: url::Url, }, DisplayVoucherInformation { voucher_details: payments::VoucherNextStepData, }, WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, InvokeSdkClient { next_action_data: payments::SdkNextActionData, }, CollectOtp { consent_data_required: payments::MobilePaymentConsent, }, InvokeHiddenIframe { iframe_data: payments::IframeData, }, } pub(crate) fn into_stripe_next_action( next_action: Option<payments::NextActionData>, return_url: Option<String>, ) -> Option<StripeNextAction> { next_action.map(|next_action_data| match next_action_data { payments::NextActionData::RedirectToUrl { redirect_to_url } => { StripeNextAction::RedirectToUrl { redirect_to_url: RedirectUrl { return_url, url: Some(redirect_to_url), }, } } payments::NextActionData::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details, } => StripeNextAction::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details, }, payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { StripeNextAction::ThirdPartySdkSessionToken { session_token } } payments::NextActionData::QrCodeInformation { image_data_url, display_to_timestamp, qr_code_url, border_color, display_text, } => StripeNextAction::QrCodeInformation { image_data_url, display_to_timestamp, qr_code_url, border_color, display_text, }, payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => { StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url } } payments::NextActionData::DisplayVoucherInformation { voucher_details } => { StripeNextAction::DisplayVoucherInformation { voucher_details } } payments::NextActionData::WaitScreenInformation { display_from_timestamp, display_to_timestamp, } => StripeNextAction::WaitScreenInformation { display_from_timestamp, display_to_timestamp, }, payments::NextActionData::ThreeDsInvoke { .. } => StripeNextAction::RedirectToUrl { redirect_to_url: RedirectUrl { return_url: None, url: None, }, }, payments::NextActionData::InvokeSdkClient { next_action_data } => { StripeNextAction::InvokeSdkClient { next_action_data } } payments::NextActionData::CollectOtp { consent_data_required, } => StripeNextAction::CollectOtp { consent_data_required, }, payments::NextActionData::InvokeHiddenIframe { iframe_data } => { StripeNextAction::InvokeHiddenIframe { iframe_data } } }) } #[derive(Deserialize, Clone)] pub struct StripePaymentRetrieveBody { pub client_secret: Option<String>, } //To handle payment types that have empty payment method data fn get_pmd_based_on_payment_method_type( payment_method_type: Option<api_enums::PaymentMethodType>, billing_details: Option<hyperswitch_domain_models::address::Address>, ) -> Option<payments::PaymentMethodData> { match payment_method_type { Some(api_enums::PaymentMethodType::UpiIntent) => Some(payments::PaymentMethodData::Upi( payments::UpiData::UpiIntent(payments::UpiIntentData {}), )), Some(api_enums::PaymentMethodType::Fps) => { Some(payments::PaymentMethodData::RealTimePayment(Box::new( payments::RealTimePaymentData::Fps {}, ))) } Some(api_enums::PaymentMethodType::DuitNow) => { Some(payments::PaymentMethodData::RealTimePayment(Box::new( payments::RealTimePaymentData::DuitNow {}, ))) } Some(api_enums::PaymentMethodType::PromptPay) => { Some(payments::PaymentMethodData::RealTimePayment(Box::new( payments::RealTimePaymentData::PromptPay {}, ))) } Some(api_enums::PaymentMethodType::VietQr) => { Some(payments::PaymentMethodData::RealTimePayment(Box::new( payments::RealTimePaymentData::VietQr {}, ))) } Some(api_enums::PaymentMethodType::Ideal) => Some( payments::PaymentMethodData::BankRedirect(payments::BankRedirectData::Ideal { billing_details: billing_details.as_ref().map(|billing_data| { payments::BankRedirectBilling { billing_name: billing_data.get_optional_full_name(), email: billing_data.email.clone(), } }), bank_name: None, country: billing_details .as_ref() .and_then(|billing_data| billing_data.get_optional_country()), }), ), Some(api_enums::PaymentMethodType::LocalBankRedirect) => { Some(payments::PaymentMethodData::BankRedirect( payments::BankRedirectData::LocalBankRedirect {}, )) } _ => None, } }
7,613
1,438
hyperswitch
crates/router/src/compatibility/stripe/refunds/types.rs
.rs
use std::{convert::From, default::Default}; use common_utils::pii; use serde::{Deserialize, Serialize}; use crate::types::api::{admin, refunds}; #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)] pub struct StripeCreateRefundRequest { pub refund_id: Option<String>, pub amount: Option<i64>, pub payment_intent: common_utils::id_type::PaymentId, pub reason: Option<String>, pub metadata: Option<pii::SecretSerdeValue>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct StripeUpdateRefundRequest { #[serde(skip)] pub refund_id: String, pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Clone, Serialize, PartialEq, Eq, Debug)] pub struct StripeRefundResponse { pub id: String, pub amount: i64, pub currency: String, pub payment_intent: common_utils::id_type::PaymentId, pub status: StripeRefundStatus, pub created: Option<i64>, pub metadata: pii::SecretSerdeValue, } #[derive(Clone, Serialize, Deserialize, Eq, PartialEq, Debug)] #[serde(rename_all = "snake_case")] pub enum StripeRefundStatus { Succeeded, Failed, Pending, RequiresAction, } impl From<StripeCreateRefundRequest> for refunds::RefundRequest { fn from(req: StripeCreateRefundRequest) -> Self { Self { refund_id: req.refund_id, amount: req.amount.map(common_utils::types::MinorUnit::new), payment_id: req.payment_intent, reason: req.reason, refund_type: Some(refunds::RefundType::Instant), metadata: req.metadata, merchant_connector_details: req.merchant_connector_details, ..Default::default() } } } impl From<StripeUpdateRefundRequest> for refunds::RefundUpdateRequest { fn from(req: StripeUpdateRefundRequest) -> Self { Self { refund_id: req.refund_id, metadata: req.metadata, reason: None, } } } impl From<refunds::RefundStatus> for StripeRefundStatus { fn from(status: refunds::RefundStatus) -> Self { match status { refunds::RefundStatus::Succeeded => Self::Succeeded, refunds::RefundStatus::Failed => Self::Failed, refunds::RefundStatus::Pending => Self::Pending, refunds::RefundStatus::Review => Self::RequiresAction, } } } impl From<refunds::RefundResponse> for StripeRefundResponse { fn from(res: refunds::RefundResponse) -> Self { Self { id: res.refund_id, amount: res.amount.get_amount_as_i64(), currency: res.currency.to_ascii_lowercase(), payment_intent: res.payment_id, status: res.status.into(), created: res.created_at.map(|t| t.assume_utc().unix_timestamp()), metadata: res .metadata .unwrap_or_else(|| masking::Secret::new(serde_json::json!({}))), } } }
696
1,439
hyperswitch
crates/router/src/compatibility/stripe/setup_intents/types.rs
.rs
use std::str::FromStr; use api_models::payments; use common_utils::{date_time, ext_traits::StringExt, id_type, pii as secret}; use error_stack::ResultExt; use router_env::logger; use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::{ compatibility::stripe::{ payment_intents::types as payment_intent, refunds::types as stripe_refunds, }, consts, core::errors, pii::{self, PeekInterface}, types::{ api::{self as api_types, admin, enums as api_enums}, transformers::{ForeignFrom, ForeignTryFrom}, }, utils::OptionExt, }; #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct StripeBillingDetails { pub address: Option<payments::AddressDetails>, pub email: Option<pii::Email>, pub name: Option<String>, pub phone: Option<pii::Secret<String>>, } impl From<StripeBillingDetails> for payments::Address { fn from(details: StripeBillingDetails) -> Self { Self { address: details.address, phone: Some(payments::PhoneDetails { number: details.phone, country_code: None, }), email: details.email, } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct StripeCard { pub number: cards::CardNumber, pub exp_month: pii::Secret<String>, pub exp_year: pii::Secret<String>, pub cvc: pii::Secret<String>, } // ApplePay wallet param is not available in stripe Docs #[derive(Serialize, PartialEq, Eq, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripeWallet { ApplePay(payments::ApplePayWalletData), } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodType { #[default] Card, Wallet, } impl From<StripePaymentMethodType> for api_enums::PaymentMethod { fn from(item: StripePaymentMethodType) -> Self { match item { StripePaymentMethodType::Card => Self::Card, StripePaymentMethodType::Wallet => Self::Wallet, } } } #[derive(Default, PartialEq, Eq, Deserialize, Clone)] pub struct StripePaymentMethodData { #[serde(rename = "type")] pub stype: StripePaymentMethodType, pub billing_details: Option<StripeBillingDetails>, #[serde(flatten)] pub payment_method_details: Option<StripePaymentMethodDetails>, // enum pub metadata: Option<Value>, } #[derive(PartialEq, Eq, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum StripePaymentMethodDetails { Card(StripeCard), Wallet(StripeWallet), } impl From<StripeCard> for payments::Card { fn from(card: StripeCard) -> Self { Self { card_number: card.number, card_exp_month: card.exp_month, card_exp_year: card.exp_year, card_holder_name: Some(masking::Secret::new("stripe_cust".to_owned())), card_cvc: card.cvc, card_issuer: None, card_network: None, bank_code: None, card_issuing_country: None, card_type: None, nick_name: None, } } } impl From<StripeWallet> for payments::WalletData { fn from(wallet: StripeWallet) -> Self { match wallet { StripeWallet::ApplePay(data) => Self::ApplePay(data), } } } impl From<StripePaymentMethodDetails> for payments::PaymentMethodData { fn from(item: StripePaymentMethodDetails) -> Self { match item { StripePaymentMethodDetails::Card(card) => Self::Card(payments::Card::from(card)), StripePaymentMethodDetails::Wallet(wallet) => { Self::Wallet(payments::WalletData::from(wallet)) } } } } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct Shipping { pub address: Option<payments::AddressDetails>, pub name: Option<String>, pub carrier: Option<String>, pub phone: Option<pii::Secret<String>>, pub tracking_number: Option<pii::Secret<String>>, } impl From<Shipping> for payments::Address { fn from(details: Shipping) -> Self { Self { address: details.address, phone: Some(payments::PhoneDetails { number: details.phone, country_code: None, }), email: None, } } } #[derive(Default, Deserialize, Clone)] pub struct StripeSetupIntentRequest { pub confirm: Option<bool>, pub customer: Option<id_type::CustomerId>, pub connector: Option<Vec<api_enums::RoutableConnectors>>, pub description: Option<String>, pub currency: Option<String>, pub payment_method_data: Option<StripePaymentMethodData>, pub receipt_email: Option<pii::Email>, pub return_url: Option<url::Url>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub shipping: Option<Shipping>, pub billing_details: Option<StripeBillingDetails>, pub statement_descriptor: Option<String>, pub statement_descriptor_suffix: Option<String>, pub metadata: Option<secret::SecretSerdeValue>, pub client_secret: Option<pii::Secret<String>>, pub payment_method_options: Option<payment_intent::StripePaymentMethodOptions>, pub payment_method: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, pub receipt_ipaddress: Option<String>, pub user_agent: Option<String>, pub mandate_data: Option<payment_intent::MandateData>, pub connector_metadata: Option<payments::ConnectorMetadata>, } impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripeSetupIntentRequest) -> errors::RouterResult<Self> { let routable_connector: Option<api_enums::RoutableConnectors> = item.connector.and_then(|v| v.into_iter().next()); let routing = routable_connector .map(|connector| { api_models::routing::RoutingAlgorithm::Single(Box::new( api_models::routing::RoutableConnectorChoice { choice_kind: api_models::routing::RoutableChoiceKind::FullStruct, connector, merchant_connector_id: None, }, )) }) .map(|r| { serde_json::to_value(r) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("converting to routing failed") }) .transpose()?; let ip_address = item .receipt_ipaddress .map(|ip| std::net::IpAddr::from_str(ip.as_str())) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "receipt_ipaddress".to_string(), expected_format: "127.0.0.1".to_string(), })?; let metadata_object = item .metadata .clone() .parse_value("metadata") .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "metadata mapping failed", })?; let request = Ok(Self { amount: Some(api_types::Amount::Zero), capture_method: None, amount_to_capture: None, confirm: item.confirm, customer_id: item.customer, currency: item .currency .as_ref() .map(|c| c.to_uppercase().parse_enum("currency")) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "currency", })?, email: item.receipt_email, name: item .billing_details .as_ref() .and_then(|b| b.name.as_ref().map(|x| masking::Secret::new(x.to_owned()))), phone: item.shipping.as_ref().and_then(|s| s.phone.clone()), description: item.description, return_url: item.return_url, payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| { pmd.payment_method_details .as_ref() .map(|spmd| payments::PaymentMethodDataRequest { payment_method_data: Some(payments::PaymentMethodData::from( spmd.to_owned(), )), billing: pmd.billing_details.clone().map(payments::Address::from), }) }), payment_method: item .payment_method_data .as_ref() .map(|pmd| api_enums::PaymentMethod::from(pmd.stype.to_owned())), shipping: item .shipping .as_ref() .map(|s| payments::Address::from(s.to_owned())), billing: item .billing_details .as_ref() .map(|b| payments::Address::from(b.to_owned())), statement_descriptor_name: item.statement_descriptor, statement_descriptor_suffix: item.statement_descriptor_suffix, metadata: metadata_object, client_secret: item.client_secret.map(|s| s.peek().clone()), setup_future_usage: item.setup_future_usage, merchant_connector_details: item.merchant_connector_details, routing, authentication_type: match item.payment_method_options { Some(pmo) => { let payment_intent::StripePaymentMethodOptions::Card { request_three_d_secure, }: payment_intent::StripePaymentMethodOptions = pmo; Some(api_enums::AuthenticationType::foreign_from( request_three_d_secure, )) } None => None, }, mandate_data: ForeignTryFrom::foreign_try_from(( item.mandate_data, item.currency.to_owned(), ))?, browser_info: Some( serde_json::to_value(crate::types::BrowserInformation { ip_address, user_agent: item.user_agent, ..Default::default() }) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("convert to browser info failed")?, ), connector_metadata: item.connector_metadata, ..Default::default() }); request } } #[derive(Clone, Default, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum StripeSetupStatus { Succeeded, Canceled, #[default] Processing, RequiresAction, RequiresPaymentMethod, RequiresConfirmation, } impl From<api_enums::IntentStatus> for StripeSetupStatus { fn from(item: api_enums::IntentStatus) -> Self { match item { api_enums::IntentStatus::Succeeded | api_enums::IntentStatus::PartiallyCaptured => { Self::Succeeded } api_enums::IntentStatus::Failed => Self::Canceled, api_enums::IntentStatus::Processing => Self::Processing, api_enums::IntentStatus::RequiresCustomerAction => Self::RequiresAction, api_enums::IntentStatus::RequiresMerchantAction => Self::RequiresAction, api_enums::IntentStatus::RequiresPaymentMethod => Self::RequiresPaymentMethod, api_enums::IntentStatus::RequiresConfirmation => Self::RequiresConfirmation, api_enums::IntentStatus::RequiresCapture | api_enums::IntentStatus::PartiallyCapturedAndCapturable => { logger::error!("Invalid status change"); Self::Canceled } api_enums::IntentStatus::Cancelled => Self::Canceled, } } } #[derive(Debug, Serialize, Deserialize, Copy, Clone, strum::Display)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum CancellationReason { Duplicate, Fraudulent, RequestedByCustomer, Abandoned, } #[derive(Debug, Deserialize, Serialize, Copy, Clone)] pub struct StripePaymentCancelRequest { cancellation_reason: Option<CancellationReason>, } impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest { fn from(item: StripePaymentCancelRequest) -> Self { Self { cancellation_reason: item.cancellation_reason.map(|c| c.to_string()), ..Self::default() } } } #[derive(Default, Eq, PartialEq, Serialize)] pub struct RedirectUrl { pub return_url: Option<String>, pub url: Option<String>, } #[derive(Eq, PartialEq, serde::Serialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum StripeNextAction { RedirectToUrl { redirect_to_url: RedirectUrl, }, DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: payments::BankTransferNextStepsData, }, ThirdPartySdkSessionToken { session_token: Option<payments::SessionToken>, }, QrCodeInformation { image_data_url: Option<url::Url>, display_to_timestamp: Option<i64>, qr_code_url: Option<url::Url>, border_color: Option<String>, display_text: Option<String>, }, FetchQrCodeInformation { qr_code_fetch_url: url::Url, }, DisplayVoucherInformation { voucher_details: payments::VoucherNextStepData, }, WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, InvokeSdkClient { next_action_data: payments::SdkNextActionData, }, CollectOtp { consent_data_required: payments::MobilePaymentConsent, }, InvokeHiddenIframe { iframe_data: payments::IframeData, }, } pub(crate) fn into_stripe_next_action( next_action: Option<payments::NextActionData>, return_url: Option<String>, ) -> Option<StripeNextAction> { next_action.map(|next_action_data| match next_action_data { payments::NextActionData::RedirectToUrl { redirect_to_url } => { StripeNextAction::RedirectToUrl { redirect_to_url: RedirectUrl { return_url, url: Some(redirect_to_url), }, } } payments::NextActionData::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details, } => StripeNextAction::DisplayBankTransferInformation { bank_transfer_steps_and_charges_details, }, payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { StripeNextAction::ThirdPartySdkSessionToken { session_token } } payments::NextActionData::QrCodeInformation { image_data_url, display_to_timestamp, qr_code_url, display_text, border_color, } => StripeNextAction::QrCodeInformation { image_data_url, display_to_timestamp, qr_code_url, display_text, border_color, }, payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => { StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url } } payments::NextActionData::DisplayVoucherInformation { voucher_details } => { StripeNextAction::DisplayVoucherInformation { voucher_details } } payments::NextActionData::WaitScreenInformation { display_from_timestamp, display_to_timestamp, } => StripeNextAction::WaitScreenInformation { display_from_timestamp, display_to_timestamp, }, payments::NextActionData::ThreeDsInvoke { .. } => StripeNextAction::RedirectToUrl { redirect_to_url: RedirectUrl { return_url: None, url: None, }, }, payments::NextActionData::InvokeSdkClient { next_action_data } => { StripeNextAction::InvokeSdkClient { next_action_data } } payments::NextActionData::CollectOtp { consent_data_required, } => StripeNextAction::CollectOtp { consent_data_required, }, payments::NextActionData::InvokeHiddenIframe { iframe_data } => { StripeNextAction::InvokeHiddenIframe { iframe_data } } }) } #[derive(Default, Eq, PartialEq, Serialize)] pub struct StripeSetupIntentResponse { pub id: id_type::PaymentId, pub object: String, pub status: StripeSetupStatus, pub client_secret: Option<masking::Secret<String>>, pub metadata: Option<Value>, #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, pub customer: Option<id_type::CustomerId>, pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>, pub mandate_id: Option<String>, pub next_action: Option<StripeNextAction>, pub last_payment_error: Option<LastPaymentError>, pub charges: payment_intent::Charges, pub connector_transaction_id: Option<String>, } #[derive(Default, Eq, PartialEq, Serialize)] pub struct LastPaymentError { charge: Option<String>, code: Option<String>, decline_code: Option<String>, message: String, param: Option<String>, payment_method: StripePaymentMethod, #[serde(rename = "type")] error_type: String, } #[derive(Default, Eq, PartialEq, Serialize)] pub struct StripePaymentMethod { #[serde(rename = "id")] payment_method_id: String, object: &'static str, card: Option<StripeCard>, created: u64, #[serde(rename = "type")] method_type: String, livemode: bool, } impl From<payments::PaymentsResponse> for StripeSetupIntentResponse { fn from(resp: payments::PaymentsResponse) -> Self { Self { object: "setup_intent".to_owned(), status: StripeSetupStatus::from(resp.status), client_secret: resp.client_secret, charges: payment_intent::Charges::new(), created: resp.created, customer: resp.customer_id, metadata: resp.metadata, id: resp.payment_id, refunds: resp .refunds .map(|a| a.into_iter().map(Into::into).collect()), mandate_id: resp.mandate_id, next_action: into_stripe_next_action(resp.next_action, resp.return_url), last_payment_error: resp.error_code.map(|code| -> LastPaymentError { LastPaymentError { charge: None, code: Some(code.to_owned()), decline_code: None, message: resp .error_message .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), param: None, payment_method: StripePaymentMethod { payment_method_id: "place_holder_id".to_string(), object: "payment_method", card: None, created: u64::try_from(date_time::now().assume_utc().unix_timestamp()) .unwrap_or_default(), method_type: "card".to_string(), livemode: false, }, error_type: code, } }), connector_transaction_id: resp.connector_transaction_id, } } } #[derive(Clone, Debug, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct StripePaymentListConstraints { pub customer: Option<id_type::CustomerId>, pub starting_after: Option<id_type::PaymentId>, pub ending_before: Option<id_type::PaymentId>, #[serde(default = "default_limit")] pub limit: u32, pub created: Option<i64>, #[serde(rename = "created[lt]")] pub created_lt: Option<i64>, #[serde(rename = "created[gt]")] pub created_gt: Option<i64>, #[serde(rename = "created[lte]")] pub created_lte: Option<i64>, #[serde(rename = "created[gte]")] pub created_gte: Option<i64>, } fn default_limit() -> u32 { 10 } impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints { type Error = error_stack::Report<errors::ApiErrorResponse>; fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> { Ok(Self { customer_id: item.customer, starting_after: item.starting_after, ending_before: item.ending_before, limit: item.limit, created: from_timestamp_to_datetime(item.created)?, created_lt: from_timestamp_to_datetime(item.created_lt)?, created_gt: from_timestamp_to_datetime(item.created_gt)?, created_lte: from_timestamp_to_datetime(item.created_lte)?, created_gte: from_timestamp_to_datetime(item.created_gte)?, }) } } #[inline] fn from_timestamp_to_datetime( time: Option<i64>, ) -> Result<Option<time::PrimitiveDateTime>, errors::ApiErrorResponse> { if let Some(time) = time { let time = time::OffsetDateTime::from_unix_timestamp(time).map_err(|err| { logger::error!("Error: from_unix_timestamp: {}", err); errors::ApiErrorResponse::InvalidRequestData { message: "Error while converting timestamp".to_string(), } })?; Ok(Some(time::PrimitiveDateTime::new(time.date(), time.time()))) } else { Ok(None) } }
4,569
1,440
hyperswitch
crates/router/src/compatibility/stripe/customers/types.rs
.rs
use std::{convert::From, default::Default}; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] use api_models::payment_methods as api_types; use api_models::payments; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use common_utils::{crypto::Encryptable, date_time}; use common_utils::{ id_type, pii::{self, Email}, types::Description, }; use serde::{Deserialize, Serialize}; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::logger; use crate::types::{api, api::enums as api_enums}; #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct Shipping { pub address: StripeAddressDetails, pub name: Option<masking::Secret<String>>, pub carrier: Option<String>, pub phone: Option<masking::Secret<String>>, pub tracking_number: Option<masking::Secret<String>>, } #[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)] pub struct StripeAddressDetails { pub city: Option<String>, pub country: Option<api_enums::CountryAlpha2>, pub line1: Option<masking::Secret<String>>, pub line2: Option<masking::Secret<String>>, pub postal_code: Option<masking::Secret<String>>, pub state: Option<masking::Secret<String>>, } #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CreateCustomerRequest { pub email: Option<Email>, pub invoice_prefix: Option<String>, pub name: Option<masking::Secret<String>>, pub phone: Option<masking::Secret<String>>, pub address: Option<StripeAddressDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub description: Option<Description>, pub shipping: Option<Shipping>, pub payment_method: Option<String>, // not used pub balance: Option<i64>, // not used pub cash_balance: Option<pii::SecretSerdeValue>, // not used pub coupon: Option<String>, // not used pub invoice_settings: Option<pii::SecretSerdeValue>, // not used pub next_invoice_sequence: Option<String>, // not used pub preferred_locales: Option<String>, // not used pub promotion_code: Option<String>, // not used pub source: Option<String>, // not used pub tax: Option<pii::SecretSerdeValue>, // not used pub tax_exempt: Option<String>, // not used pub tax_id_data: Option<String>, // not used pub test_clock: Option<String>, // not used } #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CustomerUpdateRequest { pub description: Option<Description>, pub email: Option<Email>, pub phone: Option<masking::Secret<String, masking::WithType>>, pub name: Option<masking::Secret<String>>, pub address: Option<StripeAddressDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub shipping: Option<Shipping>, pub payment_method: Option<String>, // not used pub balance: Option<i64>, // not used pub cash_balance: Option<pii::SecretSerdeValue>, // not used pub coupon: Option<String>, // not used pub default_source: Option<String>, // not used pub invoice_settings: Option<pii::SecretSerdeValue>, // not used pub next_invoice_sequence: Option<String>, // not used pub preferred_locales: Option<String>, // not used pub promotion_code: Option<String>, // not used pub source: Option<String>, // not used pub tax: Option<pii::SecretSerdeValue>, // not used pub tax_exempt: Option<String>, // not used } #[derive(Serialize, PartialEq, Eq)] pub struct CreateCustomerResponse { pub id: id_type::CustomerId, pub object: String, pub created: u64, pub description: Option<Description>, pub email: Option<Email>, pub metadata: Option<pii::SecretSerdeValue>, pub name: Option<masking::Secret<String>>, pub phone: Option<masking::Secret<String, masking::WithType>>, } pub type CustomerRetrieveResponse = CreateCustomerResponse; pub type CustomerUpdateResponse = CreateCustomerResponse; #[derive(Serialize, PartialEq, Eq)] pub struct CustomerDeleteResponse { pub id: id_type::CustomerId, pub deleted: bool, } impl From<StripeAddressDetails> for payments::AddressDetails { fn from(address: StripeAddressDetails) -> Self { Self { city: address.city, country: address.country, line1: address.line1, line2: address.line2, zip: address.postal_code, state: address.state, first_name: None, line3: None, last_name: None, } } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl From<CreateCustomerRequest> for api::CustomerRequest { fn from(req: CreateCustomerRequest) -> Self { Self { customer_id: Some(common_utils::generate_customer_id_of_default_length()), name: req.name, phone: req.phone, email: req.email, description: req.description, metadata: req.metadata, address: req.address.map(|s| s.into()), ..Default::default() } } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl From<CustomerUpdateRequest> for api::CustomerUpdateRequest { fn from(req: CustomerUpdateRequest) -> Self { Self { name: req.name, phone: req.phone, email: req.email, description: req.description, metadata: req.metadata, address: req.address.map(|s| s.into()), ..Default::default() } } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl From<api::CustomerResponse> for CreateCustomerResponse { fn from(cust: api::CustomerResponse) -> Self { let cust = cust.into_inner(); Self { id: cust.customer_id, object: "customer".to_owned(), created: u64::try_from(cust.created_at.assume_utc().unix_timestamp()).unwrap_or_else( |error| { logger::error!( %error, "incorrect value for `customer.created_at` provided {}", cust.created_at ); // Current timestamp converted to Unix timestamp should have a positive value // for many years to come u64::try_from(date_time::now().assume_utc().unix_timestamp()) .unwrap_or_default() }, ), description: cust.description, email: cust.email.map(|inner| inner.into()), metadata: cust.metadata, name: cust.name.map(Encryptable::into_inner), phone: cust.phone.map(Encryptable::into_inner), } } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl From<api::CustomerDeleteResponse> for CustomerDeleteResponse { fn from(cust: api::CustomerDeleteResponse) -> Self { Self { id: cust.customer_id, deleted: cust.customer_deleted, } } } #[derive(Default, Serialize, PartialEq, Eq)] pub struct CustomerPaymentMethodListResponse { pub object: &'static str, pub data: Vec<PaymentMethodData>, } #[derive(Default, Serialize, PartialEq, Eq)] pub struct PaymentMethodData { pub id: Option<String>, pub object: &'static str, pub card: Option<CardDetails>, pub created: Option<time::PrimitiveDateTime>, } #[derive(Default, Serialize, PartialEq, Eq)] pub struct CardDetails { pub country: Option<String>, pub last4: Option<String>, pub exp_month: Option<masking::Secret<String>>, pub exp_year: Option<masking::Secret<String>>, pub fingerprint: Option<masking::Secret<String>>, } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] impl From<api::CustomerPaymentMethodsListResponse> for CustomerPaymentMethodListResponse { fn from(item: api::CustomerPaymentMethodsListResponse) -> Self { let customer_payment_methods = item.customer_payment_methods; let data = customer_payment_methods .into_iter() .map(From::from) .collect(); Self { object: "list", data, } } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] impl From<api_types::CustomerPaymentMethod> for PaymentMethodData { fn from(item: api_types::CustomerPaymentMethod) -> Self { let card = item.card.map(From::from); Self { id: Some(item.payment_token), object: "payment_method", card, created: item.created, } } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] impl From<api_types::CardDetailFromLocker> for CardDetails { fn from(item: api_types::CardDetailFromLocker) -> Self { Self { country: item.issuer_country, last4: item.last4_digits, exp_month: item.expiry_month, exp_year: item.expiry_year, fingerprint: item.card_fingerprint, } } }
2,154
1,441
hyperswitch
crates/router/src/db/kafka_store.rs
.rs
use std::sync::Arc; use ::payment_methods::state::PaymentMethodsStorageInterface; use common_enums::enums::MerchantStorageScheme; use common_utils::{ errors::CustomResult, id_type, types::{keymanager::KeyManagerState, theme::ThemeLineage}, }; #[cfg(feature = "v2")] use diesel_models::ephemeral_key::{ClientSecretType, ClientSecretTypeNew}; use diesel_models::{ enums, enums::ProcessTrackerStatus, ephemeral_key::{EphemeralKey, EphemeralKeyNew}, reverse_lookup::{ReverseLookup, ReverseLookupNew}, user_role as user_storage, }; #[cfg(feature = "payouts")] use hyperswitch_domain_models::payouts::{ payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface, }; use hyperswitch_domain_models::{ disputes, payment_methods::PaymentMethodInterface, payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface}, refunds, }; #[cfg(not(feature = "payouts"))] use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface}; use masking::Secret; use redis_interface::{errors::RedisError, RedisConnectionPool, RedisEntryId}; use router_env::{instrument, logger, tracing}; use scheduler::{ db::{process_tracker::ProcessTrackerInterface, queue::QueueInterface}, SchedulerInterface, }; use serde::Serialize; use storage_impl::{config::TenantConfig, redis::kv_store::RedisConnInterface}; use time::PrimitiveDateTime; use super::{ dashboard_metadata::DashboardMetadataInterface, ephemeral_key::ClientSecretInterface, role::RoleInterface, user::{sample_data::BatchSampleDataInterface, theme::ThemeInterface, UserInterface}, user_authentication_method::UserAuthenticationMethodInterface, user_key_store::UserKeyStoreInterface, user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload, UserRoleInterface}, }; #[cfg(feature = "payouts")] use crate::services::kafka::payout::KafkaPayout; use crate::{ core::errors::{self, ProcessTrackerError}, db::{ self, address::AddressInterface, api_keys::ApiKeyInterface, authentication::AuthenticationInterface, authorization::AuthorizationInterface, business_profile::ProfileInterface, callback_mapper::CallbackMapperInterface, capture::CaptureInterface, cards_info::CardsInfoInterface, configs::ConfigInterface, customers::CustomerInterface, dispute::DisputeInterface, ephemeral_key::EphemeralKeyInterface, events::EventInterface, file::FileMetadataInterface, generic_link::GenericLinkInterface, gsm::GsmInterface, health_check::HealthCheckDbInterface, locker_mock_up::LockerMockUpInterface, mandate::MandateInterface, merchant_account::MerchantAccountInterface, merchant_connector_account::{ConnectorAccessToken, MerchantConnectorAccountInterface}, merchant_key_store::MerchantKeyStoreInterface, payment_link::PaymentLinkInterface, refund::RefundInterface, reverse_lookup::ReverseLookupInterface, routing_algorithm::RoutingAlgorithmInterface, unified_translations::UnifiedTranslationsInterface, AccountsStorageInterface, CommonStorageInterface, GlobalStorageInterface, MasterKeyInterface, StorageInterface, }, services::{kafka::KafkaProducer, Store}, types::{domain, storage, AccessToken}, }; #[derive(Debug, Clone, Serialize)] pub struct TenantID(pub String); #[derive(Clone)] pub struct KafkaStore { pub kafka_producer: KafkaProducer, pub diesel_store: Store, pub tenant_id: TenantID, } impl KafkaStore { pub async fn new( store: Store, mut kafka_producer: KafkaProducer, tenant_id: TenantID, tenant_config: &dyn TenantConfig, ) -> Self { kafka_producer.set_tenancy(tenant_config); Self { kafka_producer, diesel_store: store, tenant_id, } } } #[async_trait::async_trait] impl AddressInterface for KafkaStore { async fn find_address_by_address_id( &self, state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store .find_address_by_address_id(state, address_id, key_store) .await } async fn update_address( &self, state: &KeyManagerState, address_id: String, address: storage::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store .update_address(state, address_id, address, key_store) .await } async fn update_address_for_payments( &self, state: &KeyManagerState, this: domain::PaymentAddress, address: domain::AddressUpdate, payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store .update_address_for_payments( state, this, address, payment_id, key_store, storage_scheme, ) .await } async fn insert_address_for_payments( &self, state: &KeyManagerState, payment_id: &id_type::PaymentId, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store .insert_address_for_payments(state, payment_id, address, key_store, storage_scheme) .await } async fn find_address_by_merchant_id_payment_id_address_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { self.diesel_store .find_address_by_merchant_id_payment_id_address_id( state, merchant_id, payment_id, address_id, key_store, storage_scheme, ) .await } async fn insert_address_for_customers( &self, state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { self.diesel_store .insert_address_for_customers(state, address, key_store) .await } async fn update_address_by_merchant_id_customer_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, address: storage::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError> { self.diesel_store .update_address_by_merchant_id_customer_id( state, customer_id, merchant_id, address, key_store, ) .await } } #[async_trait::async_trait] impl ApiKeyInterface for KafkaStore { async fn insert_api_key( &self, api_key: storage::ApiKeyNew, ) -> CustomResult<storage::ApiKey, errors::StorageError> { self.diesel_store.insert_api_key(api_key).await } async fn update_api_key( &self, merchant_id: id_type::MerchantId, key_id: id_type::ApiKeyId, api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError> { self.diesel_store .update_api_key(merchant_id, key_id, api_key) .await } async fn revoke_api_key( &self, merchant_id: &id_type::MerchantId, key_id: &id_type::ApiKeyId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store.revoke_api_key(merchant_id, key_id).await } async fn find_api_key_by_merchant_id_key_id_optional( &self, merchant_id: &id_type::MerchantId, key_id: &id_type::ApiKeyId, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { self.diesel_store .find_api_key_by_merchant_id_key_id_optional(merchant_id, key_id) .await } async fn find_api_key_by_hash_optional( &self, hashed_api_key: storage::HashedApiKey, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { self.diesel_store .find_api_key_by_hash_optional(hashed_api_key) .await } async fn list_api_keys_by_merchant_id( &self, merchant_id: &id_type::MerchantId, limit: Option<i64>, offset: Option<i64>, ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> { self.diesel_store .list_api_keys_by_merchant_id(merchant_id, limit, offset) .await } } #[async_trait::async_trait] impl CardsInfoInterface for KafkaStore { async fn get_card_info( &self, card_iin: &str, ) -> CustomResult<Option<storage::CardInfo>, errors::StorageError> { self.diesel_store.get_card_info(card_iin).await } async fn add_card_info( &self, data: storage::CardInfo, ) -> CustomResult<storage::CardInfo, errors::StorageError> { self.diesel_store.add_card_info(data).await } async fn update_card_info( &self, card_iin: String, data: storage::UpdateCardInfo, ) -> CustomResult<storage::CardInfo, errors::StorageError> { self.diesel_store.update_card_info(card_iin, data).await } } #[async_trait::async_trait] impl ConfigInterface for KafkaStore { async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store.insert_config(config).await } async fn find_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store.find_config_by_key(key).await } async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store.find_config_by_key_from_db(key).await } async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store .update_config_in_database(key, config_update) .await } async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store .update_config_by_key(key, config_update) .await } async fn delete_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store.delete_config_by_key(key).await } async fn find_config_by_key_unwrap_or( &self, key: &str, default_config: Option<String>, ) -> CustomResult<storage::Config, errors::StorageError> { self.diesel_store .find_config_by_key_unwrap_or(key, default_config) .await } } #[async_trait::async_trait] impl CustomerInterface for KafkaStore { #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_customer_by_customer_id_merchant_id(customer_id, merchant_id) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, errors::StorageError> { self.diesel_store .find_customer_optional_by_customer_id_merchant_id( state, customer_id, merchant_id, key_store, storage_scheme, ) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, errors::StorageError> { self.diesel_store .find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( state, customer_id, merchant_id, key_store, storage_scheme, ) .await } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<domain::Customer>, errors::StorageError> { self.diesel_store .find_optional_by_merchant_id_merchant_reference_id( state, customer_id, merchant_id, key_store, storage_scheme, ) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn update_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, customer: domain::Customer, customer_update: storage::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .update_customer_by_customer_id_merchant_id( state, customer_id, merchant_id, customer, customer_update, key_store, storage_scheme, ) .await } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn update_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: domain::Customer, merchant_id: &id_type::MerchantId, customer_update: storage::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .update_customer_by_global_id( state, id, customer, merchant_id, customer_update, key_store, storage_scheme, ) .await } async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, constraints: super::customers::CustomerListConstraints, ) -> CustomResult<Vec<domain::Customer>, errors::StorageError> { self.diesel_store .list_customers_by_merchant_id(state, merchant_id, key_store, constraints) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .find_customer_by_customer_id_merchant_id( state, customer_id, merchant_id, key_store, storage_scheme, ) .await } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_customer_by_merchant_reference_id_merchant_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .find_customer_by_merchant_reference_id_merchant_id( state, merchant_reference_id, merchant_id, key_store, storage_scheme, ) .await } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .find_customer_by_global_id(state, id, merchant_id, key_store, storage_scheme) .await } async fn insert_customer( &self, customer_data: domain::Customer, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::Customer, errors::StorageError> { self.diesel_store .insert_customer(customer_data, state, key_store, storage_scheme) .await } } #[async_trait::async_trait] impl DisputeInterface for KafkaStore { async fn insert_dispute( &self, dispute_new: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError> { let dispute = self.diesel_store.insert_dispute(dispute_new).await?; if let Err(er) = self .kafka_producer .log_dispute(&dispute, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to add analytics entry for Dispute {dispute:?}", error_message=?er); }; Ok(dispute) } async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult<Option<storage::Dispute>, errors::StorageError> { self.diesel_store .find_by_merchant_id_payment_id_connector_dispute_id( merchant_id, payment_id, connector_dispute_id, ) .await } async fn find_dispute_by_merchant_id_dispute_id( &self, merchant_id: &id_type::MerchantId, dispute_id: &str, ) -> CustomResult<storage::Dispute, errors::StorageError> { self.diesel_store .find_dispute_by_merchant_id_dispute_id(merchant_id, dispute_id) .await } async fn find_disputes_by_constraints( &self, merchant_id: &id_type::MerchantId, dispute_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { self.diesel_store .find_disputes_by_constraints(merchant_id, dispute_constraints) .await } async fn update_dispute( &self, this: storage::Dispute, dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError> { let dispute_new = self .diesel_store .update_dispute(this.clone(), dispute) .await?; if let Err(er) = self .kafka_producer .log_dispute(&dispute_new, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to add analytics entry for Dispute {dispute_new:?}", error_message=?er); }; Ok(dispute_new) } async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { self.diesel_store .find_disputes_by_merchant_id_payment_id(merchant_id, payment_id) .await } async fn get_dispute_status_with_count( &self, merchant_id: &id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { self.diesel_store .get_dispute_status_with_count(merchant_id, profile_id_list, time_range) .await } } #[async_trait::async_trait] impl EphemeralKeyInterface for KafkaStore { #[cfg(feature = "v1")] async fn create_ephemeral_key( &self, ek: EphemeralKeyNew, validity: i64, ) -> CustomResult<EphemeralKey, errors::StorageError> { self.diesel_store.create_ephemeral_key(ek, validity).await } #[cfg(feature = "v1")] async fn get_ephemeral_key( &self, key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { self.diesel_store.get_ephemeral_key(key).await } #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, id: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { self.diesel_store.delete_ephemeral_key(id).await } } #[async_trait::async_trait] impl ClientSecretInterface for KafkaStore { #[cfg(feature = "v2")] async fn create_client_secret( &self, ek: ClientSecretTypeNew, validity: i64, ) -> CustomResult<ClientSecretType, errors::StorageError> { self.diesel_store.create_client_secret(ek, validity).await } #[cfg(feature = "v2")] async fn get_client_secret( &self, key: &str, ) -> CustomResult<ClientSecretType, errors::StorageError> { self.diesel_store.get_client_secret(key).await } #[cfg(feature = "v2")] async fn delete_client_secret( &self, id: &str, ) -> CustomResult<ClientSecretType, errors::StorageError> { self.diesel_store.delete_client_secret(id).await } } #[async_trait::async_trait] impl EventInterface for KafkaStore { async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { self.diesel_store .insert_event(state, event, merchant_key_store) .await } async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { self.diesel_store .find_event_by_merchant_id_event_id(state, merchant_id, event_id, merchant_key_store) .await } async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_merchant_id_primary_object_id( state, merchant_id, primary_object_id, merchant_key_store, ) .await } async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, created_after: PrimitiveDateTime, created_before: PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_merchant_id_constraints( state, merchant_id, created_after, created_before, limit, offset, is_delivered, merchant_key_store, ) .await } async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_events_by_merchant_id_initial_attempt_id( state, merchant_id, initial_attempt_id, merchant_key_store, ) .await } async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_profile_id_primary_object_id( state, profile_id, primary_object_id, merchant_key_store, ) .await } async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, created_after: PrimitiveDateTime, created_before: PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { self.diesel_store .list_initial_events_by_profile_id_constraints( state, profile_id, created_after, created_before, limit, offset, is_delivered, merchant_key_store, ) .await } async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { self.diesel_store .update_event_by_merchant_id_event_id( state, merchant_id, event_id, event, merchant_key_store, ) .await } async fn count_initial_events_by_constraints( &self, merchant_id: &id_type::MerchantId, profile_id: Option<id_type::ProfileId>, created_after: PrimitiveDateTime, created_before: PrimitiveDateTime, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .count_initial_events_by_constraints( merchant_id, profile_id, created_after, created_before, is_delivered, ) .await } } #[async_trait::async_trait] impl LockerMockUpInterface for KafkaStore { async fn find_locker_by_card_id( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { self.diesel_store.find_locker_by_card_id(card_id).await } async fn insert_locker_mock_up( &self, new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { self.diesel_store.insert_locker_mock_up(new).await } async fn delete_locker_mock_up( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { self.diesel_store.delete_locker_mock_up(card_id).await } } #[async_trait::async_trait] impl MandateInterface for KafkaStore { async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Mandate, errors::StorageError> { self.diesel_store .find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id, storage_scheme) .await } async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Mandate, errors::StorageError> { self.diesel_store .find_mandate_by_merchant_id_connector_mandate_id( merchant_id, connector_mandate_id, storage_scheme, ) .await } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_mandate_by_global_customer_id( &self, id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> { self.diesel_store .find_mandate_by_global_customer_id(id) .await } async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> { self.diesel_store .find_mandate_by_merchant_id_customer_id(merchant_id, customer_id) .await } async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage::MandateUpdate, mandate: storage::Mandate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Mandate, errors::StorageError> { self.diesel_store .update_mandate_by_merchant_id_mandate_id( merchant_id, mandate_id, mandate_update, mandate, storage_scheme, ) .await } async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> { self.diesel_store .find_mandates_by_merchant_id(merchant_id, mandate_constraints) .await } async fn insert_mandate( &self, mandate: storage::MandateNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Mandate, errors::StorageError> { self.diesel_store .insert_mandate(mandate, storage_scheme) .await } } #[async_trait::async_trait] impl PaymentLinkInterface for KafkaStore { async fn find_payment_link_by_payment_link_id( &self, payment_link_id: &str, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { self.diesel_store .find_payment_link_by_payment_link_id(payment_link_id) .await } async fn insert_payment_link( &self, payment_link_object: storage::PaymentLinkNew, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { self.diesel_store .insert_payment_link(payment_link_object) .await } async fn list_payment_link_by_merchant_id( &self, merchant_id: &id_type::MerchantId, payment_link_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> { self.diesel_store .list_payment_link_by_merchant_id(merchant_id, payment_link_constraints) .await } } #[async_trait::async_trait] impl MerchantAccountInterface for KafkaStore { async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store .insert_merchant(state, merchant_account, key_store) .await } async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store .find_merchant_account_by_merchant_id(state, merchant_id, key_store) .await } async fn update_merchant( &self, state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: storage::MerchantAccountUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store .update_merchant(state, this, merchant_account, key_store) .await } async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, merchant_account: storage::MerchantAccountUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { self.diesel_store .update_specific_fields_in_merchant(state, merchant_id, merchant_account, key_store) .await } async fn update_all_merchant_account( &self, merchant_account: storage::MerchantAccountUpdate, ) -> CustomResult<usize, errors::StorageError> { self.diesel_store .update_all_merchant_account(merchant_account) .await } async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError> { self.diesel_store .find_merchant_account_by_publishable_key(state, publishable_key) .await } #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { self.diesel_store .list_merchant_accounts_by_organization_id(state, organization_id) .await } async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_merchant_account_by_merchant_id(merchant_id) .await } #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { self.diesel_store .list_multiple_merchant_accounts(state, merchant_ids) .await } #[cfg(feature = "olap")] async fn list_merchant_and_org_ids( &self, state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult<Vec<(id_type::MerchantId, id_type::OrganizationId)>, errors::StorageError> { self.diesel_store .list_merchant_and_org_ids(state, limit, offset) .await } } #[async_trait::async_trait] impl ConnectorAccessToken for KafkaStore { async fn get_access_token( &self, merchant_id: &id_type::MerchantId, merchant_connector_id: &str, ) -> CustomResult<Option<AccessToken>, errors::StorageError> { self.diesel_store .get_access_token(merchant_id, merchant_connector_id) .await } async fn set_access_token( &self, merchant_id: &id_type::MerchantId, merchant_connector_id: &str, access_token: AccessToken, ) -> CustomResult<(), errors::StorageError> { self.diesel_store .set_access_token(merchant_id, merchant_connector_id, access_token) .await } } #[async_trait::async_trait] impl FileMetadataInterface for KafkaStore { async fn insert_file_metadata( &self, file: storage::FileMetadataNew, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { self.diesel_store.insert_file_metadata(file).await } async fn find_file_metadata_by_merchant_id_file_id( &self, merchant_id: &id_type::MerchantId, file_id: &str, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { self.diesel_store .find_file_metadata_by_merchant_id_file_id(merchant_id, file_id) .await } async fn delete_file_metadata_by_merchant_id_file_id( &self, merchant_id: &id_type::MerchantId, file_id: &str, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_file_metadata_by_merchant_id_file_id(merchant_id, file_id) .await } async fn update_file_metadata( &self, this: storage::FileMetadata, file_metadata: storage::FileMetadataUpdate, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { self.diesel_store .update_file_metadata(this, file_metadata) .await } } #[async_trait::async_trait] impl MerchantConnectorAccountInterface for KafkaStore { async fn update_multiple_merchant_connector_accounts( &self, merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), errors::StorageError> { self.diesel_store .update_multiple_merchant_connector_accounts(merchant_connector_accounts) .await } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, connector: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_connector_label( state, merchant_id, connector, key_store, ) .await } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_connector_name( state, merchant_id, connector_name, key_store, ) .await } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_profile_id_connector_name( state, profile_id, connector_name, key_store, ) .await } #[cfg(all(feature = "oltp", feature = "v2"))] async fn list_enabled_connector_accounts_by_profile_id( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, key_store: &domain::MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { self.list_enabled_connector_accounts_by_profile_id( state, profile_id, key_store, connector_type, ) .await } async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .insert_merchant_connector_account(state, t, key_store) .await } #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( state, merchant_id, merchant_connector_id, key_store, ) .await } #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_id(state, id, key_store) .await } async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, get_disabled: bool, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, errors::StorageError> { self.diesel_store .find_merchant_connector_account_by_merchant_id_and_disabled_list( state, merchant_id, get_disabled, key_store, ) .await } #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &id_type::ProfileId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { self.diesel_store .list_connector_account_by_profile_id(state, profile_id, key_store) .await } async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { self.diesel_store .update_merchant_connector_account(state, this, merchant_connector_account, key_store) .await } #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &id_type::MerchantId, merchant_connector_id: &id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_merchant_connector_account_by_merchant_id_merchant_connector_id( merchant_id, merchant_connector_id, ) .await } #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_merchant_connector_account_by_id(id) .await } } #[async_trait::async_trait] impl QueueInterface for KafkaStore { async fn fetch_consumer_tasks( &self, stream_name: &str, group_name: &str, consumer_name: &str, ) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError> { self.diesel_store .fetch_consumer_tasks(stream_name, group_name, consumer_name) .await } async fn consumer_group_create( &self, stream: &str, group: &str, id: &RedisEntryId, ) -> CustomResult<(), RedisError> { self.diesel_store .consumer_group_create(stream, group, id) .await } async fn acquire_pt_lock( &self, tag: &str, lock_key: &str, lock_val: &str, ttl: i64, ) -> CustomResult<bool, RedisError> { self.diesel_store .acquire_pt_lock(tag, lock_key, lock_val, ttl) .await } async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> CustomResult<bool, RedisError> { self.diesel_store.release_pt_lock(tag, lock_key).await } async fn stream_append_entry( &self, stream: &str, entry_id: &RedisEntryId, fields: Vec<(&str, String)>, ) -> CustomResult<(), RedisError> { self.diesel_store .stream_append_entry(stream, entry_id, fields) .await } async fn get_key(&self, key: &str) -> CustomResult<Vec<u8>, RedisError> { self.diesel_store.get_key(key).await } } #[async_trait::async_trait] impl PaymentAttemptInterface for KafkaStore { type Error = errors::StorageError; #[cfg(feature = "v1")] async fn insert_payment_attempt( &self, payment_attempt: storage::PaymentAttemptNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { let attempt = self .diesel_store .insert_payment_attempt(payment_attempt, storage_scheme) .await?; if let Err(er) = self .kafka_producer .log_payment_attempt(&attempt, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) } Ok(attempt) } #[cfg(feature = "v2")] async fn insert_payment_attempt( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, payment_attempt: storage::PaymentAttempt, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { let attempt = self .diesel_store .insert_payment_attempt( key_manager_state, merchant_key_store, payment_attempt, storage_scheme, ) .await?; if let Err(er) = self .kafka_producer .log_payment_attempt(&attempt, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) } Ok(attempt) } #[cfg(feature = "v1")] async fn update_payment_attempt_with_attempt_id( &self, this: storage::PaymentAttempt, payment_attempt: storage::PaymentAttemptUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { let attempt = self .diesel_store .update_payment_attempt_with_attempt_id(this.clone(), payment_attempt, storage_scheme) .await?; if let Err(er) = self .kafka_producer .log_payment_attempt(&attempt, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) } Ok(attempt) } #[cfg(feature = "v2")] async fn update_payment_attempt( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, this: storage::PaymentAttempt, payment_attempt: storage::PaymentAttemptUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { let attempt = self .diesel_store .update_payment_attempt( key_manager_state, merchant_key_store, this.clone(), payment_attempt, storage_scheme, ) .await?; if let Err(er) = self .kafka_producer .log_payment_attempt(&attempt, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er) } Ok(attempt) } #[cfg(feature = "v1")] async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( &self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( connector_transaction_id, payment_id, merchant_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_by_merchant_id_connector_txn_id( &self, merchant_id: &id_type::MerchantId, connector_txn_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_merchant_id_connector_txn_id( merchant_id, connector_txn_id, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_attempt_by_profile_id_connector_transaction_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &id_type::ProfileId, connector_transaction_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_profile_id_connector_transaction_id( key_manager_state, merchant_key_store, profile_id, connector_transaction_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, attempt_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_payment_id_merchant_id_attempt_id( payment_id, merchant_id, attempt_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_by_attempt_id_merchant_id( &self, attempt_id: &str, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_attempt_id_merchant_id(attempt_id, merchant_id, storage_scheme) .await } #[cfg(feature = "v2")] async fn find_payment_attempt_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, attempt_id: &id_type::GlobalAttemptId, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_id( key_manager_state, merchant_key_store, attempt_id, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_attempts_by_payment_intent_id( &self, key_manager_state: &KeyManagerState, payment_id: &id_type::GlobalPaymentId, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<storage::PaymentAttempt>, errors::StorageError> { self.diesel_store .find_payment_attempts_by_payment_intent_id( key_manager_state, payment_id, merchant_key_store, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id( payment_id, merchant_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id( payment_id, merchant_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_payment_attempt_by_preprocessing_id_merchant_id( &self, preprocessing_id: &str, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentAttempt, errors::StorageError> { self.diesel_store .find_payment_attempt_by_preprocessing_id_merchant_id( preprocessing_id, merchant_id, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn get_filters_for_payments( &self, pi: &[hyperswitch_domain_models::payments::PaymentIntent], merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult< hyperswitch_domain_models::payments::payment_attempt::PaymentListFilters, errors::StorageError, > { self.diesel_store .get_filters_for_payments(pi, merchant_id, storage_scheme) .await } #[cfg(feature = "v1")] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &id_type::MerchantId, active_attempt_ids: &[String], connector: Option<Vec<api_models::enums::Connector>>, payment_method: Option<Vec<common_enums::PaymentMethod>>, payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, card_network: Option<Vec<common_enums::CardNetwork>>, card_discovery: Option<Vec<common_enums::CardDiscovery>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_total_count_of_filtered_payment_attempts( merchant_id, active_attempt_ids, connector, payment_method, payment_method_type, authentication_type, merchant_connector_id, card_network, card_discovery, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn get_total_count_of_filtered_payment_attempts( &self, merchant_id: &id_type::MerchantId, active_attempt_ids: &[String], connector: Option<api_models::enums::Connector>, payment_method_type: Option<common_enums::PaymentMethod>, payment_method_subtype: Option<common_enums::PaymentMethodType>, authentication_type: Option<common_enums::AuthenticationType>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, card_network: Option<common_enums::CardNetwork>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_total_count_of_filtered_payment_attempts( merchant_id, active_attempt_ids, connector, payment_method_type, payment_method_subtype, authentication_type, merchant_connector_id, card_network, storage_scheme, ) .await } #[cfg(feature = "v1")] async fn find_attempts_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::PaymentAttempt>, errors::StorageError> { self.diesel_store .find_attempts_by_merchant_id_payment_id(merchant_id, payment_id, storage_scheme) .await } } #[async_trait::async_trait] impl PaymentIntentInterface for KafkaStore { type Error = errors::StorageError; async fn update_payment_intent( &self, state: &KeyManagerState, this: storage::PaymentIntent, payment_intent: storage::PaymentIntentUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentIntent, errors::StorageError> { let intent = self .diesel_store .update_payment_intent( state, this.clone(), payment_intent, key_store, storage_scheme, ) .await?; if let Err(er) = self .kafka_producer .log_payment_intent(&intent, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er); }; Ok(intent) } async fn insert_payment_intent( &self, state: &KeyManagerState, new: storage::PaymentIntent, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentIntent, errors::StorageError> { logger::debug!("Inserting PaymentIntent Via KafkaStore"); let intent = self .diesel_store .insert_payment_intent(state, new, key_store, storage_scheme) .await?; if let Err(er) = self .kafka_producer .log_payment_intent(&intent, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er); }; Ok(intent) } #[cfg(feature = "v1")] async fn find_payment_intent_by_payment_id_merchant_id( &self, state: &KeyManagerState, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentIntent, errors::StorageError> { self.diesel_store .find_payment_intent_by_payment_id_merchant_id( state, payment_id, merchant_id, key_store, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_intent_by_id( &self, state: &KeyManagerState, payment_id: &id_type::GlobalPaymentId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PaymentIntent, errors::StorageError> { self.diesel_store .find_payment_intent_by_id(state, payment_id, key_store, storage_scheme) .await } #[cfg(all(feature = "olap", feature = "v1"))] async fn filter_payment_intent_by_constraints( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::PaymentIntent>, errors::StorageError> { self.diesel_store .filter_payment_intent_by_constraints( state, merchant_id, filters, key_store, storage_scheme, ) .await } #[cfg(all(feature = "olap", feature = "v1"))] async fn filter_payment_intents_by_time_range_constraints( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, time_range: &common_utils::types::TimeRange, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::PaymentIntent>, errors::StorageError> { self.diesel_store .filter_payment_intents_by_time_range_constraints( state, merchant_id, time_range, key_store, storage_scheme, ) .await } #[cfg(feature = "olap")] async fn get_intent_status_with_count( &self, merchant_id: &id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::StorageError> { self.diesel_store .get_intent_status_with_count(merchant_id, profile_id_list, time_range) .await } #[cfg(all(feature = "olap", feature = "v1"))] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult< Vec<( hyperswitch_domain_models::payments::PaymentIntent, hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt, )>, errors::StorageError, > { self.diesel_store .get_filtered_payment_intents_attempt( state, merchant_id, constraints, key_store, storage_scheme, ) .await } #[cfg(all(feature = "olap", feature = "v2"))] async fn get_filtered_payment_intents_attempt( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult< Vec<( hyperswitch_domain_models::payments::PaymentIntent, Option<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>, )>, errors::StorageError, > { self.diesel_store .get_filtered_payment_intents_attempt( state, merchant_id, constraints, key_store, storage_scheme, ) .await } #[cfg(all(feature = "olap", feature = "v1"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<String>, errors::StorageError> { self.diesel_store .get_filtered_active_attempt_ids_for_total_count( merchant_id, constraints, storage_scheme, ) .await } #[cfg(feature = "v2")] async fn find_payment_intent_by_merchant_reference_id_profile_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::PaymentReferenceId, profile_id: &id_type::ProfileId, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: &MerchantStorageScheme, ) -> error_stack::Result<hyperswitch_domain_models::payments::PaymentIntent, errors::StorageError> { self.diesel_store .find_payment_intent_by_merchant_reference_id_profile_id( state, merchant_reference_id, profile_id, merchant_key_store, storage_scheme, ) .await } #[cfg(all(feature = "olap", feature = "v2"))] async fn get_filtered_active_attempt_ids_for_total_count( &self, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<Option<String>>, errors::StorageError> { self.diesel_store .get_filtered_active_attempt_ids_for_total_count( merchant_id, constraints, storage_scheme, ) .await } } #[async_trait::async_trait] impl PaymentMethodInterface for KafkaStore { type Error = errors::StorageError; #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, payment_method_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .find_payment_method(state, key_store, payment_method_id, storage_scheme) .await } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn find_payment_method( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, payment_method_id: &id_type::GlobalPaymentMethodId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .find_payment_method(state, key_store, payment_method_id, storage_scheme) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn find_payment_method_by_customer_id_merchant_id_list( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, limit: Option<i64>, ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> { self.diesel_store .find_payment_method_by_customer_id_merchant_id_list( state, key_store, customer_id, merchant_id, limit, ) .await } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_payment_method_list_by_global_customer_id( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, id: &id_type::GlobalCustomerId, limit: Option<i64>, ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> { self.diesel_store .find_payment_method_list_by_global_customer_id(state, key_store, id, limit) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn find_payment_method_by_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> { self.diesel_store .find_payment_method_by_customer_id_merchant_id_status( state, key_store, customer_id, merchant_id, status, limit, storage_scheme, ) .await } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_payment_method_by_global_customer_id_merchant_id_status( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, customer_id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, limit: Option<i64>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<domain::PaymentMethod>, errors::StorageError> { self.diesel_store .find_payment_method_by_global_customer_id_merchant_id_status( state, key_store, customer_id, merchant_id, status, limit, storage_scheme, ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn get_payment_method_count_by_customer_id_merchant_id_status( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_payment_method_count_by_customer_id_merchant_id_status( customer_id, merchant_id, status, ) .await } async fn get_payment_method_count_by_merchant_id_status( &self, merchant_id: &id_type::MerchantId, status: common_enums::PaymentMethodStatus, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_payment_method_count_by_merchant_id_status(merchant_id, status) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn find_payment_method_by_locker_id( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, locker_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .find_payment_method_by_locker_id(state, key_store, locker_id, storage_scheme) .await } async fn insert_payment_method( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, m: domain::PaymentMethod, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .insert_payment_method(state, key_store, m, storage_scheme) .await } async fn update_payment_method( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, payment_method: domain::PaymentMethod, payment_method_update: storage::PaymentMethodUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .update_payment_method( state, key_store, payment_method, payment_method_update, storage_scheme, ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] async fn delete_payment_method_by_merchant_id_payment_method_id( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, payment_method_id: &str, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .delete_payment_method_by_merchant_id_payment_method_id( state, key_store, merchant_id, payment_method_id, ) .await } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn delete_payment_method( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, payment_method: domain::PaymentMethod, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .delete_payment_method(state, key_store, payment_method) .await } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] async fn find_payment_method_by_fingerprint_id( &self, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, fingerprint_id: &str, ) -> CustomResult<domain::PaymentMethod, errors::StorageError> { self.diesel_store .find_payment_method_by_fingerprint_id(state, key_store, fingerprint_id) .await } } #[cfg(not(feature = "payouts"))] impl PayoutAttemptInterface for KafkaStore {} #[cfg(feature = "payouts")] #[async_trait::async_trait] impl PayoutAttemptInterface for KafkaStore { type Error = errors::StorageError; async fn find_payout_attempt_by_merchant_id_payout_attempt_id( &self, merchant_id: &id_type::MerchantId, payout_attempt_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> { self.diesel_store .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, payout_attempt_id, storage_scheme, ) .await } async fn find_payout_attempt_by_merchant_id_connector_payout_id( &self, merchant_id: &id_type::MerchantId, connector_payout_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> { self.diesel_store .find_payout_attempt_by_merchant_id_connector_payout_id( merchant_id, connector_payout_id, storage_scheme, ) .await } async fn update_payout_attempt( &self, this: &storage::PayoutAttempt, payout_attempt_update: storage::PayoutAttemptUpdate, payouts: &storage::Payouts, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> { let updated_payout_attempt = self .diesel_store .update_payout_attempt(this, payout_attempt_update, payouts, storage_scheme) .await?; if let Err(err) = self .kafka_producer .log_payout( &KafkaPayout::from_storage(payouts, &updated_payout_attempt), Some(KafkaPayout::from_storage(payouts, this)), self.tenant_id.clone(), ) .await { logger::error!(message="Failed to update analytics entry for Payouts {payouts:?}\n{updated_payout_attempt:?}", error_message=?err); }; Ok(updated_payout_attempt) } async fn insert_payout_attempt( &self, payout_attempt: storage::PayoutAttemptNew, payouts: &storage::Payouts, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::PayoutAttempt, errors::StorageError> { let payout_attempt_new = self .diesel_store .insert_payout_attempt(payout_attempt, payouts, storage_scheme) .await?; if let Err(err) = self .kafka_producer .log_payout( &KafkaPayout::from_storage(payouts, &payout_attempt_new), None, self.tenant_id.clone(), ) .await { logger::error!(message="Failed to add analytics entry for Payouts {payouts:?}\n{payout_attempt_new:?}", error_message=?err); }; Ok(payout_attempt_new) } async fn get_filters_for_payouts( &self, payouts: &[hyperswitch_domain_models::payouts::payouts::Payouts], merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult< hyperswitch_domain_models::payouts::payout_attempt::PayoutListFilters, errors::StorageError, > { self.diesel_store .get_filters_for_payouts(payouts, merchant_id, storage_scheme) .await } } #[cfg(not(feature = "payouts"))] impl PayoutsInterface for KafkaStore {} #[cfg(feature = "payouts")] #[async_trait::async_trait] impl PayoutsInterface for KafkaStore { type Error = errors::StorageError; async fn find_payout_by_merchant_id_payout_id( &self, merchant_id: &id_type::MerchantId, payout_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Payouts, errors::StorageError> { self.diesel_store .find_payout_by_merchant_id_payout_id(merchant_id, payout_id, storage_scheme) .await } async fn update_payout( &self, this: &storage::Payouts, payout_update: storage::PayoutsUpdate, payout_attempt: &storage::PayoutAttempt, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Payouts, errors::StorageError> { let payout = self .diesel_store .update_payout(this, payout_update, payout_attempt, storage_scheme) .await?; if let Err(err) = self .kafka_producer .log_payout( &KafkaPayout::from_storage(&payout, payout_attempt), Some(KafkaPayout::from_storage(this, payout_attempt)), self.tenant_id.clone(), ) .await { logger::error!(message="Failed to update analytics entry for Payouts {payout:?}\n{payout_attempt:?}", error_message=?err); }; Ok(payout) } async fn insert_payout( &self, payout: storage::PayoutsNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Payouts, errors::StorageError> { self.diesel_store .insert_payout(payout, storage_scheme) .await } async fn find_optional_payout_by_merchant_id_payout_id( &self, merchant_id: &id_type::MerchantId, payout_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<storage::Payouts>, errors::StorageError> { self.diesel_store .find_optional_payout_by_merchant_id_payout_id(merchant_id, payout_id, storage_scheme) .await } #[cfg(feature = "olap")] async fn filter_payouts_by_constraints( &self, merchant_id: &id_type::MerchantId, filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::Payouts>, errors::StorageError> { self.diesel_store .filter_payouts_by_constraints(merchant_id, filters, storage_scheme) .await } #[cfg(feature = "olap")] async fn filter_payouts_and_attempts( &self, merchant_id: &id_type::MerchantId, filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints, storage_scheme: MerchantStorageScheme, ) -> CustomResult< Vec<( storage::Payouts, storage::PayoutAttempt, Option<diesel_models::Customer>, Option<diesel_models::Address>, )>, errors::StorageError, > { self.diesel_store .filter_payouts_and_attempts(merchant_id, filters, storage_scheme) .await } #[cfg(feature = "olap")] async fn filter_payouts_by_time_range_constraints( &self, merchant_id: &id_type::MerchantId, time_range: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::Payouts>, errors::StorageError> { self.diesel_store .filter_payouts_by_time_range_constraints(merchant_id, time_range, storage_scheme) .await } #[cfg(feature = "olap")] async fn get_total_count_of_filtered_payouts( &self, merchant_id: &id_type::MerchantId, active_payout_ids: &[String], connector: Option<Vec<api_models::enums::PayoutConnectors>>, currency: Option<Vec<enums::Currency>>, status: Option<Vec<enums::PayoutStatus>>, payout_method: Option<Vec<enums::PayoutType>>, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_total_count_of_filtered_payouts( merchant_id, active_payout_ids, connector, currency, status, payout_method, ) .await } #[cfg(feature = "olap")] async fn filter_active_payout_ids_by_constraints( &self, merchant_id: &id_type::MerchantId, constraints: &hyperswitch_domain_models::payouts::PayoutFetchConstraints, ) -> CustomResult<Vec<String>, errors::StorageError> { self.diesel_store .filter_active_payout_ids_by_constraints(merchant_id, constraints) .await } } #[async_trait::async_trait] impl ProcessTrackerInterface for KafkaStore { async fn reinitialize_limbo_processes( &self, ids: Vec<String>, schedule_time: PrimitiveDateTime, ) -> CustomResult<usize, errors::StorageError> { self.diesel_store .reinitialize_limbo_processes(ids, schedule_time) .await } async fn find_process_by_id( &self, id: &str, ) -> CustomResult<Option<storage::ProcessTracker>, errors::StorageError> { self.diesel_store.find_process_by_id(id).await } async fn update_process( &self, this: storage::ProcessTracker, process: storage::ProcessTrackerUpdate, ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { self.diesel_store.update_process(this, process).await } async fn process_tracker_update_process_status_by_ids( &self, task_ids: Vec<String>, task_update: storage::ProcessTrackerUpdate, ) -> CustomResult<usize, errors::StorageError> { self.diesel_store .process_tracker_update_process_status_by_ids(task_ids, task_update) .await } async fn insert_process( &self, new: storage::ProcessTrackerNew, ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { self.diesel_store.insert_process(new).await } async fn reset_process( &self, this: storage::ProcessTracker, schedule_time: PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError> { self.diesel_store.reset_process(this, schedule_time).await } async fn retry_process( &self, this: storage::ProcessTracker, schedule_time: PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError> { self.diesel_store.retry_process(this, schedule_time).await } async fn finish_process_with_business_status( &self, this: storage::ProcessTracker, business_status: &'static str, ) -> CustomResult<(), errors::StorageError> { self.diesel_store .finish_process_with_business_status(this, business_status) .await } async fn find_processes_by_time_status( &self, time_lower_limit: PrimitiveDateTime, time_upper_limit: PrimitiveDateTime, status: ProcessTrackerStatus, limit: Option<i64>, ) -> CustomResult<Vec<storage::ProcessTracker>, errors::StorageError> { self.diesel_store .find_processes_by_time_status(time_lower_limit, time_upper_limit, status, limit) .await } } #[async_trait::async_trait] impl CaptureInterface for KafkaStore { async fn insert_capture( &self, capture: storage::CaptureNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Capture, errors::StorageError> { self.diesel_store .insert_capture(capture, storage_scheme) .await } async fn update_capture_with_capture_id( &self, this: storage::Capture, capture: storage::CaptureUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Capture, errors::StorageError> { self.diesel_store .update_capture_with_capture_id(this, capture, storage_scheme) .await } async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, authorized_attempt_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::Capture>, errors::StorageError> { self.diesel_store .find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( merchant_id, payment_id, authorized_attempt_id, storage_scheme, ) .await } } #[async_trait::async_trait] impl RefundInterface for KafkaStore { #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Refund, errors::StorageError> { self.diesel_store .find_refund_by_internal_reference_id_merchant_id( internal_reference_id, merchant_id, storage_scheme, ) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &id_type::PaymentId, merchant_id: &id_type::MerchantId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::Refund>, errors::StorageError> { self.diesel_store .find_refund_by_payment_id_merchant_id(payment_id, merchant_id, storage_scheme) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &id_type::MerchantId, refund_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Refund, errors::StorageError> { self.diesel_store .find_refund_by_merchant_id_refund_id(merchant_id, refund_id, storage_scheme) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &id_type::MerchantId, connector_refund_id: &str, connector: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Refund, errors::StorageError> { self.diesel_store .find_refund_by_merchant_id_connector_refund_id_connector( merchant_id, connector_refund_id, connector, storage_scheme, ) .await } async fn update_refund( &self, this: storage::Refund, refund: storage::RefundUpdate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Refund, errors::StorageError> { let refund = self .diesel_store .update_refund(this.clone(), refund, storage_scheme) .await?; if let Err(er) = self .kafka_producer .log_refund(&refund, Some(this), self.tenant_id.clone()) .await { logger::error!(message="Failed to insert analytics event for Refund Update {refund?}", error_message=?er); } Ok(refund) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &id_type::MerchantId, connector_transaction_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::Refund>, errors::StorageError> { self.diesel_store .find_refund_by_merchant_id_connector_transaction_id( merchant_id, connector_transaction_id, storage_scheme, ) .await } #[cfg(all(feature = "v2", feature = "refunds_v2"))] async fn find_refund_by_id( &self, id: &id_type::GlobalRefundId, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Refund, errors::StorageError> { self.diesel_store .find_refund_by_id(id, storage_scheme) .await } async fn insert_refund( &self, new: storage::RefundNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage::Refund, errors::StorageError> { let refund = self.diesel_store.insert_refund(new, storage_scheme).await?; if let Err(er) = self .kafka_producer .log_refund(&refund, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to insert analytics event for Refund Create {refund?}", error_message=?er); } Ok(refund) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] async fn filter_refund_by_constraints( &self, merchant_id: &id_type::MerchantId, refund_details: &refunds::RefundListConstraints, storage_scheme: MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::Refund>, errors::StorageError> { self.diesel_store .filter_refund_by_constraints( merchant_id, refund_details, storage_scheme, limit, offset, ) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] async fn filter_refund_by_meta_constraints( &self, merchant_id: &id_type::MerchantId, refund_details: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { self.diesel_store .filter_refund_by_meta_constraints(merchant_id, refund_details, storage_scheme) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] async fn get_refund_status_with_count( &self, merchant_id: &id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { self.diesel_store .get_refund_status_with_count(merchant_id, profile_id_list, constraints, storage_scheme) .await } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] async fn get_total_count_of_refunds( &self, merchant_id: &id_type::MerchantId, refund_details: &refunds::RefundListConstraints, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { self.diesel_store .get_total_count_of_refunds(merchant_id, refund_details, storage_scheme) .await } } #[async_trait::async_trait] impl MerchantKeyStoreInterface for KafkaStore { async fn insert_merchant_key_store( &self, state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { self.diesel_store .insert_merchant_key_store(state, merchant_key_store, key) .await } async fn get_merchant_key_store_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { self.diesel_store .get_merchant_key_store_by_merchant_id(state, merchant_id, key) .await } async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_merchant_key_store_by_merchant_id(merchant_id) .await } #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, state: &KeyManagerState, merchant_ids: Vec<id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { self.diesel_store .list_multiple_key_stores(state, merchant_ids, key) .await } async fn get_all_key_stores( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { self.diesel_store .get_all_key_stores(state, key, from, to) .await } } #[async_trait::async_trait] impl ProfileInterface for KafkaStore { async fn insert_business_profile( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, business_profile: domain::Profile, ) -> CustomResult<domain::Profile, errors::StorageError> { self.diesel_store .insert_business_profile(key_manager_state, merchant_key_store, business_profile) .await } async fn find_business_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &id_type::ProfileId, ) -> CustomResult<domain::Profile, errors::StorageError> { self.diesel_store .find_business_profile_by_profile_id(key_manager_state, merchant_key_store, profile_id) .await } async fn find_business_profile_by_merchant_id_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, ) -> CustomResult<domain::Profile, errors::StorageError> { self.diesel_store .find_business_profile_by_merchant_id_profile_id( key_manager_state, merchant_key_store, merchant_id, profile_id, ) .await } async fn update_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: domain::Profile, business_profile_update: domain::ProfileUpdate, ) -> CustomResult<domain::Profile, errors::StorageError> { self.diesel_store .update_profile_by_profile_id( key_manager_state, merchant_key_store, current_state, business_profile_update, ) .await } async fn delete_profile_by_profile_id_merchant_id( &self, profile_id: &id_type::ProfileId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_profile_by_profile_id_merchant_id(profile_id, merchant_id) .await } async fn list_profile_by_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, merchant_id: &id_type::MerchantId, ) -> CustomResult<Vec<domain::Profile>, errors::StorageError> { self.diesel_store .list_profile_by_merchant_id(key_manager_state, merchant_key_store, merchant_id) .await } async fn find_business_profile_by_profile_name_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_name: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<domain::Profile, errors::StorageError> { self.diesel_store .find_business_profile_by_profile_name_merchant_id( key_manager_state, merchant_key_store, profile_name, merchant_id, ) .await } } #[async_trait::async_trait] impl ReverseLookupInterface for KafkaStore { async fn insert_reverse_lookup( &self, new: ReverseLookupNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { self.diesel_store .insert_reverse_lookup(new, storage_scheme) .await } async fn get_lookup_by_lookup_id( &self, id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { self.diesel_store .get_lookup_by_lookup_id(id, storage_scheme) .await } } #[async_trait::async_trait] impl RoutingAlgorithmInterface for KafkaStore { async fn insert_routing_algorithm( &self, routing_algorithm: storage::RoutingAlgorithm, ) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> { self.diesel_store .insert_routing_algorithm(routing_algorithm) .await } async fn find_routing_algorithm_by_profile_id_algorithm_id( &self, profile_id: &id_type::ProfileId, algorithm_id: &id_type::RoutingId, ) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> { self.diesel_store .find_routing_algorithm_by_profile_id_algorithm_id(profile_id, algorithm_id) .await } async fn find_routing_algorithm_by_algorithm_id_merchant_id( &self, algorithm_id: &id_type::RoutingId, merchant_id: &id_type::MerchantId, ) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> { self.diesel_store .find_routing_algorithm_by_algorithm_id_merchant_id(algorithm_id, merchant_id) .await } async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id( &self, algorithm_id: &id_type::RoutingId, profile_id: &id_type::ProfileId, ) -> CustomResult<storage::RoutingProfileMetadata, errors::StorageError> { self.diesel_store .find_routing_algorithm_metadata_by_algorithm_id_profile_id(algorithm_id, profile_id) .await } async fn list_routing_algorithm_metadata_by_profile_id( &self, profile_id: &id_type::ProfileId, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::RoutingProfileMetadata>, errors::StorageError> { self.diesel_store .list_routing_algorithm_metadata_by_profile_id(profile_id, limit, offset) .await } async fn list_routing_algorithm_metadata_by_merchant_id( &self, merchant_id: &id_type::MerchantId, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::RoutingProfileMetadata>, errors::StorageError> { self.diesel_store .list_routing_algorithm_metadata_by_merchant_id(merchant_id, limit, offset) .await } async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type( &self, merchant_id: &id_type::MerchantId, transaction_type: &enums::TransactionType, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::RoutingProfileMetadata>, errors::StorageError> { self.diesel_store .list_routing_algorithm_metadata_by_merchant_id_transaction_type( merchant_id, transaction_type, limit, offset, ) .await } } #[async_trait::async_trait] impl GsmInterface for KafkaStore { async fn add_gsm_rule( &self, rule: storage::GatewayStatusMappingNew, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { self.diesel_store.add_gsm_rule(rule).await } async fn find_gsm_decision( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<String, errors::StorageError> { self.diesel_store .find_gsm_decision(connector, flow, sub_flow, code, message) .await } async fn find_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { self.diesel_store .find_gsm_rule(connector, flow, sub_flow, code, message) .await } async fn update_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, data: storage::GatewayStatusMappingUpdate, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { self.diesel_store .update_gsm_rule(connector, flow, sub_flow, code, message, data) .await } async fn delete_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_gsm_rule(connector, flow, sub_flow, code, message) .await } } #[async_trait::async_trait] impl UnifiedTranslationsInterface for KafkaStore { async fn add_unfied_translation( &self, translation: storage::UnifiedTranslationsNew, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> { self.diesel_store.add_unfied_translation(translation).await } async fn find_translation( &self, unified_code: String, unified_message: String, locale: String, ) -> CustomResult<String, errors::StorageError> { self.diesel_store .find_translation(unified_code, unified_message, locale) .await } async fn update_translation( &self, unified_code: String, unified_message: String, locale: String, data: storage::UnifiedTranslationsUpdate, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> { self.diesel_store .update_translation(unified_code, unified_message, locale, data) .await } async fn delete_translation( &self, unified_code: String, unified_message: String, locale: String, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_translation(unified_code, unified_message, locale) .await } } #[async_trait::async_trait] impl StorageInterface for KafkaStore { fn get_scheduler_db(&self) -> Box<dyn SchedulerInterface> { Box::new(self.clone()) } fn get_cache_store(&self) -> Box<(dyn RedisConnInterface + Send + Sync + 'static)> { Box::new(self.clone()) } } impl GlobalStorageInterface for KafkaStore {} impl AccountsStorageInterface for KafkaStore {} impl PaymentMethodsStorageInterface for KafkaStore {} impl CommonStorageInterface for KafkaStore { fn get_storage_interface(&self) -> Box<dyn StorageInterface> { Box::new(self.clone()) } fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface> { Box::new(self.clone()) } fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface> { Box::new(self.clone()) } } #[async_trait::async_trait] impl SchedulerInterface for KafkaStore {} impl MasterKeyInterface for KafkaStore { fn get_master_key(&self) -> &[u8] { self.diesel_store.get_master_key() } } #[async_trait::async_trait] impl UserInterface for KafkaStore { async fn insert_user( &self, user_data: storage::UserNew, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store.insert_user(user_data).await } async fn find_user_by_email( &self, user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store.find_user_by_email(user_email).await } async fn find_user_by_id( &self, user_id: &str, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store.find_user_by_id(user_id).await } async fn update_user_by_user_id( &self, user_id: &str, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store .update_user_by_user_id(user_id, user) .await } async fn update_user_by_email( &self, user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store .update_user_by_email(user_email, user) .await } async fn delete_user_by_user_id( &self, user_id: &str, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store.delete_user_by_user_id(user_id).await } async fn find_users_by_user_ids( &self, user_ids: Vec<String>, ) -> CustomResult<Vec<storage::User>, errors::StorageError> { self.diesel_store.find_users_by_user_ids(user_ids).await } } impl RedisConnInterface for KafkaStore { fn get_redis_conn(&self) -> CustomResult<Arc<RedisConnectionPool>, RedisError> { self.diesel_store.get_redis_conn() } } #[async_trait::async_trait] impl UserRoleInterface for KafkaStore { async fn insert_user_role( &self, user_role: storage::UserRoleNew, ) -> CustomResult<user_storage::UserRole, errors::StorageError> { self.diesel_store.insert_user_role(user_role).await } async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { self.diesel_store .find_user_role_by_user_id_and_lineage( user_id, tenant_id, org_id, merchant_id, profile_id, version, ) .await } async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, update: user_storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { self.diesel_store .update_user_role_by_user_id_and_lineage( user_id, tenant_id, org_id, merchant_id, profile_id, update, version, ) .await } async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { self.diesel_store .delete_user_role_by_user_id_and_lineage( user_id, tenant_id, org_id, merchant_id, profile_id, version, ) .await } async fn list_user_roles_by_user_id<'a>( &self, payload: ListUserRolesByUserIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { self.diesel_store.list_user_roles_by_user_id(payload).await } async fn list_user_roles_by_user_id_across_tenants( &self, user_id: &str, limit: Option<u32>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { self.diesel_store .list_user_roles_by_user_id_across_tenants(user_id, limit) .await } async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { self.diesel_store.list_user_roles_by_org_id(payload).await } } #[async_trait::async_trait] impl DashboardMetadataInterface for KafkaStore { async fn insert_metadata( &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { self.diesel_store.insert_metadata(metadata).await } async fn update_metadata( &self, user_id: Option<String>, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_key: enums::DashboardMetadata, dashboard_metadata_update: storage::DashboardMetadataUpdate, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { self.diesel_store .update_metadata( user_id, merchant_id, org_id, data_key, dashboard_metadata_update, ) .await } async fn find_user_scoped_dashboard_metadata( &self, user_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { self.diesel_store .find_user_scoped_dashboard_metadata(user_id, merchant_id, org_id, data_keys) .await } async fn find_merchant_scoped_dashboard_metadata( &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { self.diesel_store .find_merchant_scoped_dashboard_metadata(merchant_id, org_id, data_keys) .await } async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { self.diesel_store .delete_all_user_scoped_dashboard_metadata_by_merchant_id(user_id, merchant_id) .await } async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &self, user_id: &str, merchant_id: &id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { self.diesel_store .delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( user_id, merchant_id, data_key, ) .await } } #[async_trait::async_trait] impl BatchSampleDataInterface for KafkaStore { #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, state: &KeyManagerState, batch: Vec<hyperswitch_domain_models::payments::PaymentIntent>, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, ) -> CustomResult< Vec<hyperswitch_domain_models::payments::PaymentIntent>, storage_impl::errors::StorageError, > { let payment_intents_list = self .diesel_store .insert_payment_intents_batch_for_sample_data(state, batch, key_store) .await?; for payment_intent in payment_intents_list.iter() { let _ = self .kafka_producer .log_payment_intent(payment_intent, None, self.tenant_id.clone()) .await; } Ok(payment_intents_list) } #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, batch: Vec<diesel_models::user::sample_data::PaymentAttemptBatchNew>, ) -> CustomResult< Vec<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>, storage_impl::errors::StorageError, > { let payment_attempts_list = self .diesel_store .insert_payment_attempts_batch_for_sample_data(batch) .await?; for payment_attempt in payment_attempts_list.iter() { let _ = self .kafka_producer .log_payment_attempt(payment_attempt, None, self.tenant_id.clone()) .await; } Ok(payment_attempts_list) } #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, batch: Vec<diesel_models::RefundNew>, ) -> CustomResult<Vec<diesel_models::Refund>, storage_impl::errors::StorageError> { let refunds_list = self .diesel_store .insert_refunds_batch_for_sample_data(batch) .await?; for refund in refunds_list.iter() { let _ = self .kafka_producer .log_refund(refund, None, self.tenant_id.clone()) .await; } Ok(refunds_list) } #[cfg(feature = "v1")] async fn insert_disputes_batch_for_sample_data( &self, batch: Vec<diesel_models::DisputeNew>, ) -> CustomResult<Vec<diesel_models::Dispute>, storage_impl::errors::StorageError> { let disputes_list = self .diesel_store .insert_disputes_batch_for_sample_data(batch) .await?; for dispute in disputes_list.iter() { let _ = self .kafka_producer .log_dispute(dispute, None, self.tenant_id.clone()) .await; } Ok(disputes_list) } #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, ) -> CustomResult< Vec<hyperswitch_domain_models::payments::PaymentIntent>, storage_impl::errors::StorageError, > { let payment_intents_list = self .diesel_store .delete_payment_intents_for_sample_data(state, merchant_id, key_store) .await?; for payment_intent in payment_intents_list.iter() { let _ = self .kafka_producer .log_payment_intent_delete(payment_intent, self.tenant_id.clone()) .await; } Ok(payment_intents_list) } #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, merchant_id: &id_type::MerchantId, ) -> CustomResult< Vec<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>, storage_impl::errors::StorageError, > { let payment_attempts_list = self .diesel_store .delete_payment_attempts_for_sample_data(merchant_id) .await?; for payment_attempt in payment_attempts_list.iter() { let _ = self .kafka_producer .log_payment_attempt_delete(payment_attempt, self.tenant_id.clone()) .await; } Ok(payment_attempts_list) } #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, merchant_id: &id_type::MerchantId, ) -> CustomResult<Vec<diesel_models::Refund>, storage_impl::errors::StorageError> { let refunds_list = self .diesel_store .delete_refunds_for_sample_data(merchant_id) .await?; for refund in refunds_list.iter() { let _ = self .kafka_producer .log_refund_delete(refund, self.tenant_id.clone()) .await; } Ok(refunds_list) } #[cfg(feature = "v1")] async fn delete_disputes_for_sample_data( &self, merchant_id: &id_type::MerchantId, ) -> CustomResult<Vec<diesel_models::Dispute>, storage_impl::errors::StorageError> { let disputes_list = self .diesel_store .delete_disputes_for_sample_data(merchant_id) .await?; for dispute in disputes_list.iter() { let _ = self .kafka_producer .log_dispute_delete(dispute, self.tenant_id.clone()) .await; } Ok(disputes_list) } } #[async_trait::async_trait] impl AuthorizationInterface for KafkaStore { async fn insert_authorization( &self, authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError> { self.diesel_store.insert_authorization(authorization).await } async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> { self.diesel_store .find_all_authorizations_by_merchant_id_payment_id(merchant_id, payment_id) .await } async fn update_authorization_by_merchant_id_authorization_id( &self, merchant_id: id_type::MerchantId, authorization_id: String, authorization: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError> { self.diesel_store .update_authorization_by_merchant_id_authorization_id( merchant_id, authorization_id, authorization, ) .await } } #[async_trait::async_trait] impl AuthenticationInterface for KafkaStore { async fn insert_authentication( &self, authentication: storage::AuthenticationNew, ) -> CustomResult<storage::Authentication, errors::StorageError> { let auth = self .diesel_store .insert_authentication(authentication) .await?; if let Err(er) = self .kafka_producer .log_authentication(&auth, None, self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for authentication {auth:?}", error_message=?er) } Ok(auth) } async fn find_authentication_by_merchant_id_authentication_id( &self, merchant_id: &id_type::MerchantId, authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError> { self.diesel_store .find_authentication_by_merchant_id_authentication_id(merchant_id, authentication_id) .await } async fn find_authentication_by_merchant_id_connector_authentication_id( &self, merchant_id: id_type::MerchantId, connector_authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError> { self.diesel_store .find_authentication_by_merchant_id_connector_authentication_id( merchant_id, connector_authentication_id, ) .await } async fn update_authentication_by_merchant_id_authentication_id( &self, previous_state: storage::Authentication, authentication_update: storage::AuthenticationUpdate, ) -> CustomResult<storage::Authentication, errors::StorageError> { let auth = self .diesel_store .update_authentication_by_merchant_id_authentication_id( previous_state.clone(), authentication_update, ) .await?; if let Err(er) = self .kafka_producer .log_authentication(&auth, Some(previous_state.clone()), self.tenant_id.clone()) .await { logger::error!(message="Failed to log analytics event for authentication {auth:?}", error_message=?er) } Ok(auth) } } #[async_trait::async_trait] impl HealthCheckDbInterface for KafkaStore { async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { self.diesel_store.health_check_db().await } } #[async_trait::async_trait] impl RoleInterface for KafkaStore { async fn insert_role( &self, role: storage::RoleNew, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store.insert_role(role).await } async fn find_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store.find_role_by_role_id(role_id).await } async fn find_role_by_role_id_in_lineage( &self, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store .find_role_by_role_id_in_lineage(role_id, merchant_id, org_id, profile_id, tenant_id) .await } async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store .find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id) .await } async fn update_role_by_role_id( &self, role_id: &str, role_update: storage::RoleUpdate, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store .update_role_by_role_id(role_id, role_update) .await } async fn delete_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store.delete_role_by_role_id(role_id).await } //TODO: Remove once generic_list_roles_by_entity_type is stable async fn list_roles_for_org_by_parameters( &self, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<enums::EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { self.diesel_store .list_roles_for_org_by_parameters(tenant_id, org_id, merchant_id, entity_type, limit) .await } async fn generic_list_roles_by_entity_type( &self, payload: diesel_models::role::ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { self.diesel_store .generic_list_roles_by_entity_type(payload, is_lineage_data_required, tenant_id, org_id) .await } } #[async_trait::async_trait] impl GenericLinkInterface for KafkaStore { async fn find_generic_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { self.diesel_store .find_generic_link_by_link_id(link_id) .await } async fn find_pm_collect_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { self.diesel_store .find_pm_collect_link_by_link_id(link_id) .await } async fn find_payout_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { self.diesel_store.find_payout_link_by_link_id(link_id).await } async fn insert_generic_link( &self, generic_link: storage::GenericLinkNew, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { self.diesel_store.insert_generic_link(generic_link).await } async fn insert_pm_collect_link( &self, pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { self.diesel_store .insert_pm_collect_link(pm_collect_link) .await } async fn insert_payout_link( &self, pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { self.diesel_store.insert_payout_link(pm_collect_link).await } async fn update_payout_link( &self, payout_link: storage::PayoutLink, payout_link_update: storage::PayoutLinkUpdate, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { self.diesel_store .update_payout_link(payout_link, payout_link_update) .await } } #[async_trait::async_trait] impl UserKeyStoreInterface for KafkaStore { async fn insert_user_key_store( &self, state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { self.diesel_store .insert_user_key_store(state, user_key_store, key) .await } async fn get_user_key_store_by_user_id( &self, state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { self.diesel_store .get_user_key_store_by_user_id(state, user_id, key) .await } async fn get_all_user_key_store( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { self.diesel_store .get_all_user_key_store(state, key, from, limit) .await } } #[async_trait::async_trait] impl UserAuthenticationMethodInterface for KafkaStore { async fn insert_user_authentication_method( &self, user_authentication_method: storage::UserAuthenticationMethodNew, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { self.diesel_store .insert_user_authentication_method(user_authentication_method) .await } async fn get_user_authentication_method_by_id( &self, id: &str, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { self.diesel_store .get_user_authentication_method_by_id(id) .await } async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { self.diesel_store .list_user_authentication_methods_for_auth_id(auth_id) .await } async fn list_user_authentication_methods_for_owner_id( &self, owner_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { self.diesel_store .list_user_authentication_methods_for_owner_id(owner_id) .await } async fn update_user_authentication_method( &self, id: &str, user_authentication_method_update: storage::UserAuthenticationMethodUpdate, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { self.diesel_store .update_user_authentication_method(id, user_authentication_method_update) .await } async fn list_user_authentication_methods_for_email_domain( &self, email_domain: &str, ) -> CustomResult< Vec<diesel_models::user_authentication_method::UserAuthenticationMethod>, errors::StorageError, > { self.diesel_store .list_user_authentication_methods_for_email_domain(email_domain) .await } } #[async_trait::async_trait] impl ThemeInterface for KafkaStore { async fn insert_theme( &self, theme: storage::theme::ThemeNew, ) -> CustomResult<storage::theme::Theme, errors::StorageError> { self.diesel_store.insert_theme(theme).await } async fn find_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::theme::Theme, errors::StorageError> { self.diesel_store.find_theme_by_theme_id(theme_id).await } async fn find_most_specific_theme_in_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<diesel_models::user::theme::Theme, errors::StorageError> { self.diesel_store .find_most_specific_theme_in_lineage(lineage) .await } async fn find_theme_by_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::theme::Theme, errors::StorageError> { self.diesel_store.find_theme_by_lineage(lineage).await } async fn delete_theme_by_lineage_and_theme_id( &self, theme_id: String, lineage: ThemeLineage, ) -> CustomResult<storage::theme::Theme, errors::StorageError> { self.diesel_store .delete_theme_by_lineage_and_theme_id(theme_id, lineage) .await } } #[async_trait::async_trait] #[cfg(feature = "v2")] impl db::payment_method_session::PaymentMethodsSessionInterface for KafkaStore { async fn insert_payment_methods_session( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, validity: i64, ) -> CustomResult<(), errors::StorageError> { self.diesel_store .insert_payment_methods_session(state, key_store, payment_methods_session, validity) .await } async fn get_payment_methods_session( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &id_type::GlobalPaymentMethodSessionId, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, > { self.diesel_store .get_payment_methods_session(state, key_store, id) .await } async fn update_payment_method_session( &self, state: &KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &id_type::GlobalPaymentMethodSessionId, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum, current_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, > { self.diesel_store .update_payment_method_session( state, key_store, id, payment_methods_session, current_session, ) .await } } #[async_trait::async_trait] #[cfg(feature = "v1")] impl db::payment_method_session::PaymentMethodsSessionInterface for KafkaStore {} #[async_trait::async_trait] impl CallbackMapperInterface for KafkaStore { #[instrument(skip_all)] async fn insert_call_back_mapper( &self, call_back_mapper: domain::CallbackMapper, ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { self.diesel_store .insert_call_back_mapper(call_back_mapper) .await } #[instrument(skip_all)] async fn find_call_back_mapper_by_id( &self, id: &str, ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { self.diesel_store.find_call_back_mapper_by_id(id).await } }
30,709
1,442
hyperswitch
crates/router/src/db/payment_link.rs
.rs
use error_stack::report; use router_env::{instrument, tracing}; use crate::{ connection, core::errors::{self, CustomResult}, db::MockDb, services::Store, types::storage::{self, PaymentLinkDbExt}, }; #[async_trait::async_trait] pub trait PaymentLinkInterface { async fn find_payment_link_by_payment_link_id( &self, payment_link_id: &str, ) -> CustomResult<storage::PaymentLink, errors::StorageError>; async fn insert_payment_link( &self, _payment_link: storage::PaymentLinkNew, ) -> CustomResult<storage::PaymentLink, errors::StorageError>; async fn list_payment_link_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_link_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError>; } #[async_trait::async_trait] impl PaymentLinkInterface for Store { #[instrument(skip_all)] async fn find_payment_link_by_payment_link_id( &self, payment_link_id: &str, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::PaymentLink::find_link_by_payment_link_id(&conn, payment_link_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_payment_link( &self, payment_link_config: storage::PaymentLinkNew, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; payment_link_config .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_payment_link_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_link_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::PaymentLink::filter_by_constraints(&conn, merchant_id, payment_link_constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl PaymentLinkInterface for MockDb { async fn insert_payment_link( &self, _payment_link: storage::PaymentLinkNew, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn find_payment_link_by_payment_link_id( &self, _payment_link_id: &str, ) -> CustomResult<storage::PaymentLink, errors::StorageError> { // TODO: Implement function for `MockDb`x Err(errors::StorageError::MockDbError)? } async fn list_payment_link_by_merchant_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _payment_link_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> { // TODO: Implement function for `MockDb`x Err(errors::StorageError::MockDbError)? } }
773
1,443
hyperswitch
crates/router/src/db/merchant_account.rs
.rs
#[cfg(feature = "olap")] use std::collections::HashMap; use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use diesel_models::MerchantAccountUpdateInternal; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use storage_impl::redis::cache::{self, CacheKind, ACCOUNTS_CACHE}; use super::{MasterKeyInterface, MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, db::merchant_key_store::MerchantKeyStoreInterface, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage, }, }; #[async_trait::async_trait] pub trait MerchantAccountInterface where domain::MerchantAccount: Conversion<DstType = storage::MerchantAccount, NewDstType = storage::MerchantAccountNew>, { async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError>; async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError>; async fn update_all_merchant_account( &self, merchant_account: storage::MerchantAccountUpdate, ) -> CustomResult<usize, errors::StorageError>; async fn update_merchant( &self, state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError>; async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError>; async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError>; #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError>; async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError>; #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError>; #[cfg(feature = "olap")] async fn list_merchant_and_org_ids( &self, state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, errors::StorageError, >; } #[async_trait::async_trait] impl MerchantAccountInterface for Store { #[instrument(skip_all)] async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; merchant_account .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let fetch_func = || async { let conn = connection::pg_accounts_connection_read(self).await?; storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { fetch_func() .await? .convert( state, merchant_key_store.key.get_inner(), merchant_id.to_owned().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, merchant_id.get_string_repr(), fetch_func, &ACCOUNTS_CACHE, ) .await? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } } #[instrument(skip_all)] async fn update_merchant( &self, state: &KeyManagerState, this: domain::MerchantAccount, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; let updated_merchant_account = Conversion::convert(this) .await .change_context(errors::StorageError::EncryptionError)? .update(&conn, merchant_account.into()) .await .map_err(|error| report!(errors::StorageError::from(error)))?; #[cfg(feature = "accounts_cache")] { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; let updated_merchant_account = storage::MerchantAccount::update_with_specific_fields( &conn, merchant_id, merchant_account.into(), ) .await .map_err(|error| report!(errors::StorageError::from(error)))?; #[cfg(feature = "accounts_cache")] { publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?; } updated_merchant_account .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError> { let fetch_by_pub_key_func = || async { let conn = connection::pg_accounts_connection_read(self).await?; storage::MerchantAccount::find_by_publishable_key(&conn, publishable_key) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let merchant_account; #[cfg(not(feature = "accounts_cache"))] { merchant_account = fetch_by_pub_key_func().await?; } #[cfg(feature = "accounts_cache")] { merchant_account = cache::get_or_populate_in_memory( self, publishable_key, fetch_by_pub_key_func, &ACCOUNTS_CACHE, ) .await?; } let key_store = self .get_merchant_key_store_by_merchant_id( state, merchant_account.get_id(), &self.get_master_key().to_vec().into(), ) .await?; let domain_merchant_account = merchant_account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; Ok((domain_merchant_account, key_store)) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { use futures::future::try_join_all; let conn = connection::pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_by_organization_id(&conn, organization_id) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let db_master_key = self.get_master_key().to_vec().into(); let merchant_key_stores = try_join_all(encrypted_merchant_accounts.iter().map(|merchant_account| { self.get_merchant_key_store_by_merchant_id( state, merchant_account.get_id(), &db_master_key, ) })) .await?; let merchant_accounts = try_join_all( encrypted_merchant_accounts .into_iter() .zip(merchant_key_stores.iter()) .map(|(merchant_account, key_store)| async { merchant_account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }), ) .await?; Ok(merchant_accounts) } #[instrument(skip_all)] async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; let is_deleted_func = || async { storage::MerchantAccount::delete_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let is_deleted; #[cfg(not(feature = "accounts_cache"))] { is_deleted = is_deleted_func().await?; } #[cfg(feature = "accounts_cache")] { let merchant_account = storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error)))?; is_deleted = is_deleted_func().await?; publish_and_redact_merchant_account_cache(self, &merchant_account).await?; } Ok(is_deleted) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_multiple_merchant_accounts(&conn, merchant_ids) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let db_master_key = self.get_master_key().to_vec().into(); let merchant_key_stores = self .list_multiple_key_stores( state, encrypted_merchant_accounts .iter() .map(|merchant_account| merchant_account.get_id()) .cloned() .collect(), &db_master_key, ) .await?; let key_stores_by_id: HashMap<_, _> = merchant_key_stores .iter() .map(|key_store| (key_store.merchant_id.to_owned(), key_store)) .collect(); let merchant_accounts = futures::future::try_join_all(encrypted_merchant_accounts.into_iter().map( |merchant_account| async { let key_store = key_stores_by_id.get(merchant_account.get_id()).ok_or( errors::StorageError::ValueNotFound(format!( "merchant_key_store with merchant_id = {:?}", merchant_account.get_id() )), )?; merchant_account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }, )) .await?; Ok(merchant_accounts) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_merchant_and_org_ids( &self, _state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, errors::StorageError, > { let conn = connection::pg_accounts_connection_read(self).await?; let encrypted_merchant_accounts = storage::MerchantAccount::list_all_merchant_accounts(&conn, limit, offset) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let merchant_and_org_ids = encrypted_merchant_accounts .into_iter() .map(|merchant_account| { let merchant_id = merchant_account.get_id().clone(); let org_id = merchant_account.organization_id; (merchant_id, org_id) }) .collect(); Ok(merchant_and_org_ids) } async fn update_all_merchant_account( &self, merchant_account: storage::MerchantAccountUpdate, ) -> CustomResult<usize, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; let db_func = || async { storage::MerchantAccount::update_all_merchant_accounts( &conn, MerchantAccountUpdateInternal::from(merchant_account), ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let total; #[cfg(not(feature = "accounts_cache"))] { let ma = db_func().await?; total = ma.len(); } #[cfg(feature = "accounts_cache")] { let ma = db_func().await?; publish_and_redact_all_merchant_account_cache(self, &ma).await?; total = ma.len(); } Ok(total) } } #[async_trait::async_trait] impl MerchantAccountInterface for MockDb { #[allow(clippy::panic)] async fn insert_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let mut accounts = self.merchant_accounts.lock().await; let account = Conversion::convert(merchant_account) .await .change_context(errors::StorageError::EncryptionError)?; accounts.push(account.clone()); account .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[allow(clippy::panic)] async fn find_merchant_account_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let accounts = self.merchant_accounts.lock().await; accounts .iter() .find(|account| account.get_id() == merchant_id) .cloned() .ok_or(errors::StorageError::ValueNotFound(format!( "Merchant ID: {:?} not found", merchant_id )))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn update_merchant( &self, state: &KeyManagerState, merchant_account: domain::MerchantAccount, merchant_account_update: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let merchant_id = merchant_account.get_id().to_owned(); let mut accounts = self.merchant_accounts.lock().await; accounts .iter_mut() .find(|account| account.get_id() == merchant_account.get_id()) .async_map(|account| async { let update = MerchantAccountUpdateInternal::from(merchant_account_update) .apply_changeset( Conversion::convert(merchant_account) .await .change_context(errors::StorageError::EncryptionError)?, ); *account = update.clone(); update .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "Merchant ID: {:?} not found", merchant_id )) .into(), ) } async fn update_specific_fields_in_merchant( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_account_update: storage::MerchantAccountUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantAccount, errors::StorageError> { let mut accounts = self.merchant_accounts.lock().await; accounts .iter_mut() .find(|account| account.get_id() == merchant_id) .async_map(|account| async { let update = MerchantAccountUpdateInternal::from(merchant_account_update) .apply_changeset(account.clone()); *account = update.clone(); update .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "Merchant ID: {:?} not found", merchant_id )) .into(), ) } async fn find_merchant_account_by_publishable_key( &self, state: &KeyManagerState, publishable_key: &str, ) -> CustomResult<(domain::MerchantAccount, domain::MerchantKeyStore), errors::StorageError> { let accounts = self.merchant_accounts.lock().await; let account = accounts .iter() .find(|account| { account .publishable_key .as_ref() .is_some_and(|key| key == publishable_key) }) .ok_or(errors::StorageError::ValueNotFound(format!( "Publishable Key: {} not found", publishable_key )))?; let key_store = self .get_merchant_key_store_by_merchant_id( state, account.get_id(), &self.get_master_key().to_vec().into(), ) .await?; let merchant_account = account .clone() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; Ok((merchant_account, key_store)) } async fn update_all_merchant_account( &self, merchant_account_update: storage::MerchantAccountUpdate, ) -> CustomResult<usize, errors::StorageError> { let mut accounts = self.merchant_accounts.lock().await; Ok(accounts.iter_mut().fold(0, |acc, account| { let update = MerchantAccountUpdateInternal::from(merchant_account_update.clone()) .apply_changeset(account.clone()); *account = update; acc + 1 })) } async fn delete_merchant_account_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let mut accounts = self.merchant_accounts.lock().await; accounts.retain(|x| x.get_id() != merchant_id); Ok(true) } #[cfg(feature = "olap")] async fn list_merchant_accounts_by_organization_id( &self, state: &KeyManagerState, organization_id: &common_utils::id_type::OrganizationId, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { let accounts = self.merchant_accounts.lock().await; let futures = accounts .iter() .filter(|account| account.organization_id == *organization_id) .map(|account| async { let key_store = self .get_merchant_key_store_by_merchant_id( state, account.get_id(), &self.get_master_key().to_vec().into(), ) .await; match key_store { Ok(key) => account .clone() .convert(state, key.key.get_inner(), key.merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError), Err(err) => Err(err), } }); futures::future::join_all(futures) .await .into_iter() .collect() } #[cfg(feature = "olap")] async fn list_multiple_merchant_accounts( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> { let accounts = self.merchant_accounts.lock().await; let futures = accounts .iter() .filter(|account| merchant_ids.contains(account.get_id())) .map(|account| async { let key_store = self .get_merchant_key_store_by_merchant_id( state, account.get_id(), &self.get_master_key().to_vec().into(), ) .await; match key_store { Ok(key) => account .clone() .convert(state, key.key.get_inner(), key.merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError), Err(err) => Err(err), } }); futures::future::join_all(futures) .await .into_iter() .collect() } #[cfg(feature = "olap")] async fn list_merchant_and_org_ids( &self, _state: &KeyManagerState, limit: u32, offset: Option<u32>, ) -> CustomResult< Vec<( common_utils::id_type::MerchantId, common_utils::id_type::OrganizationId, )>, errors::StorageError, > { let accounts = self.merchant_accounts.lock().await; let limit = limit.try_into().unwrap_or(accounts.len()); let offset = offset.unwrap_or(0).try_into().unwrap_or(0); let merchant_and_org_ids = accounts .iter() .skip(offset) .take(limit) .map(|account| (account.get_id().clone(), account.organization_id.clone())) .collect::<Vec<_>>(); Ok(merchant_and_org_ids) } } #[cfg(feature = "accounts_cache")] async fn publish_and_redact_merchant_account_cache( store: &dyn super::StorageInterface, merchant_account: &storage::MerchantAccount, ) -> CustomResult<(), errors::StorageError> { let publishable_key = merchant_account .publishable_key .as_ref() .map(|publishable_key| CacheKind::Accounts(publishable_key.into())); #[cfg(feature = "v1")] let cgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| { CacheKind::CGraph( format!( "cgraph_{}_{}", merchant_account.get_id().get_string_repr(), profile_id.get_string_repr(), ) .into(), ) }); // TODO: we will not have default profile in v2 #[cfg(feature = "v2")] let cgraph_key = None; let mut cache_keys = vec![CacheKind::Accounts( merchant_account.get_id().get_string_repr().into(), )]; cache_keys.extend(publishable_key.into_iter()); cache_keys.extend(cgraph_key.into_iter()); cache::redact_from_redis_and_publish(store.get_cache_store().as_ref(), cache_keys).await?; Ok(()) } #[cfg(feature = "accounts_cache")] async fn publish_and_redact_all_merchant_account_cache( store: &dyn super::StorageInterface, merchant_accounts: &[storage::MerchantAccount], ) -> CustomResult<(), errors::StorageError> { let merchant_ids = merchant_accounts .iter() .map(|merchant_account| merchant_account.get_id().get_string_repr().to_string()); let publishable_keys = merchant_accounts .iter() .filter_map(|m| m.publishable_key.clone()); let cache_keys: Vec<CacheKind<'_>> = merchant_ids .chain(publishable_keys) .map(|s| CacheKind::Accounts(s.into())) .collect(); cache::redact_from_redis_and_publish(store.get_cache_store().as_ref(), cache_keys).await?; Ok(()) }
5,901
1,444
hyperswitch
crates/router/src/db/refund.rs
.rs
#[cfg(feature = "olap")] use std::collections::{HashMap, HashSet}; #[cfg(feature = "olap")] use common_utils::types::{ConnectorTransactionIdTrait, MinorUnit}; use diesel_models::{errors::DatabaseError, refund::RefundUpdateInternal}; use hyperswitch_domain_models::refunds; use super::MockDb; use crate::{ core::errors::{self, CustomResult}, types::storage::{self as storage_types, enums}, }; #[cfg(feature = "olap")] const MAX_LIMIT: usize = 100; #[async_trait::async_trait] pub trait RefundInterface { #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, refund_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, connector_refund_id: &str, connector: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; async fn update_refund( &self, this: storage_types::Refund, refund: storage_types::RefundUpdate, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError>; #[cfg(all(feature = "v2", feature = "refunds_v2"))] async fn find_refund_by_id( &self, id: &common_utils::id_type::GlobalRefundId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; async fn insert_refund( &self, new: storage_types::RefundNew, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError>; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] async fn filter_refund_by_meta_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &common_utils::types::TimeRange, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError>; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError>; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError>; } #[cfg(not(feature = "kv_store"))] mod storage { use error_stack::report; use router_env::{instrument, tracing}; use super::RefundInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::storage::{self as storage_types, enums}, }; #[async_trait::async_trait] impl RefundInterface for Store { #[instrument(skip_all)] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Refund::find_by_internal_reference_id_merchant_id( &conn, internal_reference_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_refund( &self, new: storage_types::RefundNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Refund::find_by_merchant_id_connector_transaction_id( &conn, merchant_id, connector_transaction_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_refund( &self, this: storage_types::Refund, refund: storage_types::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update(&conn, refund) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, refund_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Refund::find_by_merchant_id_refund_id(&conn, merchant_id, refund_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, connector_refund_id: &str, connector: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Refund::find_by_merchant_id_connector_refund_id_connector( &conn, merchant_id, connector_refund_id, connector, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Refund::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints( &conn, merchant_id, refund_details, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn filter_refund_by_meta_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &api_models::payments::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_meta_constraints( &conn, merchant_id, refund_details, ) .await .map_err(|error|report!(errors::StorageError::from(error))) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &api_models::payments::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id,profile_id_list, time_range) .await .map_err(|error|report!(errors::StorageError::from(error))) } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count( &conn, merchant_id, refund_details, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } } #[cfg(feature = "kv_store")] mod storage { use common_utils::{ ext_traits::Encode, fallback_reverse_lookup_not_found, types::ConnectorTransactionIdTrait, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::refunds; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey, }; use super::RefundInterface; use crate::{ connection, core::errors::{self, utils::RedisErrorExt, CustomResult}, db::reverse_lookup::ReverseLookupInterface, services::Store, types::storage::{self as storage_types, enums, kv}, utils::db_utils, }; #[async_trait::async_trait] impl RefundInterface for Store { #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; storage_types::Refund::find_by_internal_reference_id_merchant_id( &conn, internal_reference_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let lookup_id = format!( "ref_inter_ref_{}_{internal_reference_id}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<storage_types::Refund>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn insert_refund( &self, new: storage_types::RefundNew, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } enums::MerchantStorageScheme::RedisKv => { let merchant_id = new.merchant_id.clone(); let payment_id = new.payment_id.clone(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let key_str = key.to_string(); // TODO: need to add an application generated payment attempt id to distinguish between multiple attempts for the same payment id // Check for database presence as well Maybe use a read replica here ? let created_refund = storage_types::Refund { refund_id: new.refund_id.clone(), merchant_id: new.merchant_id.clone(), attempt_id: new.attempt_id.clone(), internal_reference_id: new.internal_reference_id.clone(), payment_id: new.payment_id.clone(), connector_transaction_id: new.connector_transaction_id.clone(), connector: new.connector.clone(), connector_refund_id: new.connector_refund_id.clone(), external_reference_id: new.external_reference_id.clone(), refund_type: new.refund_type, total_amount: new.total_amount, currency: new.currency, refund_amount: new.refund_amount, refund_status: new.refund_status, sent_to_gateway: new.sent_to_gateway, refund_error_message: None, refund_error_code: None, metadata: new.metadata.clone(), refund_arn: new.refund_arn.clone(), created_at: new.created_at, modified_at: new.created_at, description: new.description.clone(), refund_reason: new.refund_reason.clone(), profile_id: new.profile_id.clone(), updated_by: new.updated_by.clone(), merchant_connector_id: new.merchant_connector_id.clone(), charges: new.charges.clone(), split_refunds: new.split_refunds.clone(), organization_id: new.organization_id.clone(), unified_code: None, unified_message: None, processor_refund_data: new.processor_refund_data.clone(), processor_transaction_data: new.processor_transaction_data.clone(), issuer_error_code: None, issuer_error_message: None, // Below fields are deprecated. Please add any new fields above this line. connector_refund_data: None, connector_transaction_data: None, }; let field = format!( "pa_{}_ref_{}", &created_refund.attempt_id, &created_refund.refund_id ); let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Refund(new)), }, }; let mut reverse_lookups = vec![ storage_types::ReverseLookupNew { sk_id: field.clone(), lookup_id: format!( "ref_ref_id_{}_{}", created_refund.merchant_id.get_string_repr(), created_refund.refund_id ), pk_id: key_str.clone(), source: "refund".to_string(), updated_by: storage_scheme.to_string(), }, // [#492]: A discussion is required on whether this is required? storage_types::ReverseLookupNew { sk_id: field.clone(), lookup_id: format!( "ref_inter_ref_{}_{}", created_refund.merchant_id.get_string_repr(), created_refund.internal_reference_id ), pk_id: key_str.clone(), source: "refund".to_string(), updated_by: storage_scheme.to_string(), }, ]; if let Some(connector_refund_id) = created_refund.to_owned().get_optional_connector_refund_id() { reverse_lookups.push(storage_types::ReverseLookupNew { sk_id: field.clone(), lookup_id: format!( "ref_connector_{}_{}_{}", created_refund.merchant_id.get_string_repr(), connector_refund_id, created_refund.connector ), pk_id: key_str.clone(), source: "refund".to_string(), updated_by: storage_scheme.to_string(), }) }; let rev_look = reverse_lookups .into_iter() .map(|rev| self.insert_reverse_lookup(rev, storage_scheme)); futures::future::try_join_all(rev_look).await?; match Box::pin(kv_wrapper::<storage_types::Refund, _, _>( self, KvOperation::<storage_types::Refund>::HSetNx( &field, &created_refund, redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "refund", key: Some(created_refund.refund_id), } .into()), Ok(HsetnxReply::KeySet) => Ok(created_refund), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } #[cfg(all(feature = "v2", feature = "refunds_v2"))] #[instrument(skip_all)] async fn insert_refund( &self, new: storage_types::RefundNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; storage_types::Refund::find_by_merchant_id_connector_transaction_id( &conn, merchant_id, connector_transaction_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let lookup_id = format!( "pa_conn_trans_{}_{connector_transaction_id}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; let pattern = db_utils::generate_hscan_pattern_for_refund(&lookup.sk_id); Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<storage_types::Refund>::Scan(&pattern), key, )) .await? .try_into_scan() }, database_call, )) .await } } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn update_refund( &self, this: storage_types::Refund, refund: storage_types::RefundUpdate, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let merchant_id = this.merchant_id.clone(); let payment_id = this.payment_id.clone(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let field = format!("pa_{}_ref_{}", &this.attempt_id, &this.refund_id); let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>( self, storage_scheme, Op::Update(key.clone(), &field, Some(&this.updated_by)), )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; this.update(&conn, refund) .await .map_err(|error| report!(errors::StorageError::from(error))) } enums::MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); let updated_refund = refund.clone().apply_changeset(this.clone()); let redis_value = updated_refund .encode_to_string_of_json() .change_context(errors::StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::RefundUpdate(Box::new( kv::RefundUpdateMems { orig: this, update_data: refund, }, ))), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::Hset::<storage_types::Refund>( (&field, redis_value), redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_refund) } } } #[cfg(all(feature = "v2", feature = "refunds_v2"))] #[instrument(skip_all)] async fn update_refund( &self, this: storage_types::Refund, refund: storage_types::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update_with_id(&conn, refund) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, refund_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; storage_types::Refund::find_by_merchant_id_refund_id(&conn, merchant_id, refund_id) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let lookup_id = format!("ref_ref_id_{}_{refund_id}", merchant_id.get_string_repr()); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<storage_types::Refund>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, connector_refund_id: &str, connector: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; storage_types::Refund::find_by_merchant_id_connector_refund_id_connector( &conn, merchant_id, connector_refund_id, connector, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let lookup_id = format!( "ref_connector_{}_{connector_refund_id}_{connector}", merchant_id.get_string_repr() ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<storage_types::Refund>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] #[instrument(skip_all)] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; storage_types::Refund::find_by_payment_id_merchant_id( &conn, payment_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<storage_types::Refund>::Scan("pa_*_ref_*"), key, )) .await? .try_into_scan() }, database_call, )) .await } } } #[cfg(all(feature = "v2", feature = "refunds_v2"))] #[instrument(skip_all)] async fn find_refund_by_id( &self, id: &common_utils::id_type::GlobalRefundId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Refund::find_by_global_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] #[instrument(skip_all)] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints( &conn, merchant_id, refund_details, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] #[instrument(skip_all)] async fn filter_refund_by_meta_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_meta_constraints(&conn, merchant_id, refund_details) .await .map_err(|error|report!(errors::StorageError::from(error))) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] #[instrument(skip_all)] async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id,profile_id_list, constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] #[instrument(skip_all)] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count( &conn, merchant_id, refund_details, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } } #[async_trait::async_trait] impl RefundInterface for MockDb { #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_internal_reference_id_merchant_id( &self, internal_reference_id: &str, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let refunds = self.refunds.lock().await; refunds .iter() .find(|refund| { refund.merchant_id == *merchant_id && refund.internal_reference_id == internal_reference_id }) .cloned() .ok_or_else(|| { errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() }) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn insert_refund( &self, new: storage_types::RefundNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let mut refunds = self.refunds.lock().await; let current_time = common_utils::date_time::now(); let refund = storage_types::Refund { internal_reference_id: new.internal_reference_id, refund_id: new.refund_id, payment_id: new.payment_id, merchant_id: new.merchant_id, attempt_id: new.attempt_id, connector_transaction_id: new.connector_transaction_id, connector: new.connector, connector_refund_id: new.connector_refund_id, external_reference_id: new.external_reference_id, refund_type: new.refund_type, total_amount: new.total_amount, currency: new.currency, refund_amount: new.refund_amount, refund_status: new.refund_status, sent_to_gateway: new.sent_to_gateway, refund_error_message: None, refund_error_code: None, metadata: new.metadata, refund_arn: new.refund_arn.clone(), created_at: new.created_at, modified_at: current_time, description: new.description, refund_reason: new.refund_reason.clone(), profile_id: new.profile_id, updated_by: new.updated_by, merchant_connector_id: new.merchant_connector_id, charges: new.charges, split_refunds: new.split_refunds, organization_id: new.organization_id, unified_code: None, unified_message: None, processor_refund_data: new.processor_refund_data.clone(), processor_transaction_data: new.processor_transaction_data.clone(), issuer_error_code: None, issuer_error_message: None, // Below fields are deprecated. Please add any new fields above this line. connector_refund_data: None, connector_transaction_data: None, }; refunds.push(refund.clone()); Ok(refund) } #[cfg(all(feature = "v2", feature = "refunds_v2"))] async fn insert_refund( &self, new: storage_types::RefundNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let mut refunds = self.refunds.lock().await; let current_time = common_utils::date_time::now(); let refund = storage_types::Refund { id: new.id, merchant_reference_id: new.merchant_reference_id, payment_id: new.payment_id, merchant_id: new.merchant_id, attempt_id: new.attempt_id, connector_transaction_id: new.connector_transaction_id, connector: new.connector, connector_refund_id: new.connector_refund_id, external_reference_id: new.external_reference_id, refund_type: new.refund_type, total_amount: new.total_amount, currency: new.currency, refund_amount: new.refund_amount, refund_status: new.refund_status, sent_to_gateway: new.sent_to_gateway, refund_error_message: None, refund_error_code: None, metadata: new.metadata, refund_arn: new.refund_arn.clone(), created_at: new.created_at, modified_at: current_time, description: new.description, refund_reason: new.refund_reason.clone(), profile_id: new.profile_id, updated_by: new.updated_by, connector_id: new.connector_id, charges: new.charges, split_refunds: new.split_refunds, organization_id: new.organization_id, unified_code: None, unified_message: None, processor_refund_data: new.processor_refund_data.clone(), processor_transaction_data: new.processor_transaction_data.clone(), }; refunds.push(refund.clone()); Ok(refund) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_transaction_id( &self, merchant_id: &common_utils::id_type::MerchantId, connector_transaction_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> { let refunds = self.refunds.lock().await; Ok(refunds .iter() .take_while(|refund| { refund.merchant_id == *merchant_id && refund.get_connector_transaction_id() == connector_transaction_id }) .cloned() .collect::<Vec<_>>()) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn update_refund( &self, this: storage_types::Refund, refund: storage_types::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { self.refunds .lock() .await .iter_mut() .find(|refund| this.refund_id == refund.refund_id) .map(|r| { let refund_updated = RefundUpdateInternal::from(refund).create_refund(r.clone()); *r = refund_updated.clone(); refund_updated }) .ok_or_else(|| { errors::StorageError::ValueNotFound("cannot find refund to update".to_string()) .into() }) } #[cfg(all(feature = "v2", feature = "refunds_v2"))] async fn update_refund( &self, this: storage_types::Refund, refund: storage_types::RefundUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { self.refunds .lock() .await .iter_mut() .find(|refund| this.merchant_reference_id == refund.merchant_reference_id) .map(|r| { let refund_updated = RefundUpdateInternal::from(refund).create_refund(r.clone()); *r = refund_updated.clone(); refund_updated }) .ok_or_else(|| { errors::StorageError::ValueNotFound("cannot find refund to update".to_string()) .into() }) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_refund_id( &self, merchant_id: &common_utils::id_type::MerchantId, refund_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let refunds = self.refunds.lock().await; refunds .iter() .find(|refund| refund.merchant_id == *merchant_id && refund.refund_id == refund_id) .cloned() .ok_or_else(|| { errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() }) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_merchant_id_connector_refund_id_connector( &self, merchant_id: &common_utils::id_type::MerchantId, connector_refund_id: &str, connector: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let refunds = self.refunds.lock().await; refunds .iter() .find(|refund| { refund.merchant_id == *merchant_id && refund .get_optional_connector_refund_id() .map(|refund_id| refund_id.as_str()) == Some(connector_refund_id) && refund.connector == connector }) .cloned() .ok_or_else(|| { errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() }) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "refunds_v2")))] async fn find_refund_by_payment_id_merchant_id( &self, payment_id: &common_utils::id_type::PaymentId, merchant_id: &common_utils::id_type::MerchantId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> { let refunds = self.refunds.lock().await; Ok(refunds .iter() .filter(|refund| refund.merchant_id == *merchant_id && refund.payment_id == *payment_id) .cloned() .collect::<Vec<_>>()) } #[cfg(all(feature = "v2", feature = "refunds_v2"))] async fn find_refund_by_id( &self, id: &common_utils::id_type::GlobalRefundId, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<storage_types::Refund, errors::StorageError> { let refunds = self.refunds.lock().await; refunds .iter() .find(|refund| refund.id == *id) .cloned() .ok_or_else(|| { errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() }) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] async fn filter_refund_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, limit: i64, offset: i64, ) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> { let mut unique_connectors = HashSet::new(); let mut unique_merchant_connector_ids = HashSet::new(); let mut unique_currencies = HashSet::new(); let mut unique_statuses = HashSet::new(); let mut unique_profile_ids = HashSet::new(); // Fill the hash sets with data from refund_details if let Some(connectors) = &refund_details.connector { connectors.iter().for_each(|connector| { unique_connectors.insert(connector); }); } if let Some(merchant_connector_ids) = &refund_details.merchant_connector_id { merchant_connector_ids .iter() .for_each(|unique_merchant_connector_id| { unique_merchant_connector_ids.insert(unique_merchant_connector_id); }); } if let Some(currencies) = &refund_details.currency { currencies.iter().for_each(|currency| { unique_currencies.insert(currency); }); } if let Some(refund_statuses) = &refund_details.refund_status { refund_statuses.iter().for_each(|refund_status| { unique_statuses.insert(refund_status); }); } if let Some(profile_id_list) = &refund_details.profile_id { unique_profile_ids = profile_id_list.iter().collect(); } let refunds = self.refunds.lock().await; let filtered_refunds = refunds .iter() .filter(|refund| refund.merchant_id == *merchant_id) .filter(|refund| { refund_details .payment_id .clone() .map_or(true, |id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() .map_or(true, |id| id == refund.refund_id) }) .filter(|refund| { refund.profile_id.as_ref().is_some_and(|profile_id| { unique_profile_ids.is_empty() || unique_profile_ids.contains(profile_id) }) }) .filter(|refund| { refund.created_at >= refund_details.time_range.map_or( common_utils::date_time::now() - time::Duration::days(60), |range| range.start_time, ) && refund.created_at <= refund_details .time_range .map_or(common_utils::date_time::now(), |range| { range.end_time.unwrap_or_else(common_utils::date_time::now) }) }) .filter(|refund| { refund_details .amount_filter .as_ref() .map_or(true, |amount| { refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) && refund.refund_amount <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) }) .filter(|refund| { unique_merchant_connector_ids.is_empty() || refund .merchant_connector_id .as_ref() .is_some_and(|id| unique_merchant_connector_ids.contains(id)) }) .filter(|refund| { unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) }) .filter(|refund| { unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status) }) .skip(usize::try_from(offset).unwrap_or_default()) .take(usize::try_from(limit).unwrap_or(MAX_LIMIT)) .cloned() .collect::<Vec<_>>(); Ok(filtered_refunds) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] async fn filter_refund_by_meta_constraints( &self, _merchant_id: &common_utils::id_type::MerchantId, refund_details: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { let refunds = self.refunds.lock().await; let start_time = refund_details.start_time; let end_time = refund_details .end_time .unwrap_or_else(common_utils::date_time::now); let filtered_refunds = refunds .iter() .filter(|refund| refund.created_at >= start_time && refund.created_at <= end_time) .cloned() .collect::<Vec<diesel_models::refund::Refund>>(); let mut refund_meta_data = api_models::refunds::RefundListMetaData { connector: vec![], currency: vec![], refund_status: vec![], }; let mut unique_connectors = HashSet::new(); let mut unique_currencies = HashSet::new(); let mut unique_statuses = HashSet::new(); for refund in filtered_refunds.into_iter() { unique_connectors.insert(refund.connector); let currency: api_models::enums::Currency = refund.currency; unique_currencies.insert(currency); let status: api_models::enums::RefundStatus = refund.refund_status; unique_statuses.insert(status); } refund_meta_data.connector = unique_connectors.into_iter().collect(); refund_meta_data.currency = unique_currencies.into_iter().collect(); refund_meta_data.refund_status = unique_statuses.into_iter().collect(); Ok(refund_meta_data) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] async fn get_refund_status_with_count( &self, _merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(api_models::enums::RefundStatus, i64)>, errors::StorageError> { let refunds = self.refunds.lock().await; let start_time = time_range.start_time; let end_time = time_range .end_time .unwrap_or_else(common_utils::date_time::now); let filtered_refunds = refunds .iter() .filter(|refund| { refund.created_at >= start_time && refund.created_at <= end_time && profile_id_list .as_ref() .zip(refund.profile_id.as_ref()) .map(|(received_profile_list, received_profile_id)| { received_profile_list.contains(received_profile_id) }) .unwrap_or(true) }) .cloned() .collect::<Vec<diesel_models::refund::Refund>>(); let mut refund_status_counts: HashMap<api_models::enums::RefundStatus, i64> = HashMap::new(); for refund in filtered_refunds { *refund_status_counts .entry(refund.refund_status) .or_insert(0) += 1; } let result: Vec<(api_models::enums::RefundStatus, i64)> = refund_status_counts.into_iter().collect(); Ok(result) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "refunds_v2"), feature = "olap" ))] async fn get_total_count_of_refunds( &self, merchant_id: &common_utils::id_type::MerchantId, refund_details: &refunds::RefundListConstraints, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { let mut unique_connectors = HashSet::new(); let mut unique_merchant_connector_ids = HashSet::new(); let mut unique_currencies = HashSet::new(); let mut unique_statuses = HashSet::new(); let mut unique_profile_ids = HashSet::new(); // Fill the hash sets with data from refund_details if let Some(connectors) = &refund_details.connector { connectors.iter().for_each(|connector| { unique_connectors.insert(connector); }); } if let Some(merchant_connector_ids) = &refund_details.merchant_connector_id { merchant_connector_ids .iter() .for_each(|unique_merchant_connector_id| { unique_merchant_connector_ids.insert(unique_merchant_connector_id); }); } if let Some(currencies) = &refund_details.currency { currencies.iter().for_each(|currency| { unique_currencies.insert(currency); }); } if let Some(refund_statuses) = &refund_details.refund_status { refund_statuses.iter().for_each(|refund_status| { unique_statuses.insert(refund_status); }); } if let Some(profile_id_list) = &refund_details.profile_id { unique_profile_ids = profile_id_list.iter().collect(); } let refunds = self.refunds.lock().await; let filtered_refunds = refunds .iter() .filter(|refund| refund.merchant_id == *merchant_id) .filter(|refund| { refund_details .payment_id .clone() .map_or(true, |id| id == refund.payment_id) }) .filter(|refund| { refund_details .refund_id .clone() .map_or(true, |id| id == refund.refund_id) }) .filter(|refund| { refund.profile_id.as_ref().is_some_and(|profile_id| { unique_profile_ids.is_empty() || unique_profile_ids.contains(profile_id) }) }) .filter(|refund| { refund.created_at >= refund_details.time_range.map_or( common_utils::date_time::now() - time::Duration::days(60), |range| range.start_time, ) && refund.created_at <= refund_details .time_range .map_or(common_utils::date_time::now(), |range| { range.end_time.unwrap_or_else(common_utils::date_time::now) }) }) .filter(|refund| { refund_details .amount_filter .as_ref() .map_or(true, |amount| { refund.refund_amount >= MinorUnit::new(amount.start_amount.unwrap_or(i64::MIN)) && refund.refund_amount <= MinorUnit::new(amount.end_amount.unwrap_or(i64::MAX)) }) }) .filter(|refund| { unique_connectors.is_empty() || unique_connectors.contains(&refund.connector) }) .filter(|refund| { unique_merchant_connector_ids.is_empty() || refund .merchant_connector_id .as_ref() .is_some_and(|id| unique_merchant_connector_ids.contains(id)) }) .filter(|refund| { unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) }) .filter(|refund| { unique_statuses.is_empty() || unique_statuses.contains(&refund.refund_status) }) .cloned() .collect::<Vec<_>>(); let filtered_refunds_count = filtered_refunds.len().try_into().unwrap_or_default(); Ok(filtered_refunds_count) } }
12,935
1,445
hyperswitch
crates/router/src/db/organization.rs
.rs
use common_utils::{errors::CustomResult, id_type}; use diesel_models::{organization as storage, organization::OrganizationBridge}; use error_stack::report; use router_env::{instrument, tracing}; use crate::{connection, core::errors, services::Store}; #[async_trait::async_trait] pub trait OrganizationInterface { async fn insert_organization( &self, organization: storage::OrganizationNew, ) -> CustomResult<storage::Organization, errors::StorageError>; async fn find_organization_by_org_id( &self, org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Organization, errors::StorageError>; async fn update_organization_by_org_id( &self, org_id: &id_type::OrganizationId, update: storage::OrganizationUpdate, ) -> CustomResult<storage::Organization, errors::StorageError>; } #[async_trait::async_trait] impl OrganizationInterface for Store { #[instrument(skip_all)] async fn insert_organization( &self, organization: storage::OrganizationNew, ) -> CustomResult<storage::Organization, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; organization .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_organization_by_org_id( &self, org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Organization, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; storage::Organization::find_by_org_id(&conn, org_id.to_owned()) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_organization_by_org_id( &self, org_id: &id_type::OrganizationId, update: storage::OrganizationUpdate, ) -> CustomResult<storage::Organization, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; storage::Organization::update_by_org_id(&conn, org_id.to_owned(), update) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl OrganizationInterface for super::MockDb { async fn insert_organization( &self, organization: storage::OrganizationNew, ) -> CustomResult<storage::Organization, errors::StorageError> { let mut organizations = self.organizations.lock().await; if organizations .iter() .any(|org| org.get_organization_id() == organization.get_organization_id()) { Err(errors::StorageError::DuplicateValue { entity: "org_id", key: None, })? } let org = storage::Organization::new(organization); organizations.push(org.clone()); Ok(org) } async fn find_organization_by_org_id( &self, org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Organization, errors::StorageError> { let organizations = self.organizations.lock().await; organizations .iter() .find(|org| org.get_organization_id() == *org_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No organization available for org_id = {:?}", org_id )) .into(), ) } async fn update_organization_by_org_id( &self, org_id: &id_type::OrganizationId, update: storage::OrganizationUpdate, ) -> CustomResult<storage::Organization, errors::StorageError> { let mut organizations = self.organizations.lock().await; organizations .iter_mut() .find(|org| org.get_organization_id() == *org_id) .map(|org| match &update { storage::OrganizationUpdate::Update { organization_name, organization_details, metadata, } => { organization_name .as_ref() .map(|org_name| org.set_organization_name(org_name.to_owned())); organization_details.clone_into(&mut org.organization_details); metadata.clone_into(&mut org.metadata); org } }) .ok_or( errors::StorageError::ValueNotFound(format!( "No organization available for org_id = {:?}", org_id )) .into(), ) .cloned() } }
970
1,446
hyperswitch
crates/router/src/db/capture.rs
.rs
use router_env::{instrument, tracing}; use super::MockDb; use crate::{ core::errors::{self, CustomResult}, types::storage::{self as types, enums}, }; #[async_trait::async_trait] pub trait CaptureInterface { async fn insert_capture( &self, capture: types::CaptureNew, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<types::Capture, errors::StorageError>; async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, authorized_attempt_id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<types::Capture>, errors::StorageError>; async fn update_capture_with_capture_id( &self, this: types::Capture, capture: types::CaptureUpdate, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<types::Capture, errors::StorageError>; } #[cfg(feature = "kv_store")] mod storage { use error_stack::report; use router_env::{instrument, tracing}; use super::CaptureInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::storage::{capture::*, enums}, }; #[async_trait::async_trait] impl CaptureInterface for Store { #[instrument(skip_all)] async fn insert_capture( &self, capture: CaptureNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Capture, errors::StorageError> { let db_call = || async { let conn = connection::pg_connection_write(self).await?; capture .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) }; db_call().await } #[instrument(skip_all)] async fn update_capture_with_capture_id( &self, this: Capture, capture: CaptureUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Capture, errors::StorageError> { let db_call = || async { let conn = connection::pg_connection_write(self).await?; this.update_with_capture_id(&conn, capture) .await .map_err(|error| report!(errors::StorageError::from(error))) }; db_call().await } #[instrument(skip_all)] async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, authorized_attempt_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<Capture>, errors::StorageError> { let db_call = || async { let conn = connection::pg_connection_read(self).await?; Capture::find_all_by_merchant_id_payment_id_authorized_attempt_id( merchant_id, payment_id, authorized_attempt_id, &conn, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; db_call().await } } } #[cfg(not(feature = "kv_store"))] mod storage { use error_stack::report; use router_env::{instrument, tracing}; use super::CaptureInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::storage::{capture::*, enums}, }; #[async_trait::async_trait] impl CaptureInterface for Store { #[instrument(skip_all)] async fn insert_capture( &self, capture: CaptureNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Capture, errors::StorageError> { let db_call = || async { let conn = connection::pg_connection_write(self).await?; capture .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) }; db_call().await } #[instrument(skip_all)] async fn update_capture_with_capture_id( &self, this: Capture, capture: CaptureUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Capture, errors::StorageError> { let db_call = || async { let conn = connection::pg_connection_write(self).await?; this.update_with_capture_id(&conn, capture) .await .map_err(|error| report!(errors::StorageError::from(error))) }; db_call().await } #[instrument(skip_all)] async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, authorized_attempt_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<Capture>, errors::StorageError> { let db_call = || async { let conn = connection::pg_connection_read(self).await?; Capture::find_all_by_merchant_id_payment_id_authorized_attempt_id( merchant_id, payment_id, authorized_attempt_id, &conn, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; db_call().await } } } #[async_trait::async_trait] impl CaptureInterface for MockDb { async fn insert_capture( &self, capture: types::CaptureNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<types::Capture, errors::StorageError> { let mut captures = self.captures.lock().await; let capture = types::Capture { capture_id: capture.capture_id, payment_id: capture.payment_id, merchant_id: capture.merchant_id, status: capture.status, amount: capture.amount, currency: capture.currency, connector: capture.connector, error_message: capture.error_message, error_code: capture.error_code, error_reason: capture.error_reason, tax_amount: capture.tax_amount, created_at: capture.created_at, modified_at: capture.modified_at, authorized_attempt_id: capture.authorized_attempt_id, capture_sequence: capture.capture_sequence, connector_capture_id: capture.connector_capture_id, connector_response_reference_id: capture.connector_response_reference_id, processor_capture_data: capture.processor_capture_data, // Below fields are deprecated. Please add any new fields above this line. connector_capture_data: None, }; captures.push(capture.clone()); Ok(capture) } #[instrument(skip_all)] async fn update_capture_with_capture_id( &self, _this: types::Capture, _capture: types::CaptureUpdate, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<types::Capture, errors::StorageError> { //Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _payment_id: &common_utils::id_type::PaymentId, _authorized_attempt_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<types::Capture>, errors::StorageError> { //Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } }
1,680
1,447
hyperswitch
crates/router/src/db/authorization.rs
.rs
use diesel_models::authorization::AuthorizationUpdateInternal; use error_stack::report; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait AuthorizationInterface { async fn insert_authorization( &self, authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError>; async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError>; async fn update_authorization_by_merchant_id_authorization_id( &self, merchant_id: common_utils::id_type::MerchantId, authorization_id: String, authorization: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError>; } #[async_trait::async_trait] impl AuthorizationInterface for Store { #[instrument(skip_all)] async fn insert_authorization( &self, authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; authorization .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Authorization::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_authorization_by_merchant_id_authorization_id( &self, merchant_id: common_utils::id_type::MerchantId, authorization_id: String, authorization: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Authorization::update_by_merchant_id_authorization_id( &conn, merchant_id, authorization_id, authorization, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl AuthorizationInterface for MockDb { async fn insert_authorization( &self, authorization: storage::AuthorizationNew, ) -> CustomResult<storage::Authorization, errors::StorageError> { let mut authorizations = self.authorizations.lock().await; if authorizations.iter().any(|authorization_inner| { authorization_inner.authorization_id == authorization.authorization_id }) { Err(errors::StorageError::DuplicateValue { entity: "authorization_id", key: None, })? } let authorization = storage::Authorization { authorization_id: authorization.authorization_id, merchant_id: authorization.merchant_id, payment_id: authorization.payment_id, amount: authorization.amount, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), status: authorization.status, error_code: authorization.error_code, error_message: authorization.error_message, connector_authorization_id: authorization.connector_authorization_id, previously_authorized_amount: authorization.previously_authorized_amount, }; authorizations.push(authorization.clone()); Ok(authorization) } async fn find_all_authorizations_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> { let authorizations = self.authorizations.lock().await; let authorizations_found: Vec<storage::Authorization> = authorizations .iter() .filter(|a| a.merchant_id == *merchant_id && a.payment_id == *payment_id) .cloned() .collect(); Ok(authorizations_found) } async fn update_authorization_by_merchant_id_authorization_id( &self, merchant_id: common_utils::id_type::MerchantId, authorization_id: String, authorization_update: storage::AuthorizationUpdate, ) -> CustomResult<storage::Authorization, errors::StorageError> { let mut authorizations = self.authorizations.lock().await; authorizations .iter_mut() .find(|authorization| authorization.authorization_id == authorization_id && authorization.merchant_id == merchant_id) .map(|authorization| { let authorization_updated = AuthorizationUpdateInternal::from(authorization_update) .create_authorization(authorization.clone()); *authorization = authorization_updated.clone(); authorization_updated }) .ok_or( errors::StorageError::ValueNotFound(format!( "cannot find authorization for authorization_id = {authorization_id} and merchant_id = {merchant_id:?}" )) .into(), ) } }
1,157
1,448
hyperswitch
crates/router/src/db/file.rs
.rs
use error_stack::report; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait FileMetadataInterface { async fn insert_file_metadata( &self, file: storage::FileMetadataNew, ) -> CustomResult<storage::FileMetadata, errors::StorageError>; async fn find_file_metadata_by_merchant_id_file_id( &self, merchant_id: &common_utils::id_type::MerchantId, file_id: &str, ) -> CustomResult<storage::FileMetadata, errors::StorageError>; async fn delete_file_metadata_by_merchant_id_file_id( &self, merchant_id: &common_utils::id_type::MerchantId, file_id: &str, ) -> CustomResult<bool, errors::StorageError>; async fn update_file_metadata( &self, this: storage::FileMetadata, file_metadata: storage::FileMetadataUpdate, ) -> CustomResult<storage::FileMetadata, errors::StorageError>; } #[async_trait::async_trait] impl FileMetadataInterface for Store { #[instrument(skip_all)] async fn insert_file_metadata( &self, file: storage::FileMetadataNew, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; file.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_file_metadata_by_merchant_id_file_id( &self, merchant_id: &common_utils::id_type::MerchantId, file_id: &str, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::FileMetadata::find_by_merchant_id_file_id(&conn, merchant_id, file_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_file_metadata_by_merchant_id_file_id( &self, merchant_id: &common_utils::id_type::MerchantId, file_id: &str, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::FileMetadata::delete_by_merchant_id_file_id(&conn, merchant_id, file_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_file_metadata( &self, this: storage::FileMetadata, file_metadata: storage::FileMetadataUpdate, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update(&conn, file_metadata) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl FileMetadataInterface for MockDb { async fn insert_file_metadata( &self, _file: storage::FileMetadataNew, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn find_file_metadata_by_merchant_id_file_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _file_id: &str, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn delete_file_metadata_by_merchant_id_file_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _file_id: &str, ) -> CustomResult<bool, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn update_file_metadata( &self, _this: storage::FileMetadata, _file_metadata: storage::FileMetadataUpdate, ) -> CustomResult<storage::FileMetadata, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } }
982
1,449
hyperswitch
crates/router/src/db/authentication.rs
.rs
use diesel_models::authentication::AuthenticationUpdateInternal; use error_stack::report; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait AuthenticationInterface { async fn insert_authentication( &self, authentication: storage::AuthenticationNew, ) -> CustomResult<storage::Authentication, errors::StorageError>; async fn find_authentication_by_merchant_id_authentication_id( &self, merchant_id: &common_utils::id_type::MerchantId, authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError>; async fn find_authentication_by_merchant_id_connector_authentication_id( &self, merchant_id: common_utils::id_type::MerchantId, connector_authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError>; async fn update_authentication_by_merchant_id_authentication_id( &self, previous_state: storage::Authentication, authentication_update: storage::AuthenticationUpdate, ) -> CustomResult<storage::Authentication, errors::StorageError>; } #[async_trait::async_trait] impl AuthenticationInterface for Store { #[instrument(skip_all)] async fn insert_authentication( &self, authentication: storage::AuthenticationNew, ) -> CustomResult<storage::Authentication, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; authentication .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_authentication_by_merchant_id_authentication_id( &self, merchant_id: &common_utils::id_type::MerchantId, authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Authentication::find_by_merchant_id_authentication_id( &conn, merchant_id, &authentication_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_authentication_by_merchant_id_connector_authentication_id( &self, merchant_id: common_utils::id_type::MerchantId, connector_authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Authentication::find_authentication_by_merchant_id_connector_authentication_id( &conn, &merchant_id, &connector_authentication_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_authentication_by_merchant_id_authentication_id( &self, previous_state: storage::Authentication, authentication_update: storage::AuthenticationUpdate, ) -> CustomResult<storage::Authentication, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Authentication::update_by_merchant_id_authentication_id( &conn, previous_state.merchant_id, previous_state.authentication_id, authentication_update, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl AuthenticationInterface for MockDb { async fn insert_authentication( &self, authentication: storage::AuthenticationNew, ) -> CustomResult<storage::Authentication, errors::StorageError> { let mut authentications = self.authentications.lock().await; if authentications.iter().any(|authentication_inner| { authentication_inner.authentication_id == authentication.authentication_id }) { Err(errors::StorageError::DuplicateValue { entity: "authentication_id", key: Some(authentication.authentication_id.clone()), })? } let authentication = storage::Authentication { created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), authentication_id: authentication.authentication_id, merchant_id: authentication.merchant_id, authentication_status: authentication.authentication_status, authentication_connector: authentication.authentication_connector, connector_authentication_id: authentication.connector_authentication_id, authentication_data: None, payment_method_id: authentication.payment_method_id, authentication_type: authentication.authentication_type, authentication_lifecycle_status: authentication.authentication_lifecycle_status, error_code: authentication.error_code, error_message: authentication.error_message, connector_metadata: authentication.connector_metadata, maximum_supported_version: authentication.maximum_supported_version, threeds_server_transaction_id: authentication.threeds_server_transaction_id, cavv: authentication.cavv, authentication_flow_type: authentication.authentication_flow_type, message_version: authentication.message_version, eci: authentication.eci, trans_status: authentication.trans_status, acquirer_bin: authentication.acquirer_bin, acquirer_merchant_id: authentication.acquirer_merchant_id, three_ds_method_data: authentication.three_ds_method_data, three_ds_method_url: authentication.three_ds_method_url, acs_url: authentication.acs_url, challenge_request: authentication.challenge_request, acs_reference_number: authentication.acs_reference_number, acs_trans_id: authentication.acs_trans_id, acs_signed_content: authentication.acs_signed_content, profile_id: authentication.profile_id, payment_id: authentication.payment_id, merchant_connector_id: authentication.merchant_connector_id, ds_trans_id: authentication.ds_trans_id, directory_server_id: authentication.directory_server_id, acquirer_country_code: authentication.acquirer_country_code, service_details: authentication.service_details, organization_id: authentication.organization_id, }; authentications.push(authentication.clone()); Ok(authentication) } async fn find_authentication_by_merchant_id_authentication_id( &self, merchant_id: &common_utils::id_type::MerchantId, authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError> { let authentications = self.authentications.lock().await; authentications .iter() .find(|a| a.merchant_id == *merchant_id && a.authentication_id == authentication_id) .ok_or( errors::StorageError::ValueNotFound(format!( "cannot find authentication for authentication_id = {authentication_id} and merchant_id = {merchant_id:?}" )).into(), ).cloned() } async fn find_authentication_by_merchant_id_connector_authentication_id( &self, _merchant_id: common_utils::id_type::MerchantId, _connector_authentication_id: String, ) -> CustomResult<storage::Authentication, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_authentication_by_merchant_id_authentication_id( &self, previous_state: storage::Authentication, authentication_update: storage::AuthenticationUpdate, ) -> CustomResult<storage::Authentication, errors::StorageError> { let mut authentications = self.authentications.lock().await; let authentication_id = previous_state.authentication_id.clone(); let merchant_id = previous_state.merchant_id.clone(); authentications .iter_mut() .find(|authentication| authentication.authentication_id == authentication_id && authentication.merchant_id == merchant_id) .map(|authentication| { let authentication_update_internal = AuthenticationUpdateInternal::from(authentication_update); let updated_authentication = authentication_update_internal.apply_changeset(previous_state); *authentication = updated_authentication.clone(); updated_authentication }) .ok_or( errors::StorageError::ValueNotFound(format!( "cannot find authentication for authentication_id = {authentication_id} and merchant_id = {merchant_id:?}" )) .into(), ) } }
1,667
1,450
hyperswitch
crates/router/src/db/unified_translations.rs
.rs
use diesel_models::unified_translations as storage; use error_stack::report; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait UnifiedTranslationsInterface { async fn add_unfied_translation( &self, translation: storage::UnifiedTranslationsNew, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError>; async fn update_translation( &self, unified_code: String, unified_message: String, locale: String, data: storage::UnifiedTranslationsUpdate, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError>; async fn find_translation( &self, unified_code: String, unified_message: String, locale: String, ) -> CustomResult<String, errors::StorageError>; async fn delete_translation( &self, unified_code: String, unified_message: String, locale: String, ) -> CustomResult<bool, errors::StorageError>; } #[async_trait::async_trait] impl UnifiedTranslationsInterface for Store { async fn add_unfied_translation( &self, translation: storage::UnifiedTranslationsNew, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; translation .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn update_translation( &self, unified_code: String, unified_message: String, locale: String, data: storage::UnifiedTranslationsUpdate, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UnifiedTranslations::update_by_unified_code_unified_message_locale( &conn, unified_code, unified_message, locale, data, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_translation( &self, unified_code: String, unified_message: String, locale: String, ) -> CustomResult<String, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let translations = storage::UnifiedTranslations::find_by_unified_code_unified_message_locale( &conn, unified_code, unified_message, locale, ) .await .map_err(|error| report!(errors::StorageError::from(error)))?; Ok(translations.translation) } async fn delete_translation( &self, unified_code: String, unified_message: String, locale: String, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UnifiedTranslations::delete_by_unified_code_unified_message_locale( &conn, unified_code, unified_message, locale, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl UnifiedTranslationsInterface for MockDb { async fn add_unfied_translation( &self, _translation: storage::UnifiedTranslationsNew, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_translation( &self, _unified_code: String, _unified_message: String, _locale: String, ) -> CustomResult<String, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_translation( &self, _unified_code: String, _unified_message: String, _locale: String, _data: storage::UnifiedTranslationsUpdate, ) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn delete_translation( &self, _unified_code: String, _unified_message: String, _locale: String, ) -> CustomResult<bool, errors::StorageError> { Err(errors::StorageError::MockDbError)? } }
937
1,451
hyperswitch
crates/router/src/db/api_keys.rs
.rs
use error_stack::report; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use storage_impl::redis::cache::{self, CacheKind, ACCOUNTS_CACHE}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait ApiKeyInterface { async fn insert_api_key( &self, api_key: storage::ApiKeyNew, ) -> CustomResult<storage::ApiKey, errors::StorageError>; async fn update_api_key( &self, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError>; async fn revoke_api_key( &self, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<bool, errors::StorageError>; async fn find_api_key_by_merchant_id_key_id_optional( &self, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError>; async fn find_api_key_by_hash_optional( &self, hashed_api_key: storage::HashedApiKey, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError>; async fn list_api_keys_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, limit: Option<i64>, offset: Option<i64>, ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError>; } #[async_trait::async_trait] impl ApiKeyInterface for Store { #[instrument(skip_all)] async fn insert_api_key( &self, api_key: storage::ApiKeyNew, ) -> CustomResult<storage::ApiKey, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; api_key .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_api_key( &self, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let _merchant_id = merchant_id.clone(); let _key_id = key_id.clone(); let update_call = || async { storage::ApiKey::update_by_merchant_id_key_id(&conn, merchant_id, key_id, api_key) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { update_call().await } #[cfg(feature = "accounts_cache")] { use error_stack::report; // We need to fetch api_key here because the key that's saved in cache in HashedApiKey. // Used function from storage model to reuse the connection that made here instead of // creating new. let api_key = storage::ApiKey::find_optional_by_merchant_id_key_id( &conn, &_merchant_id, &_key_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .ok_or(report!(errors::StorageError::ValueNotFound(format!( "ApiKey of {} not found", _key_id.get_string_repr() ))))?; cache::publish_and_redact( self, CacheKind::Accounts(api_key.hashed_api_key.into_inner().into()), update_call, ) .await } } #[instrument(skip_all)] async fn revoke_api_key( &self, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let delete_call = || async { storage::ApiKey::revoke_by_merchant_id_key_id(&conn, merchant_id, key_id) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { delete_call().await } #[cfg(feature = "accounts_cache")] { use error_stack::report; // We need to fetch api_key here because the key that's saved in cache in HashedApiKey. // Used function from storage model to reuse the connection that made here instead of // creating new. let api_key = storage::ApiKey::find_optional_by_merchant_id_key_id(&conn, merchant_id, key_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .ok_or(report!(errors::StorageError::ValueNotFound(format!( "ApiKey of {} not found", key_id.get_string_repr() ))))?; cache::publish_and_redact( self, CacheKind::Accounts(api_key.hashed_api_key.into_inner().into()), delete_call, ) .await } } #[instrument(skip_all)] async fn find_api_key_by_merchant_id_key_id_optional( &self, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::ApiKey::find_optional_by_merchant_id_key_id(&conn, merchant_id, key_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_api_key_by_hash_optional( &self, hashed_api_key: storage::HashedApiKey, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { let _hashed_api_key = hashed_api_key.clone(); let find_call = || async { let conn = connection::pg_connection_read(self).await?; storage::ApiKey::find_optional_by_hashed_api_key(&conn, hashed_api_key) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call().await } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &_hashed_api_key.into_inner(), find_call, &ACCOUNTS_CACHE, ) .await } } #[instrument(skip_all)] async fn list_api_keys_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, limit: Option<i64>, offset: Option<i64>, ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::ApiKey::find_by_merchant_id(&conn, merchant_id, limit, offset) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl ApiKeyInterface for MockDb { async fn insert_api_key( &self, api_key: storage::ApiKeyNew, ) -> CustomResult<storage::ApiKey, errors::StorageError> { let mut locked_api_keys = self.api_keys.lock().await; // don't allow duplicate key_ids, a those would be a unique constraint violation in the // real db as it is used as the primary key if locked_api_keys.iter().any(|k| k.key_id == api_key.key_id) { Err(errors::StorageError::MockDbError)?; } let stored_key = storage::ApiKey { key_id: api_key.key_id, merchant_id: api_key.merchant_id, name: api_key.name, description: api_key.description, hashed_api_key: api_key.hashed_api_key, prefix: api_key.prefix, created_at: api_key.created_at, expires_at: api_key.expires_at, last_used: api_key.last_used, }; locked_api_keys.push(stored_key.clone()); Ok(stored_key) } async fn update_api_key( &self, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, api_key: storage::ApiKeyUpdate, ) -> CustomResult<storage::ApiKey, errors::StorageError> { let mut locked_api_keys = self.api_keys.lock().await; // find a key with the given merchant_id and key_id and update, otherwise return an error let key_to_update = locked_api_keys .iter_mut() .find(|k| k.merchant_id == merchant_id && k.key_id == key_id) .ok_or(errors::StorageError::MockDbError)?; match api_key { storage::ApiKeyUpdate::Update { name, description, expires_at, last_used, } => { if let Some(name) = name { key_to_update.name = name; } // only update these fields if the value was Some(_) if description.is_some() { key_to_update.description = description; } if let Some(expires_at) = expires_at { key_to_update.expires_at = expires_at; } if last_used.is_some() { key_to_update.last_used = last_used } } storage::ApiKeyUpdate::LastUsedUpdate { last_used } => { key_to_update.last_used = Some(last_used); } } Ok(key_to_update.clone()) } async fn revoke_api_key( &self, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<bool, errors::StorageError> { let mut locked_api_keys = self.api_keys.lock().await; // find the key to remove, if it exists if let Some(pos) = locked_api_keys .iter() .position(|k| k.merchant_id == *merchant_id && k.key_id == *key_id) { // use `remove` instead of `swap_remove` so we have a consistent order, which might // matter to someone using limit/offset in `list_api_keys_by_merchant_id` locked_api_keys.remove(pos); Ok(true) } else { Ok(false) } } async fn find_api_key_by_merchant_id_key_id_optional( &self, merchant_id: &common_utils::id_type::MerchantId, key_id: &common_utils::id_type::ApiKeyId, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { Ok(self .api_keys .lock() .await .iter() .find(|k| k.merchant_id == *merchant_id && k.key_id == *key_id) .cloned()) } async fn find_api_key_by_hash_optional( &self, hashed_api_key: storage::HashedApiKey, ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> { Ok(self .api_keys .lock() .await .iter() .find(|k| k.hashed_api_key == hashed_api_key) .cloned()) } async fn list_api_keys_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, limit: Option<i64>, offset: Option<i64>, ) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> { // mimic the SQL limit/offset behavior let offset: usize = if let Some(offset) = offset { if offset < 0 { Err(errors::StorageError::MockDbError)?; } offset .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { 0 }; let limit: usize = if let Some(limit) = limit { if limit < 0 { Err(errors::StorageError::MockDbError)?; } limit .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { usize::MAX }; let keys_for_merchant_id: Vec<storage::ApiKey> = self .api_keys .lock() .await .iter() .filter(|k| k.merchant_id == *merchant_id) .skip(offset) .take(limit) .cloned() .collect(); Ok(keys_for_merchant_id) } } #[cfg(test)] mod tests { use std::borrow::Cow; use storage_impl::redis::{ cache::{self, CacheKey, CacheKind, ACCOUNTS_CACHE}, kv_store::RedisConnInterface, pub_sub::PubSubInterface, }; use time::macros::datetime; use crate::{ db::{api_keys::ApiKeyInterface, MockDb}, types::storage, }; #[allow(clippy::unwrap_used)] #[tokio::test] async fn test_mockdb_api_key_interface() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant1")).unwrap(); let key_id1 = common_utils::id_type::ApiKeyId::try_from(Cow::from("key_id1")).unwrap(); let key_id2 = common_utils::id_type::ApiKeyId::try_from(Cow::from("key_id2")).unwrap(); let non_existent_key_id = common_utils::id_type::ApiKeyId::try_from(Cow::from("does_not_exist")).unwrap(); let key1 = mockdb .insert_api_key(storage::ApiKeyNew { key_id: key_id1.clone(), merchant_id: merchant_id.clone(), name: "Key 1".into(), description: None, hashed_api_key: "hashed_key1".to_string().into(), prefix: "abc".into(), created_at: datetime!(2023-02-01 0:00), expires_at: Some(datetime!(2023-03-01 0:00)), last_used: None, }) .await .unwrap(); mockdb .insert_api_key(storage::ApiKeyNew { key_id: key_id2.clone(), merchant_id: merchant_id.clone(), name: "Key 2".into(), description: None, hashed_api_key: "hashed_key2".to_string().into(), prefix: "abc".into(), created_at: datetime!(2023-03-01 0:00), expires_at: None, last_used: None, }) .await .unwrap(); let found_key1 = mockdb .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id1) .await .unwrap() .unwrap(); assert_eq!(found_key1.key_id, key1.key_id); assert!(mockdb .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &non_existent_key_id) .await .unwrap() .is_none()); mockdb .update_api_key( merchant_id.clone(), key_id1.clone(), storage::ApiKeyUpdate::LastUsedUpdate { last_used: datetime!(2023-02-04 1:11), }, ) .await .unwrap(); let updated_key1 = mockdb .find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id1) .await .unwrap() .unwrap(); assert_eq!(updated_key1.last_used, Some(datetime!(2023-02-04 1:11))); assert_eq!( mockdb .list_api_keys_by_merchant_id(&merchant_id, None, None) .await .unwrap() .len(), 2 ); mockdb.revoke_api_key(&merchant_id, &key_id1).await.unwrap(); assert_eq!( mockdb .list_api_keys_by_merchant_id(&merchant_id, None, None) .await .unwrap() .len(), 1 ); } #[allow(clippy::unwrap_used)] #[tokio::test] async fn test_api_keys_cache() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("test_merchant")).unwrap(); #[allow(clippy::expect_used)] let db = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let redis_conn = db.get_redis_conn().unwrap(); redis_conn .subscribe("hyperswitch_invalidate") .await .unwrap(); let test_key = common_utils::id_type::ApiKeyId::try_from(Cow::from("test_ey")).unwrap(); let api = storage::ApiKeyNew { key_id: test_key.clone(), merchant_id: merchant_id.clone(), name: "My test key".into(), description: None, hashed_api_key: "a_hashed_key".to_string().into(), prefix: "pre".into(), created_at: datetime!(2023-06-01 0:00), expires_at: None, last_used: None, }; let api = db.insert_api_key(api).await.unwrap(); let hashed_api_key = api.hashed_api_key.clone(); let find_call = || async { db.find_api_key_by_hash_optional(hashed_api_key.clone()) .await }; let _: Option<storage::ApiKey> = cache::get_or_populate_in_memory( &db, &format!( "{}_{}", merchant_id.get_string_repr(), hashed_api_key.clone().into_inner() ), find_call, &ACCOUNTS_CACHE, ) .await .unwrap(); let delete_call = || async { db.revoke_api_key(&merchant_id, &api.key_id).await }; cache::publish_and_redact( &db, CacheKind::Accounts( format!( "{}_{}", merchant_id.get_string_repr(), hashed_api_key.clone().into_inner() ) .into(), ), delete_call, ) .await .unwrap(); assert!(ACCOUNTS_CACHE .get_val::<storage::ApiKey>(CacheKey { key: format!( "{}_{}", merchant_id.get_string_repr(), hashed_api_key.into_inner() ), prefix: String::default(), },) .await .is_none()) } }
4,255
1,452
hyperswitch
crates/router/src/db/relay.rs
.rs
use common_utils::types::keymanager::KeyManagerState; use diesel_models; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion}; use storage_impl::MockDb; use super::domain; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, services::Store, }; #[async_trait::async_trait] pub trait RelayInterface { async fn insert_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, new: hyperswitch_domain_models::relay::Relay, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; async fn update_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: hyperswitch_domain_models::relay::Relay, relay_update: hyperswitch_domain_models::relay::RelayUpdate, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; async fn find_relay_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, relay_id: &common_utils::id_type::RelayId, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; async fn find_relay_by_profile_id_connector_reference_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, connector_reference_id: &str, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; } #[async_trait::async_trait] impl RelayInterface for Store { async fn insert_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, new: hyperswitch_domain_models::relay::Relay, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn update_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: hyperswitch_domain_models::relay::Relay, relay_update: hyperswitch_domain_models::relay::RelayUpdate, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; Conversion::convert(current_state) .await .change_context(errors::StorageError::EncryptionError)? .update( &conn, diesel_models::relay::RelayUpdateInternal::from(relay_update), ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_relay_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, relay_id: &common_utils::id_type::RelayId, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_models::relay::Relay::find_by_id(&conn, relay_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_relay_by_profile_id_connector_reference_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, connector_reference_id: &str, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_models::relay::Relay::find_by_profile_id_connector_reference_id( &conn, profile_id, connector_reference_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } } #[async_trait::async_trait] impl RelayInterface for MockDb { async fn insert_relay( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &domain::MerchantKeyStore, _new: hyperswitch_domain_models::relay::Relay, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_relay( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &domain::MerchantKeyStore, _current_state: hyperswitch_domain_models::relay::Relay, _relay_update: hyperswitch_domain_models::relay::RelayUpdate, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_relay_by_id( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &domain::MerchantKeyStore, _relay_id: &common_utils::id_type::RelayId, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_relay_by_profile_id_connector_reference_id( &self, _key_manager_state: &KeyManagerState, _merchant_key_store: &domain::MerchantKeyStore, _profile_id: &common_utils::id_type::ProfileId, _connector_reference_id: &str, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl RelayInterface for KafkaStore { async fn insert_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, new: hyperswitch_domain_models::relay::Relay, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { self.diesel_store .insert_relay(key_manager_state, merchant_key_store, new) .await } async fn update_relay( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: hyperswitch_domain_models::relay::Relay, relay_update: hyperswitch_domain_models::relay::RelayUpdate, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { self.diesel_store .update_relay( key_manager_state, merchant_key_store, current_state, relay_update, ) .await } async fn find_relay_by_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, relay_id: &common_utils::id_type::RelayId, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { self.diesel_store .find_relay_by_id(key_manager_state, merchant_key_store, relay_id) .await } async fn find_relay_by_profile_id_connector_reference_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, connector_reference_id: &str, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { self.diesel_store .find_relay_by_profile_id_connector_reference_id( key_manager_state, merchant_key_store, profile_id, connector_reference_id, ) .await } }
2,050
1,453
hyperswitch
crates/router/src/db/user.rs
.rs
use diesel_models::user as storage; use error_stack::report; use masking::Secret; use router_env::{instrument, tracing}; use super::{domain, MockDb}; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; pub mod sample_data; pub mod theme; #[async_trait::async_trait] pub trait UserInterface { async fn insert_user( &self, user_data: storage::UserNew, ) -> CustomResult<storage::User, errors::StorageError>; async fn find_user_by_email( &self, user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError>; async fn find_user_by_id( &self, user_id: &str, ) -> CustomResult<storage::User, errors::StorageError>; async fn update_user_by_user_id( &self, user_id: &str, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError>; async fn update_user_by_email( &self, user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError>; async fn delete_user_by_user_id( &self, user_id: &str, ) -> CustomResult<bool, errors::StorageError>; async fn find_users_by_user_ids( &self, user_ids: Vec<String>, ) -> CustomResult<Vec<storage::User>, errors::StorageError>; } #[async_trait::async_trait] impl UserInterface for Store { #[instrument(skip_all)] async fn insert_user( &self, user_data: storage::UserNew, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; user_data .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_user_by_email( &self, user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::User::find_by_user_email(&conn, user_email.get_inner()) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_user_by_id( &self, user_id: &str, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::User::find_by_user_id(&conn, user_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_user_by_user_id( &self, user_id: &str, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::User::update_by_user_id(&conn, user_id, user) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_user_by_email( &self, user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::User::update_by_user_email(&conn, user_email.get_inner(), user) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_user_by_user_id( &self, user_id: &str, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::User::delete_by_user_id(&conn, user_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_users_by_user_ids( &self, user_ids: Vec<String>, ) -> CustomResult<Vec<storage::User>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::User::find_users_by_user_ids(&conn, user_ids) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl UserInterface for MockDb { async fn insert_user( &self, user_data: storage::UserNew, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; if users .iter() .any(|user| user.email == user_data.email || user.user_id == user_data.user_id) { Err(errors::StorageError::DuplicateValue { entity: "email or user_id", key: None, })? } let time_now = common_utils::date_time::now(); let user = storage::User { user_id: user_data.user_id, email: user_data.email, name: user_data.name, password: user_data.password, is_verified: user_data.is_verified, created_at: user_data.created_at.unwrap_or(time_now), last_modified_at: user_data.created_at.unwrap_or(time_now), totp_status: user_data.totp_status, totp_secret: user_data.totp_secret, totp_recovery_codes: user_data.totp_recovery_codes, last_password_modified_at: user_data.last_password_modified_at, }; users.push(user.clone()); Ok(user) } async fn find_user_by_email( &self, user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { let users = self.users.lock().await; users .iter() .find(|user| user.email.eq(user_email.get_inner())) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No user available for email = {user_email:?}" )) .into(), ) } async fn find_user_by_id( &self, user_id: &str, ) -> CustomResult<storage::User, errors::StorageError> { let users = self.users.lock().await; users .iter() .find(|user| user.user_id == user_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id}" )) .into(), ) } async fn update_user_by_user_id( &self, user_id: &str, update_user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; users .iter_mut() .find(|user| user.user_id == user_id) .map(|user| { *user = match &update_user { storage::UserUpdate::VerifyUser => storage::User { is_verified: true, ..user.to_owned() }, storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User { name: name.clone().map(Secret::new).unwrap_or(user.name.clone()), is_verified: is_verified.unwrap_or(user.is_verified), ..user.to_owned() }, storage::UserUpdate::TotpUpdate { totp_status, totp_secret, totp_recovery_codes, } => storage::User { totp_status: totp_status.unwrap_or(user.totp_status), totp_secret: totp_secret.clone().or(user.totp_secret.clone()), totp_recovery_codes: totp_recovery_codes .clone() .or(user.totp_recovery_codes.clone()), ..user.to_owned() }, storage::UserUpdate::PasswordUpdate { password } => storage::User { password: Some(password.clone()), last_password_modified_at: Some(common_utils::date_time::now()), ..user.to_owned() }, }; user.to_owned() }) .ok_or( errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id}" )) .into(), ) } async fn update_user_by_email( &self, user_email: &domain::UserEmail, update_user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; users .iter_mut() .find(|user| user.email.eq(user_email.get_inner())) .map(|user| { *user = match &update_user { storage::UserUpdate::VerifyUser => storage::User { is_verified: true, ..user.to_owned() }, storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User { name: name.clone().map(Secret::new).unwrap_or(user.name.clone()), is_verified: is_verified.unwrap_or(user.is_verified), ..user.to_owned() }, storage::UserUpdate::TotpUpdate { totp_status, totp_secret, totp_recovery_codes, } => storage::User { totp_status: totp_status.unwrap_or(user.totp_status), totp_secret: totp_secret.clone().or(user.totp_secret.clone()), totp_recovery_codes: totp_recovery_codes .clone() .or(user.totp_recovery_codes.clone()), ..user.to_owned() }, storage::UserUpdate::PasswordUpdate { password } => storage::User { password: Some(password.clone()), last_password_modified_at: Some(common_utils::date_time::now()), ..user.to_owned() }, }; user.to_owned() }) .ok_or( errors::StorageError::ValueNotFound(format!( "No user available for user_email = {user_email:?}" )) .into(), ) } async fn delete_user_by_user_id( &self, user_id: &str, ) -> CustomResult<bool, errors::StorageError> { let mut users = self.users.lock().await; let user_index = users .iter() .position(|user| user.user_id == user_id) .ok_or(errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id}" )))?; users.remove(user_index); Ok(true) } async fn find_users_by_user_ids( &self, _user_ids: Vec<String>, ) -> CustomResult<Vec<storage::User>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } }
2,410
1,454
hyperswitch
crates/router/src/db/health_check.rs
.rs
use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; use diesel_models::ConfigNew; use error_stack::ResultExt; use router_env::{instrument, logger, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait HealthCheckDbInterface { async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError>; } #[async_trait::async_trait] impl HealthCheckDbInterface for Store { #[instrument(skip_all)] async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { let conn = connection::pg_connection_write(self) .await .change_context(errors::HealthCheckDBError::DBError)?; conn.transaction_async(|conn| async move { let query = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1")); let _x: i32 = query.get_result_async(&conn).await.map_err(|err| { logger::error!(read_err=?err,"Error while reading element in the database"); errors::HealthCheckDBError::DBReadError })?; logger::debug!("Database read was successful"); let config = ConfigNew { key: "test_key".to_string(), config: "test_value".to_string(), }; config.insert(&conn).await.map_err(|err| { logger::error!(write_err=?err,"Error while writing to database"); errors::HealthCheckDBError::DBWriteError })?; logger::debug!("Database write was successful"); storage::Config::delete_by_key(&conn, "test_key") .await .map_err(|err| { logger::error!(delete_err=?err,"Error while deleting element in the database"); errors::HealthCheckDBError::DBDeleteError })?; logger::debug!("Database delete was successful"); Ok::<_, errors::HealthCheckDBError>(()) }) .await?; Ok(()) } } #[async_trait::async_trait] impl HealthCheckDbInterface for MockDb { async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { Ok(()) } }
499
1,455
hyperswitch
crates/router/src/db/address.rs
.rs
use common_utils::{id_type, types::keymanager::KeyManagerState}; use diesel_models::{address::AddressUpdateInternal, enums::MerchantStorageScheme}; use error_stack::ResultExt; use super::MockDb; use crate::{ core::errors::{self, CustomResult}, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage as storage_types, }, }; #[async_trait::async_trait] pub trait AddressInterface where domain::Address: Conversion<DstType = storage_types::Address, NewDstType = storage_types::AddressNew>, { async fn update_address( &self, state: &KeyManagerState, address_id: String, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError>; async fn update_address_for_payments( &self, state: &KeyManagerState, this: domain::PaymentAddress, address: domain::AddressUpdate, payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError>; async fn find_address_by_address_id( &self, state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError>; async fn insert_address_for_payments( &self, state: &KeyManagerState, payment_id: &id_type::PaymentId, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError>; async fn insert_address_for_customers( &self, state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError>; async fn find_address_by_merchant_id_payment_id_address_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError>; async fn update_address_by_merchant_id_customer_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError>; } #[cfg(not(feature = "kv_store"))] mod storage { use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::AddressInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage::{self as storage_types, enums::MerchantStorageScheme}, }, }; #[async_trait::async_trait] impl AddressInterface for Store { #[instrument(skip_all)] async fn find_address_by_address_id( &self, state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Address::find_by_address_id(&conn, address_id) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn find_address_by_merchant_id_payment_id_address_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Address::find_by_merchant_id_payment_id_address_id( &conn, merchant_id, payment_id, address_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn update_address( &self, state: &KeyManagerState, address_id: String, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Address::update_by_address_id(&conn, address_id, address.into()) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn update_address_for_payments( &self, state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, _payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let address = Conversion::convert(this) .await .change_context(errors::StorageError::EncryptionError)?; address .update(&conn, address_update.into()) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn insert_address_for_payments( &self, state: &KeyManagerState, _payment_id: &id_type::PaymentId, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; address .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn insert_address_for_customers( &self, state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; address .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn update_address_by_merchant_id_customer_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Address::update_by_merchant_id_customer_id( &conn, customer_id, merchant_id, address.into(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|addresses| async { let mut output = Vec::with_capacity(addresses.len()); for address in addresses.into_iter() { output.push( address .convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) }) .await } } } #[cfg(feature = "kv_store")] mod storage { use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use diesel_models::{enums::MerchantStorageScheme, AddressUpdateInternal}; use error_stack::{report, ResultExt}; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey, }; use super::AddressInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage::{self as storage_types, kv}, }, utils::db_utils, }; #[async_trait::async_trait] impl AddressInterface for Store { #[instrument(skip_all)] async fn find_address_by_address_id( &self, state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Address::find_by_address_id(&conn, address_id) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn find_address_by_merchant_id_payment_id_address_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Address::find_by_merchant_id_payment_id_address_id( &conn, merchant_id, payment_id, address_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Address>( self, storage_scheme, Op::Find, )) .await; let address = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id, payment_id, }; let field = format!("add_{}", address_id); Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Address>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } }?; address .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn update_address( &self, state: &KeyManagerState, address_id: String, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Address::update_by_address_id(&conn, address_id, address.into()) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn update_address_for_payments( &self, state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let address = Conversion::convert(this) .await .change_context(errors::StorageError::EncryptionError)?; let merchant_id = address.merchant_id.clone(); let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id: &payment_id, }; let field = format!("add_{}", address.address_id); let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Address>( self, storage_scheme, Op::Update(key.clone(), &field, Some(address.updated_by.as_str())), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { address .update(&conn, address_update.into()) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } MerchantStorageScheme::RedisKv => { let updated_address = AddressUpdateInternal::from(address_update.clone()) .create_address(address.clone()); let redis_value = serde_json::to_string(&updated_address) .change_context(errors::StorageError::KVError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::AddressUpdate(Box::new( kv::AddressUpdateMems { orig: address, update_data: address_update.into(), }, ))), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::Hset::<storage_types::Address>( (&field, redis_value), redis_entry, ), key, )) .await .change_context(errors::StorageError::KVError)? .try_into_hset() .change_context(errors::StorageError::KVError)?; updated_address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } } } #[instrument(skip_all)] async fn insert_address_for_payments( &self, state: &KeyManagerState, payment_id: &id_type::PaymentId, address: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let address_new = address .clone() .construct_new() .await .change_context(errors::StorageError::EncryptionError)?; let merchant_id = address_new.merchant_id.clone(); let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Address>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; address_new .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdPaymentId { merchant_id: &merchant_id, payment_id, }; let field = format!("add_{}", &address_new.address_id); let created_address = diesel_models::Address { address_id: address_new.address_id.clone(), city: address_new.city.clone(), country: address_new.country, line1: address_new.line1.clone(), line2: address_new.line2.clone(), line3: address_new.line3.clone(), state: address_new.state.clone(), zip: address_new.zip.clone(), first_name: address_new.first_name.clone(), last_name: address_new.last_name.clone(), phone_number: address_new.phone_number.clone(), country_code: address_new.country_code.clone(), created_at: address_new.created_at, modified_at: address_new.modified_at, customer_id: address_new.customer_id.clone(), merchant_id: address_new.merchant_id.clone(), payment_id: address_new.payment_id.clone(), updated_by: storage_scheme.to_string(), email: address_new.email.clone(), }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Address(Box::new(address_new))), }, }; match Box::pin(kv_wrapper::<diesel_models::Address, _, _>( self, KvOperation::HSetNx::<diesel_models::Address>( &field, &created_address, redis_entry, ), key, )) .await .change_context(errors::StorageError::KVError)? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "address", key: Some(created_address.address_id), } .into()), Ok(HsetnxReply::KeySet) => Ok(created_address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } #[instrument(skip_all)] async fn insert_address_for_customers( &self, state: &KeyManagerState, address: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; address .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|address| async { address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[instrument(skip_all)] async fn update_address_by_merchant_id_customer_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, address: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Address::update_by_merchant_id_customer_id( &conn, customer_id, merchant_id, address.into(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|addresses| async { let mut output = Vec::with_capacity(addresses.len()); for address in addresses.into_iter() { output.push( address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) }) .await } } } #[async_trait::async_trait] impl AddressInterface for MockDb { async fn find_address_by_address_id( &self, state: &KeyManagerState, address_id: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { match self .addresses .lock() .await .iter() .find(|address| address.address_id == address_id) { Some(address) => address .clone() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError), None => { return Err( errors::StorageError::ValueNotFound("address not found".to_string()).into(), ) } } } async fn find_address_by_merchant_id_payment_id_address_id( &self, state: &KeyManagerState, _merchant_id: &id_type::MerchantId, _payment_id: &id_type::PaymentId, address_id: &str, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { match self .addresses .lock() .await .iter() .find(|address| address.address_id == address_id) { Some(address) => address .clone() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError), None => { return Err( errors::StorageError::ValueNotFound("address not found".to_string()).into(), ) } } } async fn update_address( &self, state: &KeyManagerState, address_id: String, address_update: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let updated_addr = self .addresses .lock() .await .iter_mut() .find(|address| address.address_id == address_id) .map(|a| { let address_updated = AddressUpdateInternal::from(address_update).create_address(a.clone()); *a = address_updated.clone(); address_updated }); match updated_addr { Some(address_updated) => address_updated .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError), None => Err(errors::StorageError::ValueNotFound( "cannot find address to update".to_string(), ) .into()), } } async fn update_address_for_payments( &self, state: &KeyManagerState, this: domain::PaymentAddress, address_update: domain::AddressUpdate, _payment_id: id_type::PaymentId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let updated_addr = self .addresses .lock() .await .iter_mut() .find(|address| address.address_id == this.address.address_id) .map(|a| { let address_updated = AddressUpdateInternal::from(address_update).create_address(a.clone()); *a = address_updated.clone(); address_updated }); match updated_addr { Some(address_updated) => address_updated .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError), None => Err(errors::StorageError::ValueNotFound( "cannot find address to update".to_string(), ) .into()), } } async fn insert_address_for_payments( &self, state: &KeyManagerState, _payment_id: &id_type::PaymentId, address_new: domain::PaymentAddress, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<domain::PaymentAddress, errors::StorageError> { let mut addresses = self.addresses.lock().await; let address = Conversion::convert(address_new) .await .change_context(errors::StorageError::EncryptionError)?; addresses.push(address.clone()); address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn insert_address_for_customers( &self, state: &KeyManagerState, address_new: domain::CustomerAddress, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Address, errors::StorageError> { let mut addresses = self.addresses.lock().await; let address = Conversion::convert(address_new) .await .change_context(errors::StorageError::EncryptionError)?; addresses.push(address.clone()); address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn update_address_by_merchant_id_customer_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, address_update: storage_types::AddressUpdate, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Address>, errors::StorageError> { let updated_addr = self .addresses .lock() .await .iter_mut() .find(|address| { address.customer_id.as_ref() == Some(customer_id) && address.merchant_id == *merchant_id }) .map(|a| { let address_updated = AddressUpdateInternal::from(address_update).create_address(a.clone()); *a = address_updated.clone(); address_updated }); match updated_addr { Some(address) => { let address: domain::Address = address .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; Ok(vec![address]) } None => { Err(errors::StorageError::ValueNotFound("address not found".to_string()).into()) } } } }
6,486
1,456
hyperswitch
crates/router/src/db/callback_mapper.rs
.rs
use error_stack::report; use hyperswitch_domain_models::callback_mapper as domain; use router_env::{instrument, tracing}; use storage_impl::DataModelExt; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait CallbackMapperInterface { async fn insert_call_back_mapper( &self, call_back_mapper: domain::CallbackMapper, ) -> CustomResult<domain::CallbackMapper, errors::StorageError>; async fn find_call_back_mapper_by_id( &self, id: &str, ) -> CustomResult<domain::CallbackMapper, errors::StorageError>; } #[async_trait::async_trait] impl CallbackMapperInterface for Store { #[instrument(skip_all)] async fn insert_call_back_mapper( &self, call_back_mapper: domain::CallbackMapper, ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; call_back_mapper .to_storage_model() .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .map(domain::CallbackMapper::from_storage_model) } #[instrument(skip_all)] async fn find_call_back_mapper_by_id( &self, id: &str, ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::CallbackMapper::find_by_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) .map(domain::CallbackMapper::from_storage_model) } }
378
1,457
hyperswitch
crates/router/src/db/locker_mock_up.rs
.rs
use error_stack::report; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; #[async_trait::async_trait] pub trait LockerMockUpInterface { async fn find_locker_by_card_id( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError>; async fn insert_locker_mock_up( &self, new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError>; async fn delete_locker_mock_up( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError>; } #[async_trait::async_trait] impl LockerMockUpInterface for Store { #[instrument(skip_all)] async fn find_locker_by_card_id( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::LockerMockUp::find_by_card_id(&conn, card_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_locker_mock_up( &self, new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_locker_mock_up( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::LockerMockUp::delete_by_card_id(&conn, card_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl LockerMockUpInterface for MockDb { async fn find_locker_by_card_id( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { self.lockers .lock() .await .iter() .find(|l| l.card_id == card_id) .cloned() .ok_or(errors::StorageError::MockDbError.into()) } async fn insert_locker_mock_up( &self, new: storage::LockerMockUpNew, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let mut locked_lockers = self.lockers.lock().await; if locked_lockers.iter().any(|l| l.card_id == new.card_id) { Err(errors::StorageError::MockDbError)?; } let created_locker = storage::LockerMockUp { card_id: new.card_id, external_id: new.external_id, card_fingerprint: new.card_fingerprint, card_global_fingerprint: new.card_global_fingerprint, merchant_id: new.merchant_id, card_number: new.card_number, card_exp_year: new.card_exp_year, card_exp_month: new.card_exp_month, name_on_card: new.name_on_card, nickname: None, customer_id: new.customer_id, duplicate: None, card_cvc: new.card_cvc, payment_method_id: new.payment_method_id, enc_card_data: new.enc_card_data, }; locked_lockers.push(created_locker.clone()); Ok(created_locker) } async fn delete_locker_mock_up( &self, card_id: &str, ) -> CustomResult<storage::LockerMockUp, errors::StorageError> { let mut locked_lockers = self.lockers.lock().await; let position = locked_lockers .iter() .position(|l| l.card_id == card_id) .ok_or(errors::StorageError::MockDbError)?; Ok(locked_lockers.remove(position)) } } #[cfg(test)] mod tests { #[allow(clippy::unwrap_used)] mod mockdb_locker_mock_up_interface { use common_utils::{generate_customer_id_of_default_length, id_type}; use crate::{ db::{locker_mock_up::LockerMockUpInterface, MockDb}, types::storage, }; pub struct LockerMockUpIds { card_id: String, external_id: String, merchant_id: id_type::MerchantId, customer_id: id_type::CustomerId, } fn create_locker_mock_up_new(locker_ids: LockerMockUpIds) -> storage::LockerMockUpNew { storage::LockerMockUpNew { card_id: locker_ids.card_id, external_id: locker_ids.external_id, card_fingerprint: "card_fingerprint".into(), card_global_fingerprint: "card_global_fingerprint".into(), merchant_id: locker_ids.merchant_id, card_number: "1234123412341234".into(), card_exp_year: "2023".into(), card_exp_month: "06".into(), name_on_card: Some("name_on_card".into()), card_cvc: Some("123".into()), payment_method_id: Some("payment_method_id".into()), customer_id: Some(locker_ids.customer_id), nickname: Some("card_holder_nickname".into()), enc_card_data: Some("enc_card_data".into()), } } #[tokio::test] async fn find_locker_by_card_id() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_locker = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_1".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await .unwrap(); let _ = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_2".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await; let found_locker = mockdb.find_locker_by_card_id("card_1").await.unwrap(); assert_eq!(created_locker, found_locker) } #[tokio::test] async fn insert_locker_mock_up() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_locker = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_1".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await .unwrap(); let found_locker = mockdb .lockers .lock() .await .iter() .find(|l| l.card_id == "card_1") .cloned(); assert!(found_locker.is_some()); assert_eq!(created_locker, found_locker.unwrap()) } #[tokio::test] async fn delete_locker_mock_up() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_locker = mockdb .insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds { card_id: "card_1".into(), external_id: "external_1".into(), merchant_id: id_type::MerchantId::default(), customer_id: generate_customer_id_of_default_length(), })) .await .unwrap(); let deleted_locker = mockdb.delete_locker_mock_up("card_1").await.unwrap(); assert_eq!(created_locker, deleted_locker); let exist = mockdb .lockers .lock() .await .iter() .any(|l| l.card_id == "card_1"); assert!(!exist) } } }
1,947
1,458
hyperswitch
crates/router/src/db/routing_algorithm.rs
.rs
use diesel_models::routing_algorithm as routing_storage; use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::mock_db::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; type StorageResult<T> = CustomResult<T, errors::StorageError>; #[async_trait::async_trait] pub trait RoutingAlgorithmInterface { async fn insert_routing_algorithm( &self, routing_algorithm: routing_storage::RoutingAlgorithm, ) -> StorageResult<routing_storage::RoutingAlgorithm>; async fn find_routing_algorithm_by_profile_id_algorithm_id( &self, profile_id: &common_utils::id_type::ProfileId, algorithm_id: &common_utils::id_type::RoutingId, ) -> StorageResult<routing_storage::RoutingAlgorithm>; async fn find_routing_algorithm_by_algorithm_id_merchant_id( &self, algorithm_id: &common_utils::id_type::RoutingId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<routing_storage::RoutingAlgorithm>; async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id( &self, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<routing_storage::RoutingProfileMetadata>; async fn list_routing_algorithm_metadata_by_profile_id( &self, profile_id: &common_utils::id_type::ProfileId, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>; async fn list_routing_algorithm_metadata_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>; async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type( &self, merchant_id: &common_utils::id_type::MerchantId, transaction_type: &common_enums::TransactionType, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>; } #[async_trait::async_trait] impl RoutingAlgorithmInterface for Store { #[instrument(skip_all)] async fn insert_routing_algorithm( &self, routing_algorithm: routing_storage::RoutingAlgorithm, ) -> StorageResult<routing_storage::RoutingAlgorithm> { let conn = connection::pg_connection_write(self).await?; routing_algorithm .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_routing_algorithm_by_profile_id_algorithm_id( &self, profile_id: &common_utils::id_type::ProfileId, algorithm_id: &common_utils::id_type::RoutingId, ) -> StorageResult<routing_storage::RoutingAlgorithm> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::find_by_algorithm_id_profile_id( &conn, algorithm_id, profile_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_routing_algorithm_by_algorithm_id_merchant_id( &self, algorithm_id: &common_utils::id_type::RoutingId, merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<routing_storage::RoutingAlgorithm> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::find_by_algorithm_id_merchant_id( &conn, algorithm_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id( &self, algorithm_id: &common_utils::id_type::RoutingId, profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<routing_storage::RoutingProfileMetadata> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::find_metadata_by_algorithm_id_profile_id( &conn, algorithm_id, profile_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_routing_algorithm_metadata_by_profile_id( &self, profile_id: &common_utils::id_type::ProfileId, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::list_metadata_by_profile_id( &conn, profile_id, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_routing_algorithm_metadata_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::list_metadata_by_merchant_id( &conn, merchant_id, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type( &self, merchant_id: &common_utils::id_type::MerchantId, transaction_type: &common_enums::TransactionType, limit: i64, offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { let conn = connection::pg_connection_write(self).await?; routing_storage::RoutingAlgorithm::list_metadata_by_merchant_id_transaction_type( &conn, merchant_id, transaction_type, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl RoutingAlgorithmInterface for MockDb { async fn insert_routing_algorithm( &self, _routing_algorithm: routing_storage::RoutingAlgorithm, ) -> StorageResult<routing_storage::RoutingAlgorithm> { Err(errors::StorageError::MockDbError)? } async fn find_routing_algorithm_by_profile_id_algorithm_id( &self, _profile_id: &common_utils::id_type::ProfileId, _algorithm_id: &common_utils::id_type::RoutingId, ) -> StorageResult<routing_storage::RoutingAlgorithm> { Err(errors::StorageError::MockDbError)? } async fn find_routing_algorithm_by_algorithm_id_merchant_id( &self, _algorithm_id: &common_utils::id_type::RoutingId, _merchant_id: &common_utils::id_type::MerchantId, ) -> StorageResult<routing_storage::RoutingAlgorithm> { Err(errors::StorageError::MockDbError)? } async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id( &self, _algorithm_id: &common_utils::id_type::RoutingId, _profile_id: &common_utils::id_type::ProfileId, ) -> StorageResult<routing_storage::RoutingProfileMetadata> { Err(errors::StorageError::MockDbError)? } async fn list_routing_algorithm_metadata_by_profile_id( &self, _profile_id: &common_utils::id_type::ProfileId, _limit: i64, _offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { Err(errors::StorageError::MockDbError)? } async fn list_routing_algorithm_metadata_by_merchant_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _limit: i64, _offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { Err(errors::StorageError::MockDbError)? } async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type( &self, _merchant_id: &common_utils::id_type::MerchantId, _transaction_type: &common_enums::TransactionType, _limit: i64, _offset: i64, ) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> { Err(errors::StorageError::MockDbError)? } }
1,889
1,459
hyperswitch
crates/router/src/db/dynamic_routing_stats.rs
.rs
use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::MockDb; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, types::storage, }; #[async_trait::async_trait] pub trait DynamicRoutingStatsInterface { async fn insert_dynamic_routing_stat_entry( &self, dynamic_routing_stat_new: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>; async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError>; async fn update_dynamic_routing_stats( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, data: storage::DynamicRoutingStatsUpdate, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>; } #[async_trait::async_trait] impl DynamicRoutingStatsInterface for Store { #[instrument(skip_all)] async fn insert_dynamic_routing_stat_entry( &self, dynamic_routing_stat: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; dynamic_routing_stat .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::DynamicRoutingStats::find_optional_by_attempt_id_merchant_id( &conn, attempt_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn update_dynamic_routing_stats( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, data: storage::DynamicRoutingStatsUpdate, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::DynamicRoutingStats::update(&conn, attempt_id, merchant_id, data) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl DynamicRoutingStatsInterface for MockDb { #[instrument(skip_all)] async fn insert_dynamic_routing_stat_entry( &self, _dynamic_routing_stat: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( &self, _attempt_id: String, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_dynamic_routing_stats( &self, _attempt_id: String, _merchant_id: &common_utils::id_type::MerchantId, _data: storage::DynamicRoutingStatsUpdate, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl DynamicRoutingStatsInterface for KafkaStore { #[instrument(skip_all)] async fn insert_dynamic_routing_stat_entry( &self, dynamic_routing_stat: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { self.diesel_store .insert_dynamic_routing_stat_entry(dynamic_routing_stat) .await } async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> { self.diesel_store .find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(attempt_id, merchant_id) .await } async fn update_dynamic_routing_stats( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, data: storage::DynamicRoutingStatsUpdate, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { self.diesel_store .update_dynamic_routing_stats(attempt_id, merchant_id, data) .await } }
1,079
1,460
hyperswitch
crates/router/src/db/payment_method_session.rs
.rs
#[cfg(feature = "v2")] use crate::core::errors::{self, CustomResult}; use crate::db::MockDb; #[cfg(feature = "v2")] #[async_trait::async_trait] pub trait PaymentMethodsSessionInterface { async fn insert_payment_methods_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, validity: i64, ) -> CustomResult<(), errors::StorageError>; async fn update_payment_method_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &common_utils::id_type::GlobalPaymentMethodSessionId, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum, current_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, >; async fn get_payment_methods_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &common_utils::id_type::GlobalPaymentMethodSessionId, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, >; } #[cfg(feature = "v1")] pub trait PaymentMethodsSessionInterface {} #[cfg(feature = "v1")] 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 super::PaymentMethodsSessionInterface; use crate::{ core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] impl PaymentMethodsSessionInterface for Store { #[instrument(skip_all)] async fn insert_payment_methods_session( &self, _state: &common_utils::types::keymanager::KeyManagerState, _key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, validity_in_seconds: i64, ) -> CustomResult<(), errors::StorageError> { let redis_key = payment_methods_session.id.get_redis_key(); let db_model = payment_methods_session .construct_new() .await .change_context(errors::StorageError::EncryptionError)?; let redis_connection = self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)?; redis_connection .serialize_and_set_key_with_expiry(&redis_key.into(), db_model, validity_in_seconds) .await .change_context(errors::StorageError::KVError) .attach_printable("Failed to insert payment methods session to redis") } #[instrument(skip_all)] async fn get_payment_methods_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &common_utils::id_type::GlobalPaymentMethodSessionId, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, > { let redis_key = id.get_redis_key(); let redis_connection = self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)?; let db_model = redis_connection .get_and_deserialize_key::<diesel_models::payment_methods_session::PaymentMethodSession>(&redis_key.into(), "PaymentMethodSession") .await .change_context(errors::StorageError::KVError)?; let key_manager_identifier = common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ); db_model .convert(state, &key_store.key, key_manager_identifier) .await .change_context(errors::StorageError::DecryptionError) .attach_printable("Failed to decrypt payment methods session") } #[instrument(skip_all)] async fn update_payment_method_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, session_id: &common_utils::id_type::GlobalPaymentMethodSessionId, update_request: hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum, current_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, > { let redis_key = session_id.get_redis_key(); let internal_obj = hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateInternal::from(update_request); let update_state = current_session.apply_changeset(internal_obj); let db_model = update_state .construct_new() .await .change_context(errors::StorageError::EncryptionError)?; let redis_connection = self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)?; redis_connection .serialize_and_set_key_without_modifying_ttl(&redis_key.into(), db_model.clone()) .await .change_context(errors::StorageError::KVError) .attach_printable("Failed to insert payment methods session to redis"); let key_manager_identifier = common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ); db_model .convert(state, &key_store.key, key_manager_identifier) .await .change_context(errors::StorageError::DecryptionError) .attach_printable("Failed to decrypt payment methods session") } } } #[cfg(feature = "v2")] #[async_trait::async_trait] impl PaymentMethodsSessionInterface for MockDb { async fn insert_payment_methods_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, validity_in_seconds: i64, ) -> CustomResult<(), errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_payment_method_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &common_utils::id_type::GlobalPaymentMethodSessionId, payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum, current_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, > { Err(errors::StorageError::MockDbError)? } #[cfg(feature = "v2")] async fn get_payment_methods_session( &self, state: &common_utils::types::keymanager::KeyManagerState, key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore, id: &common_utils::id_type::GlobalPaymentMethodSessionId, ) -> CustomResult< hyperswitch_domain_models::payment_methods::PaymentMethodSession, errors::StorageError, > { Err(errors::StorageError::MockDbError)? } } #[cfg(feature = "v1")] #[async_trait::async_trait] impl PaymentMethodsSessionInterface for MockDb {}
1,743
1,461
hyperswitch
crates/router/src/db/dispute.rs
.rs
use std::collections::HashMap; use error_stack::report; use hyperswitch_domain_models::disputes; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage::{self, DisputeDbExt}, }; #[async_trait::async_trait] pub trait DisputeInterface { async fn insert_dispute( &self, dispute: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError>; async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult<Option<storage::Dispute>, errors::StorageError>; async fn find_dispute_by_merchant_id_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_id: &str, ) -> CustomResult<storage::Dispute, errors::StorageError>; async fn find_disputes_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError>; async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError>; async fn update_dispute( &self, this: storage::Dispute, dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError>; async fn get_dispute_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::StorageError>; } #[async_trait::async_trait] impl DisputeInterface for Store { #[instrument(skip_all)] async fn insert_dispute( &self, dispute: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; dispute .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult<Option<storage::Dispute>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::find_by_merchant_id_payment_id_connector_dispute_id( &conn, merchant_id, payment_id, connector_dispute_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_dispute_by_merchant_id_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_id: &str, ) -> CustomResult<storage::Dispute, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::find_by_merchant_id_dispute_id(&conn, merchant_id, dispute_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_disputes_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::filter_by_constraints(&conn, merchant_id, dispute_constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_dispute( &self, this: storage::Dispute, dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update(&conn, dispute) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn get_dispute_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::get_dispute_status_with_count( &conn, merchant_id, profile_id_list, time_range, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl DisputeInterface for MockDb { async fn insert_dispute( &self, dispute: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError> { let evidence = dispute.evidence.ok_or(errors::StorageError::MockDbError)?; let mut locked_disputes = self.disputes.lock().await; if locked_disputes .iter() .any(|d| d.dispute_id == dispute.dispute_id) { Err(errors::StorageError::MockDbError)?; } let now = common_utils::date_time::now(); let new_dispute = storage::Dispute { dispute_id: dispute.dispute_id, amount: dispute.amount, currency: dispute.currency, dispute_stage: dispute.dispute_stage, dispute_status: dispute.dispute_status, payment_id: dispute.payment_id, attempt_id: dispute.attempt_id, merchant_id: dispute.merchant_id, connector_status: dispute.connector_status, connector_dispute_id: dispute.connector_dispute_id, connector_reason: dispute.connector_reason, connector_reason_code: dispute.connector_reason_code, challenge_required_by: dispute.challenge_required_by, connector_created_at: dispute.connector_created_at, connector_updated_at: dispute.connector_updated_at, created_at: now, modified_at: now, connector: dispute.connector, profile_id: dispute.profile_id, evidence, merchant_connector_id: dispute.merchant_connector_id, dispute_amount: dispute.dispute_amount, organization_id: dispute.organization_id, dispute_currency: dispute.dispute_currency, }; locked_disputes.push(new_dispute.clone()); Ok(new_dispute) } async fn find_by_merchant_id_payment_id_connector_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, connector_dispute_id: &str, ) -> CustomResult<Option<storage::Dispute>, errors::StorageError> { Ok(self .disputes .lock() .await .iter() .find(|d| { d.merchant_id == *merchant_id && d.payment_id == *payment_id && d.connector_dispute_id == connector_dispute_id }) .cloned()) } async fn find_dispute_by_merchant_id_dispute_id( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_id: &str, ) -> CustomResult<storage::Dispute, errors::StorageError> { let locked_disputes = self.disputes.lock().await; locked_disputes .iter() .find(|d| d.merchant_id == *merchant_id && d.dispute_id == dispute_id) .cloned() .ok_or(errors::StorageError::ValueNotFound(format!("No dispute available for merchant_id = {merchant_id:?} and dispute_id = {dispute_id}")) .into()) } async fn find_disputes_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { let locked_disputes = self.disputes.lock().await; let limit_usize = dispute_constraints .limit .unwrap_or(u32::MAX) .try_into() .unwrap_or(usize::MAX); let offset_usize = dispute_constraints .offset .unwrap_or(0) .try_into() .unwrap_or(usize::MIN); let filtered_disputes: Vec<storage::Dispute> = locked_disputes .iter() .filter(|dispute| { dispute.merchant_id == *merchant_id && dispute_constraints .dispute_id .as_ref() .map_or(true, |id| &dispute.dispute_id == id) && dispute_constraints .payment_id .as_ref() .map_or(true, |id| &dispute.payment_id == id) && dispute_constraints .profile_id .as_ref() .map_or(true, |profile_ids| { dispute .profile_id .as_ref() .map_or(true, |id| profile_ids.contains(id)) }) && dispute_constraints .dispute_status .as_ref() .map_or(true, |statuses| statuses.contains(&dispute.dispute_status)) && dispute_constraints .dispute_stage .as_ref() .map_or(true, |stages| stages.contains(&dispute.dispute_stage)) && dispute_constraints.reason.as_ref().map_or(true, |reason| { dispute .connector_reason .as_ref() .map_or(true, |d_reason| d_reason == reason) }) && dispute_constraints .connector .as_ref() .map_or(true, |connectors| { connectors .iter() .any(|connector| dispute.connector.as_str() == *connector) }) && dispute_constraints .merchant_connector_id .as_ref() .map_or(true, |id| { dispute.merchant_connector_id.as_ref() == Some(id) }) && dispute_constraints .currency .as_ref() .map_or(true, |currencies| { currencies.iter().any(|currency| { dispute .dispute_currency .map(|dispute_currency| &dispute_currency == currency) .unwrap_or(dispute.currency.as_str() == currency.to_string()) }) }) && dispute_constraints .time_range .as_ref() .map_or(true, |range| { let dispute_time = dispute.created_at; dispute_time >= range.start_time && range .end_time .map_or(true, |end_time| dispute_time <= end_time) }) }) .skip(offset_usize) .take(limit_usize) .cloned() .collect(); Ok(filtered_disputes) } async fn find_disputes_by_merchant_id_payment_id( &self, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { let locked_disputes = self.disputes.lock().await; Ok(locked_disputes .iter() .filter(|d| d.merchant_id == *merchant_id && d.payment_id == *payment_id) .cloned() .collect()) } async fn update_dispute( &self, this: storage::Dispute, dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError> { let mut locked_disputes = self.disputes.lock().await; let dispute_to_update = locked_disputes .iter_mut() .find(|d| d.dispute_id == this.dispute_id) .ok_or(errors::StorageError::MockDbError)?; let now = common_utils::date_time::now(); match dispute { storage::DisputeUpdate::Update { dispute_stage, dispute_status, connector_status, connector_reason, connector_reason_code, challenge_required_by, connector_updated_at, } => { if connector_reason.is_some() { dispute_to_update.connector_reason = connector_reason; } if connector_reason_code.is_some() { dispute_to_update.connector_reason_code = connector_reason_code; } if challenge_required_by.is_some() { dispute_to_update.challenge_required_by = challenge_required_by; } if connector_updated_at.is_some() { dispute_to_update.connector_updated_at = connector_updated_at; } dispute_to_update.dispute_stage = dispute_stage; dispute_to_update.dispute_status = dispute_status; dispute_to_update.connector_status = connector_status; } storage::DisputeUpdate::StatusUpdate { dispute_status, connector_status, } => { if let Some(status) = connector_status { dispute_to_update.connector_status = status; } dispute_to_update.dispute_status = dispute_status; } storage::DisputeUpdate::EvidenceUpdate { evidence } => { dispute_to_update.evidence = evidence; } } dispute_to_update.modified_at = now; Ok(dispute_to_update.clone()) } async fn get_dispute_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { let locked_disputes = self.disputes.lock().await; let filtered_disputes_data = locked_disputes .iter() .filter(|d| { d.merchant_id == *merchant_id && d.created_at >= time_range.start_time && time_range .end_time .as_ref() .map(|received_end_time| received_end_time >= &d.created_at) .unwrap_or(true) && profile_id_list .as_ref() .zip(d.profile_id.as_ref()) .map(|(received_profile_list, received_profile_id)| { received_profile_list.contains(received_profile_id) }) .unwrap_or(true) }) .cloned() .collect::<Vec<storage::Dispute>>(); Ok(filtered_disputes_data .into_iter() .fold( HashMap::new(), |mut acc: HashMap<common_enums::DisputeStatus, i64>, value| { acc.entry(value.dispute_status) .and_modify(|value| *value += 1) .or_insert(1); acc }, ) .into_iter() .collect::<Vec<(common_enums::DisputeStatus, i64)>>()) } } #[cfg(test)] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used)] mod mockdb_dispute_interface { use std::borrow::Cow; use diesel_models::{ dispute::DisputeNew, enums::{DisputeStage, DisputeStatus}, }; use hyperswitch_domain_models::disputes::DisputeListConstraints; use masking::Secret; use redis_interface::RedisSettings; use serde_json::Value; use time::macros::datetime; use crate::db::{dispute::DisputeInterface, MockDb}; pub struct DisputeNewIds { dispute_id: String, payment_id: common_utils::id_type::PaymentId, attempt_id: String, merchant_id: common_utils::id_type::MerchantId, connector_dispute_id: String, } fn create_dispute_new(dispute_ids: DisputeNewIds) -> DisputeNew { DisputeNew { dispute_id: dispute_ids.dispute_id, amount: "amount".into(), currency: "currency".into(), dispute_stage: DisputeStage::Dispute, dispute_status: DisputeStatus::DisputeOpened, payment_id: dispute_ids.payment_id, attempt_id: dispute_ids.attempt_id, merchant_id: dispute_ids.merchant_id, connector_status: "connector_status".into(), connector_dispute_id: dispute_ids.connector_dispute_id, connector_reason: Some("connector_reason".into()), connector_reason_code: Some("connector_reason_code".into()), challenge_required_by: Some(datetime!(2019-01-01 0:00)), connector_created_at: Some(datetime!(2019-01-02 0:00)), connector_updated_at: Some(datetime!(2019-01-03 0:00)), connector: "connector".into(), evidence: Some(Secret::from(Value::String("evidence".into()))), profile_id: Some(common_utils::generate_profile_id_of_default_length()), merchant_connector_id: None, dispute_amount: 1040, organization_id: common_utils::id_type::OrganizationId::default(), dispute_currency: Some(common_enums::Currency::default()), } } #[tokio::test] async fn test_insert_dispute() { let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create a mock DB"); let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed( "payment_1", )) .unwrap(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let found_dispute = mockdb .disputes .lock() .await .iter() .find(|d| d.dispute_id == created_dispute.dispute_id) .cloned(); assert!(found_dispute.is_some()); assert_eq!(created_dispute, found_dispute.unwrap()); } #[tokio::test] async fn test_find_by_merchant_id_payment_id_connector_dispute_id() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed( "payment_1", )) .unwrap(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let _ = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed( "payment_1", )) .unwrap(), connector_dispute_id: "connector_dispute_2".into(), })) .await .unwrap(); let found_dispute = mockdb .find_by_merchant_id_payment_id_connector_dispute_id( &merchant_id, &common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")) .unwrap(), "connector_dispute_1", ) .await .unwrap(); assert!(found_dispute.is_some()); assert_eq!(created_dispute, found_dispute.unwrap()); } #[tokio::test] async fn test_find_dispute_by_merchant_id_dispute_id() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let _ = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let found_dispute = mockdb .find_dispute_by_merchant_id_dispute_id(&merchant_id, "dispute_1") .await .unwrap(); assert_eq!(created_dispute, found_dispute); } #[tokio::test] async fn test_find_disputes_by_merchant_id() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_2")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let _ = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let found_disputes = mockdb .find_disputes_by_constraints( &merchant_id, &DisputeListConstraints { dispute_id: None, payment_id: None, profile_id: None, connector: None, merchant_connector_id: None, currency: None, limit: None, offset: None, dispute_status: None, dispute_stage: None, reason: None, time_range: None, }, ) .await .unwrap(); assert_eq!(1, found_disputes.len()); assert_eq!(created_dispute, found_disputes.first().unwrap().clone()); } #[tokio::test] async fn test_find_disputes_by_merchant_id_payment_id() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let _ = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_2".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let found_disputes = mockdb .find_disputes_by_merchant_id_payment_id(&merchant_id, &payment_id) .await .unwrap(); assert_eq!(1, found_disputes.len()); assert_eq!(created_dispute, found_disputes.first().unwrap().clone()); } mod update_dispute { use std::borrow::Cow; use diesel_models::{ dispute::DisputeUpdate, enums::{DisputeStage, DisputeStatus}, }; use masking::Secret; use serde_json::Value; use time::macros::datetime; use crate::db::{ dispute::{ tests::mockdb_dispute_interface::{create_dispute_new, DisputeNewIds}, DisputeInterface, }, MockDb, }; #[tokio::test] async fn test_update_dispute_update() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let updated_dispute = mockdb .update_dispute( created_dispute.clone(), DisputeUpdate::Update { dispute_stage: DisputeStage::PreDispute, dispute_status: DisputeStatus::DisputeAccepted, connector_status: "updated_connector_status".into(), connector_reason: Some("updated_connector_reason".into()), connector_reason_code: Some("updated_connector_reason_code".into()), challenge_required_by: Some(datetime!(2019-01-10 0:00)), connector_updated_at: Some(datetime!(2019-01-11 0:00)), }, ) .await .unwrap(); assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); assert_eq!(created_dispute.amount, updated_dispute.amount); assert_eq!(created_dispute.currency, updated_dispute.currency); assert_ne!(created_dispute.dispute_stage, updated_dispute.dispute_stage); assert_ne!( created_dispute.dispute_status, updated_dispute.dispute_status ); assert_eq!(created_dispute.payment_id, updated_dispute.payment_id); assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id); assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id); assert_ne!( created_dispute.connector_status, updated_dispute.connector_status ); assert_eq!( created_dispute.connector_dispute_id, updated_dispute.connector_dispute_id ); assert_ne!( created_dispute.connector_reason, updated_dispute.connector_reason ); assert_ne!( created_dispute.connector_reason_code, updated_dispute.connector_reason_code ); assert_ne!( created_dispute.challenge_required_by, updated_dispute.challenge_required_by ); assert_eq!( created_dispute.connector_created_at, updated_dispute.connector_created_at ); assert_ne!( created_dispute.connector_updated_at, updated_dispute.connector_updated_at ); assert_eq!(created_dispute.created_at, updated_dispute.created_at); assert_ne!(created_dispute.modified_at, updated_dispute.modified_at); assert_eq!(created_dispute.connector, updated_dispute.connector); assert_eq!(created_dispute.evidence, updated_dispute.evidence); } #[tokio::test] async fn test_update_dispute_update_status() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let updated_dispute = mockdb .update_dispute( created_dispute.clone(), DisputeUpdate::StatusUpdate { dispute_status: DisputeStatus::DisputeExpired, connector_status: Some("updated_connector_status".into()), }, ) .await .unwrap(); assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); assert_eq!(created_dispute.amount, updated_dispute.amount); assert_eq!(created_dispute.currency, updated_dispute.currency); assert_eq!(created_dispute.dispute_stage, updated_dispute.dispute_stage); assert_ne!( created_dispute.dispute_status, updated_dispute.dispute_status ); assert_eq!(created_dispute.payment_id, updated_dispute.payment_id); assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id); assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id); assert_ne!( created_dispute.connector_status, updated_dispute.connector_status ); assert_eq!( created_dispute.connector_dispute_id, updated_dispute.connector_dispute_id ); assert_eq!( created_dispute.connector_reason, updated_dispute.connector_reason ); assert_eq!( created_dispute.connector_reason_code, updated_dispute.connector_reason_code ); assert_eq!( created_dispute.challenge_required_by, updated_dispute.challenge_required_by ); assert_eq!( created_dispute.connector_created_at, updated_dispute.connector_created_at ); assert_eq!( created_dispute.connector_updated_at, updated_dispute.connector_updated_at ); assert_eq!(created_dispute.created_at, updated_dispute.created_at); assert_ne!(created_dispute.modified_at, updated_dispute.modified_at); assert_eq!(created_dispute.connector, updated_dispute.connector); assert_eq!(created_dispute.evidence, updated_dispute.evidence); } #[tokio::test] async fn test_update_dispute_update_evidence() { let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap(); let payment_id = common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap(); let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let created_dispute = mockdb .insert_dispute(create_dispute_new(DisputeNewIds { dispute_id: "dispute_1".into(), attempt_id: "attempt_1".into(), merchant_id: merchant_id.clone(), payment_id: payment_id.clone(), connector_dispute_id: "connector_dispute_1".into(), })) .await .unwrap(); let updated_dispute = mockdb .update_dispute( created_dispute.clone(), DisputeUpdate::EvidenceUpdate { evidence: Secret::from(Value::String("updated_evidence".into())), }, ) .await .unwrap(); assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); assert_eq!(created_dispute.amount, updated_dispute.amount); assert_eq!(created_dispute.currency, updated_dispute.currency); assert_eq!(created_dispute.dispute_stage, updated_dispute.dispute_stage); assert_eq!( created_dispute.dispute_status, updated_dispute.dispute_status ); assert_eq!(created_dispute.payment_id, updated_dispute.payment_id); assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id); assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id); assert_eq!( created_dispute.connector_status, updated_dispute.connector_status ); assert_eq!( created_dispute.connector_dispute_id, updated_dispute.connector_dispute_id ); assert_eq!( created_dispute.connector_reason, updated_dispute.connector_reason ); assert_eq!( created_dispute.connector_reason_code, updated_dispute.connector_reason_code ); assert_eq!( created_dispute.challenge_required_by, updated_dispute.challenge_required_by ); assert_eq!( created_dispute.connector_created_at, updated_dispute.connector_created_at ); assert_eq!( created_dispute.connector_updated_at, updated_dispute.connector_updated_at ); assert_eq!(created_dispute.created_at, updated_dispute.created_at); assert_ne!(created_dispute.modified_at, updated_dispute.modified_at); assert_eq!(created_dispute.connector, updated_dispute.connector); assert_ne!(created_dispute.evidence, updated_dispute.evidence); } } } }
7,921
1,462
hyperswitch
crates/router/src/db/generic_link.rs
.rs
use error_stack::report; use router_env::{instrument, tracing}; use crate::{ connection, core::errors::{self, CustomResult}, db::MockDb, services::Store, types::storage, }; #[async_trait::async_trait] pub trait GenericLinkInterface { async fn find_generic_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::GenericLinkState, errors::StorageError>; async fn find_pm_collect_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError>; async fn find_payout_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PayoutLink, errors::StorageError>; async fn insert_generic_link( &self, _generic_link: storage::GenericLinkNew, ) -> CustomResult<storage::GenericLinkState, errors::StorageError>; async fn insert_pm_collect_link( &self, _pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError>; async fn insert_payout_link( &self, _payout_link: storage::GenericLinkNew, ) -> CustomResult<storage::PayoutLink, errors::StorageError>; async fn update_payout_link( &self, payout_link: storage::PayoutLink, payout_link_update: storage::PayoutLinkUpdate, ) -> CustomResult<storage::PayoutLink, errors::StorageError>; } #[async_trait::async_trait] impl GenericLinkInterface for Store { #[instrument(skip_all)] async fn find_generic_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::GenericLink::find_generic_link_by_link_id(&conn, link_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_pm_collect_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::GenericLink::find_pm_collect_link_by_link_id(&conn, link_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_payout_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::GenericLink::find_payout_link_by_link_id(&conn, link_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_generic_link( &self, generic_link: storage::GenericLinkNew, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; generic_link .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_pm_collect_link( &self, pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; pm_collect_link .insert_pm_collect_link(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_payout_link( &self, pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; pm_collect_link .insert_payout_link(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_payout_link( &self, payout_link: storage::PayoutLink, payout_link_update: storage::PayoutLinkUpdate, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; payout_link .update_payout_link(&conn, payout_link_update) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl GenericLinkInterface for MockDb { async fn find_generic_link_by_link_id( &self, _generic_link_id: &str, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { // TODO: Implement function for `MockDb`x Err(errors::StorageError::MockDbError)? } async fn find_pm_collect_link_by_link_id( &self, _generic_link_id: &str, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { // TODO: Implement function for `MockDb`x Err(errors::StorageError::MockDbError)? } async fn find_payout_link_by_link_id( &self, _generic_link_id: &str, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { // TODO: Implement function for `MockDb`x Err(errors::StorageError::MockDbError)? } async fn insert_generic_link( &self, _generic_link: storage::GenericLinkNew, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn insert_pm_collect_link( &self, _pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn insert_payout_link( &self, _pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn update_payout_link( &self, _payout_link: storage::PayoutLink, _payout_link_update: storage::PayoutLinkUpdate, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { // TODO: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } }
1,562
1,463
hyperswitch
crates/router/src/db/user_authentication_method.rs
.rs
use diesel_models::user_authentication_method as storage; use error_stack::report; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait UserAuthenticationMethodInterface { async fn insert_user_authentication_method( &self, user_authentication_method: storage::UserAuthenticationMethodNew, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; async fn get_user_authentication_method_by_id( &self, id: &str, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>; async fn list_user_authentication_methods_for_owner_id( &self, owner_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>; async fn update_user_authentication_method( &self, id: &str, user_authentication_method_update: storage::UserAuthenticationMethodUpdate, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; async fn list_user_authentication_methods_for_email_domain( &self, email_domain: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>; } #[async_trait::async_trait] impl UserAuthenticationMethodInterface for Store { #[instrument(skip_all)] async fn insert_user_authentication_method( &self, user_authentication_method: storage::UserAuthenticationMethodNew, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; user_authentication_method .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn get_user_authentication_method_by_id( &self, id: &str, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::get_user_authentication_method_by_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::list_user_authentication_methods_for_auth_id( &conn, auth_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_user_authentication_methods_for_owner_id( &self, owner_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::list_user_authentication_methods_for_owner_id( &conn, owner_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_user_authentication_method( &self, id: &str, user_authentication_method_update: storage::UserAuthenticationMethodUpdate, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UserAuthenticationMethod::update_user_authentication_method( &conn, id, user_authentication_method_update, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_user_authentication_methods_for_email_domain( &self, email_domain: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::list_user_authentication_methods_for_email_domain( &conn, email_domain, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl UserAuthenticationMethodInterface for MockDb { async fn insert_user_authentication_method( &self, user_authentication_method: storage::UserAuthenticationMethodNew, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let mut user_authentication_methods = self.user_authentication_methods.lock().await; let existing_auth_id = user_authentication_methods .iter() .find(|uam| uam.owner_id == user_authentication_method.owner_id) .map(|uam| uam.auth_id.clone()); let auth_id = existing_auth_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); let user_authentication_method = storage::UserAuthenticationMethod { id: uuid::Uuid::new_v4().to_string(), auth_id, owner_id: user_authentication_method.auth_id, owner_type: user_authentication_method.owner_type, auth_type: user_authentication_method.auth_type, public_config: user_authentication_method.public_config, private_config: user_authentication_method.private_config, allow_signup: user_authentication_method.allow_signup, created_at: user_authentication_method.created_at, last_modified_at: user_authentication_method.last_modified_at, email_domain: user_authentication_method.email_domain, }; user_authentication_methods.push(user_authentication_method.clone()); Ok(user_authentication_method) } #[instrument(skip_all)] async fn get_user_authentication_method_by_id( &self, id: &str, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let user_authentication_methods = self.user_authentication_methods.lock().await; let user_authentication_method = user_authentication_methods .iter() .find(|&auth_method_inner| auth_method_inner.id == id); if let Some(user_authentication_method) = user_authentication_method { Ok(user_authentication_method.to_owned()) } else { return Err(errors::StorageError::ValueNotFound(format!( "No user authentication method found for id = {}", id )) .into()); } } async fn list_user_authentication_methods_for_auth_id( &self, auth_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let user_authentication_methods = self.user_authentication_methods.lock().await; let user_authentication_methods_list: Vec<_> = user_authentication_methods .iter() .filter(|auth_method_inner| auth_method_inner.auth_id == auth_id) .cloned() .collect(); if user_authentication_methods_list.is_empty() { return Err(errors::StorageError::ValueNotFound(format!( "No user authentication method found for auth_id = {}", auth_id )) .into()); } Ok(user_authentication_methods_list) } async fn list_user_authentication_methods_for_owner_id( &self, owner_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let user_authentication_methods = self.user_authentication_methods.lock().await; let user_authentication_methods_list: Vec<_> = user_authentication_methods .iter() .filter(|auth_method_inner| auth_method_inner.owner_id == owner_id) .cloned() .collect(); if user_authentication_methods_list.is_empty() { return Err(errors::StorageError::ValueNotFound(format!( "No user authentication method found for owner_id = {}", owner_id )) .into()); } Ok(user_authentication_methods_list) } async fn update_user_authentication_method( &self, id: &str, user_authentication_method_update: storage::UserAuthenticationMethodUpdate, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { let mut user_authentication_methods = self.user_authentication_methods.lock().await; user_authentication_methods .iter_mut() .find(|auth_method_inner| auth_method_inner.id == id) .map(|auth_method_inner| { *auth_method_inner = match user_authentication_method_update { storage::UserAuthenticationMethodUpdate::UpdateConfig { private_config, public_config, } => storage::UserAuthenticationMethod { private_config, public_config, last_modified_at: common_utils::date_time::now(), ..auth_method_inner.to_owned() }, storage::UserAuthenticationMethodUpdate::EmailDomain { email_domain } => { storage::UserAuthenticationMethod { email_domain: email_domain.to_owned(), last_modified_at: common_utils::date_time::now(), ..auth_method_inner.to_owned() } } }; auth_method_inner.to_owned() }) .ok_or( errors::StorageError::ValueNotFound(format!( "No authentication method available for the id = {id}" )) .into(), ) } #[instrument(skip_all)] async fn list_user_authentication_methods_for_email_domain( &self, email_domain: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { let user_authentication_methods = self.user_authentication_methods.lock().await; let user_authentication_methods_list: Vec<_> = user_authentication_methods .iter() .filter(|auth_method_inner| auth_method_inner.email_domain == email_domain) .cloned() .collect(); Ok(user_authentication_methods_list) } }
2,098
1,464
hyperswitch
crates/router/src/db/user_key_store.rs
.rs
use common_utils::{ errors::CustomResult, types::keymanager::{self, KeyManagerState}, }; use error_stack::{report, ResultExt}; use masking::Secret; use router_env::{instrument, tracing}; use storage_impl::MockDb; use crate::{ connection, core::errors, services::Store, types::domain::{ self, behaviour::{Conversion, ReverseConversion}, }, }; #[async_trait::async_trait] pub trait UserKeyStoreInterface { async fn insert_user_key_store( &self, state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError>; async fn get_user_key_store_by_user_id( &self, state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError>; async fn get_all_user_key_store( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError>; } #[async_trait::async_trait] impl UserKeyStoreInterface for Store { #[instrument(skip_all)] async fn insert_user_key_store( &self, state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let user_id = user_key_store.user_id.clone(); user_key_store .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert(state, key, keymanager::Identifier::User(user_id)) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn get_user_key_store_by_user_id( &self, state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; diesel_models::user_key_store::UserKeyStore::find_by_user_id(&conn, user_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert(state, key, keymanager::Identifier::User(user_id.to_owned())) .await .change_context(errors::StorageError::DecryptionError) } async fn get_all_user_key_store( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let key_stores = diesel_models::user_key_store::UserKeyStore::get_all_user_key_stores( &conn, from, limit, ) .await .map_err(|err| report!(errors::StorageError::from(err)))?; futures::future::try_join_all(key_stores.into_iter().map(|key_store| async { let user_id = key_store.user_id.clone(); key_store .convert(state, key, keymanager::Identifier::User(user_id)) .await .change_context(errors::StorageError::DecryptionError) })) .await } } #[async_trait::async_trait] impl UserKeyStoreInterface for MockDb { #[instrument(skip_all)] async fn insert_user_key_store( &self, state: &KeyManagerState, user_key_store: domain::UserKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { let mut locked_user_key_store = self.user_key_store.lock().await; if locked_user_key_store .iter() .any(|user_key| user_key.user_id == user_key_store.user_id) { Err(errors::StorageError::DuplicateValue { entity: "user_key_store", key: Some(user_key_store.user_id.clone()), })?; } let user_key_store = Conversion::convert(user_key_store) .await .change_context(errors::StorageError::MockDbError)?; locked_user_key_store.push(user_key_store.clone()); let user_id = user_key_store.user_id.clone(); user_key_store .convert(state, key, keymanager::Identifier::User(user_id)) .await .change_context(errors::StorageError::DecryptionError) } async fn get_all_user_key_store( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, _from: u32, _limit: u32, ) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> { let user_key_store = self.user_key_store.lock().await; futures::future::try_join_all(user_key_store.iter().map(|user_key| async { let user_id = user_key.user_id.clone(); user_key .to_owned() .convert(state, key, keymanager::Identifier::User(user_id)) .await .change_context(errors::StorageError::DecryptionError) })) .await } #[instrument(skip_all)] async fn get_user_key_store_by_user_id( &self, state: &KeyManagerState, user_id: &str, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::UserKeyStore, errors::StorageError> { self.user_key_store .lock() .await .iter() .find(|user_key_store| user_key_store.user_id == user_id) .cloned() .ok_or(errors::StorageError::ValueNotFound(format!( "No user_key_store is found for user_id={}", user_id )))? .convert(state, key, keymanager::Identifier::User(user_id.to_owned())) .await .change_context(errors::StorageError::DecryptionError) } }
1,425
1,465
hyperswitch
crates/router/src/db/ephemeral_key.rs
.rs
#[cfg(feature = "v2")] use common_utils::id_type; use time::ext::NumericalDuration; #[cfg(feature = "v2")] use crate::types::storage::ephemeral_key::{ClientSecretType, ClientSecretTypeNew}; use crate::{ core::errors::{self, CustomResult}, db::MockDb, types::storage::ephemeral_key::{EphemeralKey, EphemeralKeyNew}, }; #[async_trait::async_trait] pub trait EphemeralKeyInterface { #[cfg(feature = "v1")] async fn create_ephemeral_key( &self, _ek: EphemeralKeyNew, _validity: i64, ) -> CustomResult<EphemeralKey, errors::StorageError>; #[cfg(feature = "v1")] async fn get_ephemeral_key( &self, _key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError>; #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, _id: &str, ) -> CustomResult<EphemeralKey, errors::StorageError>; } #[async_trait::async_trait] pub trait ClientSecretInterface { #[cfg(feature = "v2")] async fn create_client_secret( &self, _ek: ClientSecretTypeNew, _validity: i64, ) -> CustomResult<ClientSecretType, errors::StorageError>; #[cfg(feature = "v2")] async fn get_client_secret( &self, _key: &str, ) -> CustomResult<ClientSecretType, errors::StorageError>; #[cfg(feature = "v2")] async fn delete_client_secret( &self, _id: &str, ) -> CustomResult<ClientSecretType, errors::StorageError>; } mod storage { use common_utils::date_time; #[cfg(feature = "v2")] use common_utils::id_type; use error_stack::ResultExt; #[cfg(feature = "v2")] use masking::PeekInterface; #[cfg(feature = "v2")] use redis_interface::errors::RedisError; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::RedisConnInterface; use time::ext::NumericalDuration; use super::{ClientSecretInterface, EphemeralKeyInterface}; #[cfg(feature = "v2")] use crate::types::storage::ephemeral_key::{ClientSecretType, ClientSecretTypeNew}; use crate::{ core::errors::{self, CustomResult}, services::Store, types::storage::ephemeral_key::{EphemeralKey, EphemeralKeyNew}, }; #[async_trait::async_trait] impl EphemeralKeyInterface for Store { #[cfg(feature = "v1")] #[instrument(skip_all)] async fn create_ephemeral_key( &self, new: EphemeralKeyNew, validity: i64, ) -> CustomResult<EphemeralKey, errors::StorageError> { let secret_key = format!("epkey_{}", &new.secret); let id_key = format!("epkey_{}", &new.id); let created_at = date_time::now(); let expires = created_at.saturating_add(validity.hours()); let created_ek = EphemeralKey { id: new.id, created_at: created_at.assume_utc().unix_timestamp(), expires: expires.assume_utc().unix_timestamp(), customer_id: new.customer_id, merchant_id: new.merchant_id, secret: new.secret, }; match self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .serialize_and_set_multiple_hash_field_if_not_exist( &[ (&secret_key.as_str().into(), &created_ek), (&id_key.as_str().into(), &created_ek), ], "ephkey", None, ) .await { Ok(v) if v.contains(&HsetnxReply::KeyNotSet) => { Err(errors::StorageError::DuplicateValue { entity: "ephemeral key", key: None, } .into()) } Ok(_) => { let expire_at = expires.assume_utc().unix_timestamp(); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .set_expire_at(&secret_key.into(), expire_at) .await .change_context(errors::StorageError::KVError)?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .set_expire_at(&id_key.into(), expire_at) .await .change_context(errors::StorageError::KVError)?; Ok(created_ek) } Err(er) => Err(er).change_context(errors::StorageError::KVError), } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_ephemeral_key( &self, key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { let key = format!("epkey_{key}"); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .get_hash_field_and_deserialize(&key.into(), "ephkey", "EphemeralKey") .await .change_context(errors::StorageError::KVError) } #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, id: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { let ek = self.get_ephemeral_key(id).await?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .delete_key(&format!("epkey_{}", &ek.id).into()) .await .change_context(errors::StorageError::KVError)?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .delete_key(&format!("epkey_{}", &ek.secret).into()) .await .change_context(errors::StorageError::KVError)?; Ok(ek) } } #[async_trait::async_trait] impl ClientSecretInterface for Store { #[cfg(feature = "v2")] #[instrument(skip_all)] async fn create_client_secret( &self, new: ClientSecretTypeNew, validity: i64, ) -> CustomResult<ClientSecretType, errors::StorageError> { let created_at = date_time::now(); let expires = created_at.saturating_add(validity.hours()); let id_key = new.id.generate_redis_key(); let created_client_secret = ClientSecretType { id: new.id, created_at, expires, merchant_id: new.merchant_id, secret: new.secret, resource_id: new.resource_id, }; let secret_key = created_client_secret.generate_secret_key(); match self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .serialize_and_set_multiple_hash_field_if_not_exist( &[ (&secret_key.as_str().into(), &created_client_secret), (&id_key.as_str().into(), &created_client_secret), ], "csh", None, ) .await { Ok(v) if v.contains(&HsetnxReply::KeyNotSet) => { Err(errors::StorageError::DuplicateValue { entity: "ephemeral key", key: None, } .into()) } Ok(_) => { let expire_at = expires.assume_utc().unix_timestamp(); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .set_expire_at(&secret_key.into(), expire_at) .await .change_context(errors::StorageError::KVError)?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .set_expire_at(&id_key.into(), expire_at) .await .change_context(errors::StorageError::KVError)?; Ok(created_client_secret) } Err(er) => Err(er).change_context(errors::StorageError::KVError), } } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn get_client_secret( &self, key: &str, ) -> CustomResult<ClientSecretType, errors::StorageError> { let key = format!("cs_{key}"); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .get_hash_field_and_deserialize(&key.into(), "csh", "ClientSecretType") .await .change_context(errors::StorageError::KVError) } #[cfg(feature = "v2")] async fn delete_client_secret( &self, id: &str, ) -> CustomResult<ClientSecretType, errors::StorageError> { let client_secret = self.get_client_secret(id).await?; let redis_id_key = client_secret.id.generate_redis_key(); let secret_key = client_secret.generate_secret_key(); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .delete_key(&redis_id_key.as_str().into()) .await .map_err(|err| match err.current_context() { RedisError::NotFound => { err.change_context(errors::StorageError::ValueNotFound(redis_id_key)) } _ => err.change_context(errors::StorageError::KVError), })?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .delete_key(&secret_key.as_str().into()) .await .map_err(|err| match err.current_context() { RedisError::NotFound => { err.change_context(errors::StorageError::ValueNotFound(secret_key)) } _ => err.change_context(errors::StorageError::KVError), })?; Ok(client_secret) } } } #[async_trait::async_trait] impl EphemeralKeyInterface for MockDb { #[cfg(feature = "v1")] async fn create_ephemeral_key( &self, ek: EphemeralKeyNew, validity: i64, ) -> CustomResult<EphemeralKey, errors::StorageError> { let mut ephemeral_keys = self.ephemeral_keys.lock().await; let created_at = common_utils::date_time::now(); let expires = created_at.saturating_add(validity.hours()); let ephemeral_key = EphemeralKey { id: ek.id, merchant_id: ek.merchant_id, customer_id: ek.customer_id, created_at: created_at.assume_utc().unix_timestamp(), expires: expires.assume_utc().unix_timestamp(), secret: ek.secret, }; ephemeral_keys.push(ephemeral_key.clone()); Ok(ephemeral_key) } #[cfg(feature = "v1")] async fn get_ephemeral_key( &self, key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { match self .ephemeral_keys .lock() .await .iter() .find(|ephemeral_key| ephemeral_key.secret.eq(key)) { Some(ephemeral_key) => Ok(ephemeral_key.clone()), None => Err( errors::StorageError::ValueNotFound("ephemeral key not found".to_string()).into(), ), } } #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, id: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { let mut ephemeral_keys = self.ephemeral_keys.lock().await; if let Some(pos) = ephemeral_keys.iter().position(|x| (*x.id).eq(id)) { let ek = ephemeral_keys.remove(pos); Ok(ek) } else { return Err( errors::StorageError::ValueNotFound("ephemeral key not found".to_string()).into(), ); } } } #[async_trait::async_trait] impl ClientSecretInterface for MockDb { #[cfg(feature = "v2")] async fn create_client_secret( &self, new: ClientSecretTypeNew, validity: i64, ) -> CustomResult<ClientSecretType, errors::StorageError> { todo!() } #[cfg(feature = "v2")] async fn get_client_secret( &self, key: &str, ) -> CustomResult<ClientSecretType, errors::StorageError> { todo!() } #[cfg(feature = "v2")] async fn delete_client_secret( &self, id: &str, ) -> CustomResult<ClientSecretType, errors::StorageError> { todo!() } }
2,850
1,466
hyperswitch
crates/router/src/db/customers.rs
.rs
use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use diesel_models::query::customers::CustomerListConstraints as DieselCustomerListConstraints; use error_stack::ResultExt; use futures::future::try_join_all; use hyperswitch_domain_models::customer; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use router_env::{instrument, tracing}; use super::MockDb; use crate::{ core::errors::{self, CustomResult}, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage::{self as storage_types, enums::MerchantStorageScheme}, }, }; pub struct CustomerListConstraints { pub limit: u16, pub offset: Option<u32>, } impl From<CustomerListConstraints> for DieselCustomerListConstraints { fn from(value: CustomerListConstraints) -> Self { Self { limit: i64::from(value.limit), offset: value.offset.map(i64::from), } } } #[async_trait::async_trait] pub trait CustomerInterface where customer::Customer: Conversion<DstType = storage_types::Customer, NewDstType = storage_types::CustomerNew>, { #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError>; #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[allow(clippy::too_many_arguments)] async fn update_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, customer: customer::Customer, customer_update: storage_types::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError>; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError>; #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_customer_by_merchant_reference_id_merchant_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError>; async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, constraints: CustomerListConstraints, ) -> CustomResult<Vec<customer::Customer>, errors::StorageError>; async fn insert_customer( &self, customer_data: customer::Customer, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError>; #[cfg(all(feature = "v2", feature = "customer_v2"))] #[allow(clippy::too_many_arguments)] async fn update_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: customer::Customer, merchant_id: &id_type::MerchantId, customer_update: storage_types::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError>; #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError>; } #[cfg(feature = "kv_store")] mod storage { use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use diesel_models::kv; use error_stack::{report, ResultExt}; use futures::future::try_join_all; use hyperswitch_domain_models::customer; use masking::PeekInterface; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey, }; use super::CustomerInterface; use crate::{ connection, core::{ customers::REDACTED, errors::{self, CustomResult}, }, services::Store, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage::{self as storage_types, enums::MerchantStorageScheme}, }, utils::db_utils, }; #[async_trait::async_trait] impl CustomerInterface for Store { #[instrument(skip_all)] // check customer not found in kv and fallback to db #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|err| report!(errors::StorageError::from(err))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Find, )) .await; let maybe_customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }; let field = format!("cust_{}", customer_id.get_string_repr()); Box::pin(db_utils::try_redis_get_else_try_database_get( // check for ValueNotFound async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, )) .await? .try_into_hget() .map(Some) }, database_call, )) .await } }?; let maybe_result = maybe_customer .async_map(|c| async { c.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(Some(customer)), }) } #[instrument(skip_all)] // check customer not found in kv and fallback to db #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|err| report!(errors::StorageError::from(err))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Find, )) .await; let maybe_customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }; let field = format!("cust_{}", customer_id.get_string_repr()); Box::pin(db_utils::try_redis_get_else_try_database_get( // check for ValueNotFound async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, )) .await? .try_into_hget() .map(Some) }, database_call, )) .await } }?; let maybe_result = maybe_customer .async_map(|customer| async { customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; Ok(maybe_result) } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Customer::find_optional_by_merchant_id_merchant_reference_id( &conn, merchant_reference_id, merchant_id, ) .await .map_err(|err| report!(errors::StorageError::from(err))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Find, )) .await; let maybe_customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdMerchantReferenceId { merchant_id, merchant_reference_id: merchant_reference_id.get_string_repr(), }; let field = format!("cust_{}", merchant_reference_id.get_string_repr()); Box::pin(db_utils::try_redis_get_else_try_database_get( // check for ValueNotFound async { kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, ) .await? .try_into_hget() .map(Some) }, database_call, )) .await } }?; let maybe_result = maybe_customer .async_map(|c| async { c.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(Some(customer)), }) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, customer: customer::Customer, customer_update: storage_types::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let customer = Conversion::convert(customer) .await .change_context(errors::StorageError::EncryptionError)?; let database_call = || async { storage_types::Customer::update_by_customer_id_merchant_id( &conn, customer_id.clone(), merchant_id.clone(), customer_update.clone().into(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let key = PartitionKey::MerchantIdCustomerId { merchant_id: &merchant_id, customer_id: &customer_id, }; let field = format!("cust_{}", customer_id.get_string_repr()); let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Update(key.clone(), &field, customer.updated_by.as_deref()), )) .await; let updated_object = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let updated_customer = diesel_models::CustomerUpdateInternal::from(customer_update.clone()) .apply_changeset(customer.clone()); let redis_value = serde_json::to_string(&updated_customer) .change_context(errors::StorageError::KVError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::CustomerUpdate( kv::CustomerUpdateMems { orig: customer, update_data: customer_update.into(), }, )), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::Hset::<diesel_models::Customer>( (&field, redis_value), redis_entry, ), key, )) .await .change_context(errors::StorageError::KVError)? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_customer) } }; updated_object? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_customer_by_merchant_reference_id_merchant_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Customer::find_by_merchant_reference_id_merchant_id( &conn, merchant_reference_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Find, )) .await; let customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdMerchantReferenceId { merchant_id, merchant_reference_id: merchant_reference_id.get_string_repr(), }; let field = format!("cust_{}", merchant_reference_id.get_string_repr()); Box::pin(db_utils::try_redis_get_else_try_database_get( async { kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, ) .await? .try_into_hget() }, database_call, )) .await } }?; let result: customer::Customer = customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; match result.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(result), } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn find_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Customer::find_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Find, )) .await; let customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdCustomerId { merchant_id, customer_id, }; let field = format!("cust_{}", customer_id.get_string_repr()); Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } }?; let result: customer::Customer = customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; match result.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(result), } } #[instrument(skip_all)] async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, constraints: super::CustomerListConstraints, ) -> CustomResult<Vec<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let customer_list_constraints = diesel_models::query::customers::CustomerListConstraints::from(constraints); let encrypted_customers = storage_types::Customer::list_by_merchant_id( &conn, merchant_id, customer_list_constraints, ) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let customers = try_join_all(encrypted_customers.into_iter().map( |encrypted_customer| async { encrypted_customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }, )) .await?; Ok(customers) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn insert_customer( &self, customer_data: customer::Customer, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let id = customer_data.id.clone(); let mut new_customer = customer_data .construct_new() .await .change_context(errors::StorageError::EncryptionError)?; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Insert, )) .await; new_customer.update_storage_scheme(storage_scheme); let create_customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; new_customer .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } MerchantStorageScheme::RedisKv => { let key = PartitionKey::GlobalId { id: id.get_string_repr(), }; let field = format!("cust_{}", id.get_string_repr()); let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Customer(new_customer.clone())), }, }; let storage_customer = new_customer.into(); match kv_wrapper::<diesel_models::Customer, _, _>( self, KvOperation::HSetNx::<diesel_models::Customer>( &field, &storage_customer, redis_entry, ), key, ) .await .change_context(errors::StorageError::KVError)? .try_into_hsetnx() { Ok(redis_interface::HsetnxReply::KeyNotSet) => { Err(report!(errors::StorageError::DuplicateValue { entity: "customer", key: Some(id.get_string_repr().to_owned()), })) } Ok(redis_interface::HsetnxReply::KeySet) => Ok(storage_customer), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } }?; create_customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn insert_customer( &self, customer_data: customer::Customer, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let customer_id = customer_data.customer_id.clone(); let merchant_id = customer_data.merchant_id.clone(); let mut new_customer = customer_data .construct_new() .await .change_context(errors::StorageError::EncryptionError)?; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Insert, )) .await; new_customer.update_storage_scheme(storage_scheme); let create_customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; new_customer .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdCustomerId { merchant_id: &merchant_id, customer_id: &customer_id, }; let field = format!("cust_{}", customer_id.get_string_repr()); let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Customer(new_customer.clone())), }, }; let storage_customer = new_customer.into(); match Box::pin(kv_wrapper::<diesel_models::Customer, _, _>( self, KvOperation::HSetNx::<diesel_models::Customer>( &field, &storage_customer, redis_entry, ), key, )) .await .change_context(errors::StorageError::KVError)? .try_into_hsetnx() { Ok(redis_interface::HsetnxReply::KeyNotSet) => { Err(report!(errors::StorageError::DuplicateValue { entity: "customer", key: Some(customer_id.get_string_repr().to_string()), })) } Ok(redis_interface::HsetnxReply::KeySet) => Ok(storage_customer), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } }?; create_customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Customer::delete_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, _merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Customer::find_by_global_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Find, )) .await; let customer = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::GlobalId { id: id.get_string_repr(), }; let field = format!("cust_{}", id.get_string_repr()); Box::pin(db_utils::try_redis_get_else_try_database_get( async { kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, ) .await? .try_into_hget() }, database_call, )) .await } }?; let result: customer::Customer = customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; if result.status == common_enums::DeleteStatus::Redacted { Err(report!(errors::StorageError::CustomerRedacted)) } else { Ok(result) } } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn update_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: customer::Customer, _merchant_id: &id_type::MerchantId, customer_update: storage_types::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let customer = Conversion::convert(customer) .await .change_context(errors::StorageError::EncryptionError)?; let database_call = || async { storage_types::Customer::update_by_id( &conn, id.clone(), customer_update.clone().into(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let key = PartitionKey::GlobalId { id: id.get_string_repr(), }; let field = format!("cust_{}", id.get_string_repr()); let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>( self, storage_scheme, Op::Update(key.clone(), &field, customer.updated_by.as_deref()), )) .await; let updated_object = match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let updated_customer = diesel_models::CustomerUpdateInternal::from(customer_update.clone()) .apply_changeset(customer.clone()); let redis_value = serde_json::to_string(&updated_customer) .change_context(errors::StorageError::KVError)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::CustomerUpdate( kv::CustomerUpdateMems { orig: customer, update_data: customer_update.into(), }, )), }, }; kv_wrapper::<(), _, _>( self, KvOperation::Hset::<diesel_models::Customer>( (&field, redis_value), redis_entry, ), key, ) .await .change_context(errors::StorageError::KVError)? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_customer) } }; updated_object? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } } } #[cfg(not(feature = "kv_store"))] mod storage { use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use futures::future::try_join_all; use hyperswitch_domain_models::customer; use masking::PeekInterface; use router_env::{instrument, tracing}; use super::CustomerInterface; use crate::{ connection, core::{ customers::REDACTED, errors::{self, CustomResult}, }, services::Store, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage::{self as storage_types, enums::MerchantStorageScheme}, }, }; #[async_trait::async_trait] impl CustomerInterface for Store { #[instrument(skip_all)] #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let maybe_customer: Option<customer::Customer> = storage_types::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .async_map(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; maybe_customer.map_or(Ok(None), |customer| { // in the future, once #![feature(is_some_and)] is stable, we can make this more concise: // `if customer.name.is_some_and(|ref name| name == REDACTED) ...` match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(Some(customer)), } }) } #[instrument(skip_all)] #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let maybe_customer: Option<customer::Customer> = storage_types::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .async_map(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; Ok(maybe_customer) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let maybe_customer: Option<customer::Customer> = storage_types::Customer::find_optional_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))? .async_map(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()?; maybe_customer.map_or(Ok(None), |customer| { // in the future, once #![feature(is_some_and)] is stable, we can make this more concise: // `if customer.name.is_some_and(|ref name| name == REDACTED) ...` match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(Some(customer)), } }) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: id_type::CustomerId, merchant_id: id_type::MerchantId, _customer: customer::Customer, customer_update: storage_types::CustomerUpdate, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Customer::update_by_customer_id_merchant_id( &conn, customer_id, merchant_id.clone(), customer_update.into(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.into()) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn find_customer_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let customer: customer::Customer = storage_types::Customer::find_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await?; match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(customer), } } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_customer_by_merchant_reference_id_merchant_id( &self, state: &KeyManagerState, merchant_reference_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let customer: customer::Customer = storage_types::Customer::find_by_merchant_reference_id_merchant_id( &conn, merchant_reference_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await?; match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(customer), } } #[instrument(skip_all)] async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, constraints: super::CustomerListConstraints, ) -> CustomResult<Vec<customer::Customer>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let customer_list_constraints = diesel_models::query::customers::CustomerListConstraints::from(constraints); let encrypted_customers = storage_types::Customer::list_by_merchant_id( &conn, merchant_id, customer_list_constraints, ) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let customers = try_join_all(encrypted_customers.into_iter().map( |encrypted_customer| async { encrypted_customer .convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }, )) .await?; Ok(customers) } #[instrument(skip_all)] async fn insert_customer( &self, customer_data: customer::Customer, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; customer_data .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { c.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn delete_customer_by_customer_id_merchant_id( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Customer::delete_by_customer_id_merchant_id( &conn, customer_id, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[allow(clippy::too_many_arguments)] async fn update_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, customer: customer::Customer, merchant_id: &id_type::MerchantId, customer_update: storage_types::CustomerUpdate, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Customer::update_by_global_id(&conn, id, customer_update.into()) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_customer_by_global_id( &self, state: &KeyManagerState, id: &id_type::GlobalCustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let customer: customer::Customer = storage_types::Customer::find_by_global_id(&conn, customer_id, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|c| async { c.convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }) .await?; match customer.name { Some(ref name) if name.peek() == REDACTED => { Err(errors::StorageError::CustomerRedacted)? } _ => Ok(customer), } } } } #[async_trait::async_trait] impl CustomerInterface for MockDb { #[allow(clippy::panic)] #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let customers = self.customers.lock().await; let customer = customers .iter() .find(|customer| { customer.customer_id == *customer_id && &customer.merchant_id == merchant_id }) .cloned(); customer .async_map(|c| async { c.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose() } #[allow(clippy::panic)] #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { let customers = self.customers.lock().await; let customer = customers .iter() .find(|customer| { customer.customer_id == *customer_id && &customer.merchant_id == merchant_id }) .cloned(); customer .async_map(|c| async { c.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose() } #[allow(clippy::panic)] #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_optional_by_merchant_id_merchant_reference_id( &self, state: &KeyManagerState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<Option<customer::Customer>, errors::StorageError> { todo!() } async fn list_customers_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, key_store: &domain::MerchantKeyStore, constraints: CustomerListConstraints, ) -> CustomResult<Vec<customer::Customer>, errors::StorageError> { let customers = self.customers.lock().await; let customers = try_join_all( customers .iter() .filter(|customer| customer.merchant_id == *merchant_id) .take(usize::from(constraints.limit)) .skip(usize::try_from(constraints.offset.unwrap_or(0)).unwrap_or(0)) .map(|customer| async { customer .to_owned() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }), ) .await?; Ok(customers) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] async fn update_customer_by_customer_id_merchant_id( &self, _state: &KeyManagerState, _customer_id: id_type::CustomerId, _merchant_id: id_type::MerchantId, _customer: customer::Customer, _customer_update: storage_types::CustomerUpdate, _key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn find_customer_by_customer_id_merchant_id( &self, _state: &KeyManagerState, _customer_id: &id_type::CustomerId, _merchant_id: &id_type::MerchantId, _key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_customer_by_merchant_reference_id_merchant_id( &self, _state: &KeyManagerState, _merchant_reference_id: &id_type::CustomerId, _merchant_id: &id_type::MerchantId, _key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } #[allow(clippy::panic)] async fn insert_customer( &self, customer_data: customer::Customer, state: &KeyManagerState, key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { let mut customers = self.customers.lock().await; let customer = Conversion::convert(customer_data) .await .change_context(errors::StorageError::EncryptionError)?; customers.push(customer.clone()); customer .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn delete_customer_by_customer_id_merchant_id( &self, _customer_id: &id_type::CustomerId, _merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[allow(clippy::too_many_arguments)] async fn update_customer_by_global_id( &self, _state: &KeyManagerState, _id: &id_type::GlobalCustomerId, _customer: customer::Customer, _merchant_id: &id_type::MerchantId, _customer_update: storage_types::CustomerUpdate, _key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_customer_by_global_id( &self, _state: &KeyManagerState, _id: &id_type::GlobalCustomerId, _merchant_id: &id_type::MerchantId, _key_store: &domain::MerchantKeyStore, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<customer::Customer, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } }
11,973
1,467
hyperswitch
crates/router/src/db/dashboard_metadata.rs
.rs
use common_utils::id_type; use diesel_models::{enums, user::dashboard_metadata as storage}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use storage_impl::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait DashboardMetadataInterface { async fn insert_metadata( &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError>; async fn update_metadata( &self, user_id: Option<String>, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_key: enums::DashboardMetadata, dashboard_metadata_update: storage::DashboardMetadataUpdate, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError>; async fn find_user_scoped_dashboard_metadata( &self, user_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>; async fn find_merchant_scoped_dashboard_metadata( &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>; async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError>; async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &self, user_id: &str, merchant_id: &id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError>; } #[async_trait::async_trait] impl DashboardMetadataInterface for Store { #[instrument(skip_all)] async fn insert_metadata( &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; metadata .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_metadata( &self, user_id: Option<String>, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_key: enums::DashboardMetadata, dashboard_metadata_update: storage::DashboardMetadataUpdate, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::DashboardMetadata::update( &conn, user_id, merchant_id, org_id, data_key, dashboard_metadata_update, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_user_scoped_dashboard_metadata( &self, user_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::DashboardMetadata::find_user_scoped_dashboard_metadata( &conn, user_id.to_owned(), merchant_id.to_owned(), org_id.to_owned(), data_keys, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_merchant_scoped_dashboard_metadata( &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::DashboardMetadata::find_merchant_scoped_dashboard_metadata( &conn, merchant_id.to_owned(), org_id.to_owned(), data_keys, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::DashboardMetadata::delete_all_user_scoped_dashboard_metadata_by_merchant_id( &conn, user_id.to_owned(), merchant_id.to_owned(), ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &self, user_id: &str, merchant_id: &id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &conn, user_id.to_owned(), merchant_id.to_owned(), data_key, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl DashboardMetadataInterface for MockDb { async fn insert_metadata( &self, metadata: storage::DashboardMetadataNew, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let mut dashboard_metadata = self.dashboard_metadata.lock().await; if dashboard_metadata.iter().any(|metadata_inner| { metadata_inner.user_id == metadata.user_id && metadata_inner.merchant_id == metadata.merchant_id && metadata_inner.org_id == metadata.org_id && metadata_inner.data_key == metadata.data_key }) { Err(errors::StorageError::DuplicateValue { entity: "user_id, merchant_id, org_id and data_key", key: None, })? } let metadata_new = storage::DashboardMetadata { id: i32::try_from(dashboard_metadata.len()) .change_context(errors::StorageError::MockDbError)?, user_id: metadata.user_id, merchant_id: metadata.merchant_id, org_id: metadata.org_id, data_key: metadata.data_key, data_value: metadata.data_value, created_by: metadata.created_by, created_at: metadata.created_at, last_modified_by: metadata.last_modified_by, last_modified_at: metadata.last_modified_at, }; dashboard_metadata.push(metadata_new.clone()); Ok(metadata_new) } async fn update_metadata( &self, user_id: Option<String>, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, data_key: enums::DashboardMetadata, dashboard_metadata_update: storage::DashboardMetadataUpdate, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let mut dashboard_metadata = self.dashboard_metadata.lock().await; let dashboard_metadata_to_update = dashboard_metadata .iter_mut() .find(|metadata| { metadata.user_id == user_id && metadata.merchant_id == merchant_id && metadata.org_id == org_id && metadata.data_key == data_key }) .ok_or(errors::StorageError::MockDbError)?; match dashboard_metadata_update { storage::DashboardMetadataUpdate::UpdateData { data_key, data_value, last_modified_by, } => { dashboard_metadata_to_update.data_key = data_key; dashboard_metadata_to_update.data_value = data_value; dashboard_metadata_to_update.last_modified_by = last_modified_by; dashboard_metadata_to_update.last_modified_at = common_utils::date_time::now(); } } Ok(dashboard_metadata_to_update.clone()) } async fn find_user_scoped_dashboard_metadata( &self, user_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { let dashboard_metadata = self.dashboard_metadata.lock().await; let query_result = dashboard_metadata .iter() .filter(|metadata_inner| { metadata_inner .user_id .clone() .map(|user_id_inner| user_id_inner == user_id) .unwrap_or(false) && metadata_inner.merchant_id == *merchant_id && metadata_inner.org_id == *org_id && data_keys.contains(&metadata_inner.data_key) }) .cloned() .collect::<Vec<storage::DashboardMetadata>>(); if query_result.is_empty() { return Err(errors::StorageError::ValueNotFound(format!( "No dashboard_metadata available for user_id = {user_id},\ merchant_id = {merchant_id:?}, org_id = {org_id:?} and data_keys = {data_keys:?}", )) .into()); } Ok(query_result) } async fn find_merchant_scoped_dashboard_metadata( &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { let dashboard_metadata = self.dashboard_metadata.lock().await; let query_result = dashboard_metadata .iter() .filter(|metadata_inner| { metadata_inner.merchant_id == *merchant_id && metadata_inner.org_id == *org_id && data_keys.contains(&metadata_inner.data_key) }) .cloned() .collect::<Vec<storage::DashboardMetadata>>(); if query_result.is_empty() { return Err(errors::StorageError::ValueNotFound(format!( "No dashboard_metadata available for merchant_id = {merchant_id:?},\ org_id = {org_id:?} and data_keyss = {data_keys:?}", )) .into()); } Ok(query_result) } async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id( &self, user_id: &str, merchant_id: &id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let mut dashboard_metadata = self.dashboard_metadata.lock().await; let initial_len = dashboard_metadata.len(); dashboard_metadata.retain(|metadata_inner| { !(metadata_inner .user_id .clone() .map(|user_id_inner| user_id_inner == user_id) .unwrap_or(false) && metadata_inner.merchant_id == *merchant_id) }); if dashboard_metadata.len() == initial_len { return Err(errors::StorageError::ValueNotFound(format!( "No user available for user_id = {user_id} and merchant id = {merchant_id:?}" )) .into()); } Ok(true) } async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key( &self, user_id: &str, merchant_id: &id_type::MerchantId, data_key: enums::DashboardMetadata, ) -> CustomResult<storage::DashboardMetadata, errors::StorageError> { let mut dashboard_metadata = self.dashboard_metadata.lock().await; let index_to_remove = dashboard_metadata .iter() .position(|metadata_inner| { metadata_inner.user_id.as_deref() == Some(user_id) && metadata_inner.merchant_id == *merchant_id && metadata_inner.data_key == data_key }) .ok_or(errors::StorageError::ValueNotFound( "No data found".to_string(), ))?; let deleted_value = dashboard_metadata.swap_remove(index_to_remove); Ok(deleted_value) } }
2,671
1,468
hyperswitch
crates/router/src/db/fraud_check.rs
.rs
use diesel_models::fraud_check::{self as storage, FraudCheck, FraudCheckUpdate}; use error_stack::report; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait FraudCheckInterface { async fn insert_fraud_check_response( &self, new: storage::FraudCheckNew, ) -> CustomResult<FraudCheck, errors::StorageError>; async fn update_fraud_check_response_with_attempt_id( &self, this: FraudCheck, fraud_check: FraudCheckUpdate, ) -> CustomResult<FraudCheck, errors::StorageError>; async fn find_fraud_check_by_payment_id( &self, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<FraudCheck, errors::StorageError>; async fn find_fraud_check_by_payment_id_if_present( &self, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<Option<FraudCheck>, errors::StorageError>; } #[async_trait::async_trait] impl FraudCheckInterface for Store { #[instrument(skip_all)] async fn insert_fraud_check_response( &self, new: storage::FraudCheckNew, ) -> CustomResult<FraudCheck, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_fraud_check_response_with_attempt_id( &self, this: FraudCheck, fraud_check: FraudCheckUpdate, ) -> CustomResult<FraudCheck, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update_with_attempt_id(&conn, fraud_check) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_fraud_check_by_payment_id( &self, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<FraudCheck, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; FraudCheck::get_with_payment_id(&conn, payment_id, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_fraud_check_by_payment_id_if_present( &self, payment_id: common_utils::id_type::PaymentId, merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<Option<FraudCheck>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; FraudCheck::get_with_payment_id_if_present(&conn, payment_id, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl FraudCheckInterface for MockDb { async fn insert_fraud_check_response( &self, _new: storage::FraudCheckNew, ) -> CustomResult<FraudCheck, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_fraud_check_response_with_attempt_id( &self, _this: FraudCheck, _fraud_check: FraudCheckUpdate, ) -> CustomResult<FraudCheck, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_fraud_check_by_payment_id( &self, _payment_id: common_utils::id_type::PaymentId, _merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<FraudCheck, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_fraud_check_by_payment_id_if_present( &self, _payment_id: common_utils::id_type::PaymentId, _merchant_id: common_utils::id_type::MerchantId, ) -> CustomResult<Option<FraudCheck>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } }
978
1,469
hyperswitch
crates/router/src/db/mandate.rs
.rs
use common_utils::id_type; use super::MockDb; use crate::{ core::errors::{self, CustomResult}, types::storage::{self as storage_types, enums::MerchantStorageScheme}, }; #[async_trait::async_trait] pub trait MandateInterface { async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError>; async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError>; async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>; // Fix this function once we move to mandate v2 #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_mandate_by_global_customer_id( &self, id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>; async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage_types::MandateUpdate, mandate: storage_types::Mandate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError>; async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>; async fn insert_mandate( &self, mandate: storage_types::MandateNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError>; } #[cfg(feature = "kv_store")] mod storage { use common_utils::{fallback_reverse_lookup_not_found, id_type}; use diesel_models::kv; use error_stack::{report, ResultExt}; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey, }; use super::MandateInterface; use crate::{ connection, core::errors::{self, utils::RedisErrorExt, CustomResult}, db::reverse_lookup::ReverseLookupInterface, services::Store, types::storage::{self as storage_types, enums::MerchantStorageScheme, MandateDbExt}, utils::db_utils, }; #[async_trait::async_trait] impl MandateInterface for Store { #[instrument(skip_all)] async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Mandate::find_by_merchant_id_mandate_id( &conn, merchant_id, mandate_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let key = PartitionKey::MerchantIdMandateId { merchant_id, mandate_id, }; let field = format!("mandate_{}", mandate_id); Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Mandate>::HGet(&field), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[instrument(skip_all)] async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; let database_call = || async { storage_types::Mandate::find_by_merchant_id_connector_mandate_id( &conn, merchant_id, connector_mandate_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => database_call().await, MerchantStorageScheme::RedisKv => { let lookup_id = format!( "mid_{}_conn_mandate_{}", merchant_id.get_string_repr(), connector_mandate_id ); let lookup = fallback_reverse_lookup_not_found!( self.get_lookup_by_lookup_id(&lookup_id, storage_scheme) .await, database_call().await ); let key = PartitionKey::CombinationKey { combination: &lookup.pk_id, }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Mandate>::HGet(&lookup.sk_id), key, )) .await? .try_into_hget() }, database_call, )) .await } } } #[instrument(skip_all)] async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_merchant_id_customer_id(&conn, merchant_id, customer_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_mandate_by_global_customer_id( &self, id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_global_customer_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage_types::MandateUpdate, mandate: storage_types::Mandate, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let key = PartitionKey::MerchantIdMandateId { merchant_id, mandate_id, }; let field = format!("mandate_{}", mandate_id); let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>( self, storage_scheme, Op::Update(key.clone(), &field, mandate.updated_by.as_deref()), )) .await; match storage_scheme { MerchantStorageScheme::PostgresOnly => { storage_types::Mandate::update_by_merchant_id_mandate_id( &conn, merchant_id, mandate_id, mandate_update.convert_to_mandate_update(storage_scheme), ) .await .map_err(|error| report!(errors::StorageError::from(error))) } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); if let diesel_models::MandateUpdate::ConnectorMandateIdUpdate { connector_mandate_id: Some(val), .. } = &mandate_update { let rev_lookup = diesel_models::ReverseLookupNew { sk_id: field.clone(), pk_id: key_str.clone(), lookup_id: format!( "mid_{}_conn_mandate_{}", merchant_id.get_string_repr(), val ), source: "mandate".to_string(), updated_by: storage_scheme.to_string(), }; self.insert_reverse_lookup(rev_lookup, storage_scheme) .await?; } let m_update = mandate_update.convert_to_mandate_update(storage_scheme); let updated_mandate = m_update.clone().apply_changeset(mandate.clone()); let redis_value = serde_json::to_string(&updated_mandate) .change_context(errors::StorageError::SerializationFailed)?; let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { updatable: Box::new(kv::Updateable::MandateUpdate( kv::MandateUpdateMems { orig: mandate, update_data: m_update, }, )), }, }; Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<diesel_models::Mandate>::Hset( (&field, redis_value), redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() .change_context(errors::StorageError::KVError)?; Ok(updated_mandate) } } } #[instrument(skip_all)] async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::filter_by_constraints(&conn, merchant_id, mandate_constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_mandate( &self, mut mandate: storage_types::MandateNew, storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>( self, storage_scheme, Op::Insert, )) .await; mandate.update_storage_scheme(storage_scheme); match storage_scheme { MerchantStorageScheme::PostgresOnly => mandate .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))), MerchantStorageScheme::RedisKv => { let mandate_id = mandate.mandate_id.clone(); let merchant_id = &mandate.merchant_id.to_owned(); let connector_mandate_id = mandate.connector_mandate_id.clone(); let key = PartitionKey::MerchantIdMandateId { merchant_id, mandate_id: mandate_id.as_str(), }; let key_str = key.to_string(); let field = format!("mandate_{}", mandate_id); let storage_mandate = storage_types::Mandate::from(&mandate); let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::Mandate(mandate)), }, }; if let Some(connector_val) = connector_mandate_id { let lookup_id = format!( "mid_{}_conn_mandate_{}", merchant_id.get_string_repr(), connector_val ); let reverse_lookup_entry = diesel_models::ReverseLookupNew { sk_id: field.clone(), pk_id: key_str.clone(), lookup_id, source: "mandate".to_string(), updated_by: storage_scheme.to_string(), }; self.insert_reverse_lookup(reverse_lookup_entry, storage_scheme) .await?; } match Box::pin(kv_wrapper::<diesel_models::Mandate, _, _>( self, KvOperation::<diesel_models::Mandate>::HSetNx( &field, &storage_mandate, redis_entry, ), key, )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() { Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "mandate", key: Some(storage_mandate.mandate_id), } .into()), Ok(HsetnxReply::KeySet) => Ok(storage_mandate), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } } } #[cfg(not(feature = "kv_store"))] mod storage { use common_utils::id_type; use error_stack::report; use router_env::{instrument, tracing}; use super::MandateInterface; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, types::storage::{self as storage_types, enums::MerchantStorageScheme, MandateDbExt}, }; #[async_trait::async_trait] impl MandateInterface for Store { #[instrument(skip_all)] async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_merchant_id_mandate_id(&conn, merchant_id, mandate_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_merchant_id_connector_mandate_id( &conn, merchant_id, connector_mandate_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_merchant_id_customer_id(&conn, merchant_id, customer_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } // Need to fix this once we start moving to mandate v2 #[cfg(all(feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] async fn find_mandate_by_global_customer_id( &self, customer_id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::find_by_global_id(&conn, customer_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage_types::MandateUpdate, _mandate: storage_types::Mandate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage_types::Mandate::update_by_merchant_id_mandate_id( &conn, merchant_id, mandate_id, storage_types::MandateUpdateInternal::from(mandate_update), ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage_types::Mandate::filter_by_constraints(&conn, merchant_id, mandate_constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn insert_mandate( &self, mandate: storage_types::MandateNew, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; mandate .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } } } #[async_trait::async_trait] impl MandateInterface for MockDb { async fn find_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { self.mandates .lock() .await .iter() .find(|mandate| mandate.merchant_id == *merchant_id && mandate.mandate_id == mandate_id) .cloned() .ok_or_else(|| errors::StorageError::ValueNotFound("mandate not found".to_string())) .map_err(|err| err.into()) } async fn find_mandate_by_merchant_id_connector_mandate_id( &self, merchant_id: &id_type::MerchantId, connector_mandate_id: &str, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { self.mandates .lock() .await .iter() .find(|mandate| { mandate.merchant_id == *merchant_id && mandate.connector_mandate_id == Some(connector_mandate_id.to_string()) }) .cloned() .ok_or_else(|| errors::StorageError::ValueNotFound("mandate not found".to_string())) .map_err(|err| err.into()) } async fn find_mandate_by_merchant_id_customer_id( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { return Ok(self .mandates .lock() .await .iter() .filter(|mandate| { mandate.merchant_id == *merchant_id && &mandate.customer_id == customer_id }) .cloned() .collect()); } // Need to fix this once we move to v2 mandate #[cfg(all(feature = "v2", feature = "customer_v2"))] async fn find_mandate_by_global_customer_id( &self, id: &id_type::GlobalCustomerId, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { todo!() } async fn update_mandate_by_merchant_id_mandate_id( &self, merchant_id: &id_type::MerchantId, mandate_id: &str, mandate_update: storage_types::MandateUpdate, _mandate: storage_types::Mandate, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let mut mandates = self.mandates.lock().await; match mandates .iter_mut() .find(|mandate| mandate.merchant_id == *merchant_id && mandate.mandate_id == mandate_id) { Some(mandate) => { let m_update = diesel_models::MandateUpdateInternal::from(mandate_update); let updated_mandate = m_update.clone().apply_changeset(mandate.clone()); Ok(updated_mandate) } None => { Err(errors::StorageError::ValueNotFound("mandate not found".to_string()).into()) } } } async fn find_mandates_by_merchant_id( &self, merchant_id: &id_type::MerchantId, mandate_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> { let mandates = self.mandates.lock().await; let mandates_iter = mandates.iter().filter(|mandate| { let mut checker = mandate.merchant_id == *merchant_id; if let Some(created_time) = mandate_constraints.created_time { checker &= mandate.created_at == created_time; } if let Some(created_time_lt) = mandate_constraints.created_time_lt { checker &= mandate.created_at < created_time_lt; } if let Some(created_time_gt) = mandate_constraints.created_time_gt { checker &= mandate.created_at > created_time_gt; } if let Some(created_time_lte) = mandate_constraints.created_time_lte { checker &= mandate.created_at <= created_time_lte; } if let Some(created_time_gte) = mandate_constraints.created_time_gte { checker &= mandate.created_at >= created_time_gte; } if let Some(connector) = &mandate_constraints.connector { checker &= mandate.connector == *connector; } if let Some(mandate_status) = mandate_constraints.mandate_status { checker &= mandate.mandate_status == mandate_status; } checker }); #[allow(clippy::as_conversions)] let offset = (if mandate_constraints.offset.unwrap_or(0) < 0 { 0 } else { mandate_constraints.offset.unwrap_or(0) }) as usize; let mandates: Vec<storage_types::Mandate> = if let Some(limit) = mandate_constraints.limit { #[allow(clippy::as_conversions)] mandates_iter .skip(offset) .take((if limit < 0 { 0 } else { limit }) as usize) .cloned() .collect() } else { mandates_iter.skip(offset).cloned().collect() }; Ok(mandates) } async fn insert_mandate( &self, mandate_new: storage_types::MandateNew, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let mut mandates = self.mandates.lock().await; let mandate = storage_types::Mandate { mandate_id: mandate_new.mandate_id.clone(), customer_id: mandate_new.customer_id, merchant_id: mandate_new.merchant_id, original_payment_id: mandate_new.original_payment_id, payment_method_id: mandate_new.payment_method_id, mandate_status: mandate_new.mandate_status, mandate_type: mandate_new.mandate_type, customer_accepted_at: mandate_new.customer_accepted_at, customer_ip_address: mandate_new.customer_ip_address, customer_user_agent: mandate_new.customer_user_agent, network_transaction_id: mandate_new.network_transaction_id, previous_attempt_id: mandate_new.previous_attempt_id, created_at: mandate_new .created_at .unwrap_or_else(common_utils::date_time::now), mandate_amount: mandate_new.mandate_amount, mandate_currency: mandate_new.mandate_currency, amount_captured: mandate_new.amount_captured, connector: mandate_new.connector, connector_mandate_id: mandate_new.connector_mandate_id, start_date: mandate_new.start_date, end_date: mandate_new.end_date, metadata: mandate_new.metadata, connector_mandate_ids: mandate_new.connector_mandate_ids, merchant_connector_id: mandate_new.merchant_connector_id, updated_by: mandate_new.updated_by, }; mandates.push(mandate.clone()); Ok(mandate) } }
5,733
1,470
hyperswitch
crates/router/src/db/gsm.rs
.rs
use diesel_models::gsm as storage; use error_stack::report; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait GsmInterface { async fn add_gsm_rule( &self, rule: storage::GatewayStatusMappingNew, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError>; async fn find_gsm_decision( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<String, errors::StorageError>; async fn find_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError>; async fn update_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, data: storage::GatewayStatusMappingUpdate, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError>; async fn delete_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<bool, errors::StorageError>; } #[async_trait::async_trait] impl GsmInterface for Store { #[instrument(skip_all)] async fn add_gsm_rule( &self, rule: storage::GatewayStatusMappingNew, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; rule.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_gsm_decision( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<String, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::GatewayStatusMap::retrieve_decision( &conn, connector, flow, sub_flow, code, message, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::GatewayStatusMap::find(&conn, connector, flow, sub_flow, code, message) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, data: storage::GatewayStatusMappingUpdate, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::GatewayStatusMap::update(&conn, connector, flow, sub_flow, code, message, data) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_gsm_rule( &self, connector: String, flow: String, sub_flow: String, code: String, message: String, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::GatewayStatusMap::delete(&conn, connector, flow, sub_flow, code, message) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl GsmInterface for MockDb { async fn add_gsm_rule( &self, _rule: storage::GatewayStatusMappingNew, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_gsm_decision( &self, _connector: String, _flow: String, _sub_flow: String, _code: String, _message: String, ) -> CustomResult<String, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_gsm_rule( &self, _connector: String, _flow: String, _sub_flow: String, _code: String, _message: String, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_gsm_rule( &self, _connector: String, _flow: String, _sub_flow: String, _code: String, _message: String, _data: storage::GatewayStatusMappingUpdate, ) -> CustomResult<storage::GatewayStatusMap, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn delete_gsm_rule( &self, _connector: String, _flow: String, _sub_flow: String, _code: String, _message: String, ) -> CustomResult<bool, errors::StorageError> { Err(errors::StorageError::MockDbError)? } }
1,281
1,471
hyperswitch
crates/router/src/db/merchant_key_store.rs
.rs
use common_utils::types::keymanager::KeyManagerState; use error_stack::{report, ResultExt}; use masking::Secret; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use storage_impl::redis::cache::{self, CacheKind, ACCOUNTS_CACHE}; use crate::{ connection, core::errors::{self, CustomResult}, db::MockDb, services::Store, types::domain::{ self, behaviour::{Conversion, ReverseConversion}, }, }; #[async_trait::async_trait] pub trait MerchantKeyStoreInterface { async fn insert_merchant_key_store( &self, state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError>; async fn get_merchant_key_store_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError>; async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError>; #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>; async fn get_all_key_stores( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>; } #[async_trait::async_trait] impl MerchantKeyStoreInterface for Store { #[instrument(skip_all)] async fn insert_merchant_key_store( &self, state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; let merchant_id = merchant_key_store.merchant_id.clone(); merchant_key_store .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert(state, key, merchant_id.into()) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn get_merchant_key_store_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { let fetch_func = || async { let conn = connection::pg_accounts_connection_read(self).await?; diesel_models::merchant_key_store::MerchantKeyStore::find_by_merchant_id( &conn, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { fetch_func() .await? .convert(state, key, merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "accounts_cache")] { let key_store_cache_key = format!("merchant_key_store_{}", merchant_id.get_string_repr()); cache::get_or_populate_in_memory( self, &key_store_cache_key, fetch_func, &ACCOUNTS_CACHE, ) .await? .convert(state, key, merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) } } #[instrument(skip_all)] async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let delete_func = || async { let conn = connection::pg_accounts_connection_write(self).await?; diesel_models::merchant_key_store::MerchantKeyStore::delete_by_merchant_id( &conn, merchant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { delete_func().await } #[cfg(feature = "accounts_cache")] { let key_store_cache_key = format!("merchant_key_store_{}", merchant_id.get_string_repr()); cache::publish_and_redact( self, CacheKind::Accounts(key_store_cache_key.into()), delete_func, ) .await } } #[cfg(feature = "olap")] #[instrument(skip_all)] async fn list_multiple_key_stores( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let fetch_func = || async { let conn = connection::pg_accounts_connection_read(self).await?; diesel_models::merchant_key_store::MerchantKeyStore::list_multiple_key_stores( &conn, merchant_ids, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async { let merchant_id = key_store.merchant_id.clone(); key_store .convert(state, key, merchant_id.into()) .await .change_context(errors::StorageError::DecryptionError) })) .await } async fn get_all_key_stores( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, from: u32, to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; let stores = diesel_models::merchant_key_store::MerchantKeyStore::list_all_key_stores( &conn, from, to, ) .await .map_err(|err| report!(errors::StorageError::from(err)))?; futures::future::try_join_all(stores.into_iter().map(|key_store| async { let merchant_id = key_store.merchant_id.clone(); key_store .convert(state, key, merchant_id.into()) .await .change_context(errors::StorageError::DecryptionError) })) .await } } #[async_trait::async_trait] impl MerchantKeyStoreInterface for MockDb { async fn insert_merchant_key_store( &self, state: &KeyManagerState, merchant_key_store: domain::MerchantKeyStore, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { let mut locked_merchant_key_store = self.merchant_key_store.lock().await; if locked_merchant_key_store .iter() .any(|merchant_key| merchant_key.merchant_id == merchant_key_store.merchant_id) { Err(errors::StorageError::DuplicateValue { entity: "merchant_key_store", key: Some(merchant_key_store.merchant_id.get_string_repr().to_owned()), })?; } let merchant_key = Conversion::convert(merchant_key_store) .await .change_context(errors::StorageError::MockDbError)?; locked_merchant_key_store.push(merchant_key.clone()); let merchant_id = merchant_key.merchant_id.clone(); merchant_key .convert(state, key, merchant_id.into()) .await .change_context(errors::StorageError::DecryptionError) } async fn get_merchant_key_store_by_merchant_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key: &Secret<Vec<u8>>, ) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> { self.merchant_key_store .lock() .await .iter() .find(|merchant_key| merchant_key.merchant_id == *merchant_id) .cloned() .ok_or(errors::StorageError::ValueNotFound(String::from( "merchant_key_store", )))? .convert(state, key, merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) } async fn delete_merchant_key_store_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let mut merchant_key_stores = self.merchant_key_store.lock().await; let index = merchant_key_stores .iter() .position(|mks| mks.merchant_id == *merchant_id) .ok_or(errors::StorageError::ValueNotFound(format!( "No merchant key store found for merchant_id = {:?}", merchant_id )))?; merchant_key_stores.remove(index); Ok(true) } #[cfg(feature = "olap")] async fn list_multiple_key_stores( &self, state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, key: &Secret<Vec<u8>>, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let merchant_key_stores = self.merchant_key_store.lock().await; futures::future::try_join_all( merchant_key_stores .iter() .filter(|merchant_key| merchant_ids.contains(&merchant_key.merchant_id)) .map(|merchant_key| async { merchant_key .to_owned() .convert(state, key, merchant_key.merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) }), ) .await } async fn get_all_key_stores( &self, state: &KeyManagerState, key: &Secret<Vec<u8>>, _from: u32, _to: u32, ) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> { let merchant_key_stores = self.merchant_key_store.lock().await; futures::future::try_join_all(merchant_key_stores.iter().map(|merchant_key| async { merchant_key .to_owned() .convert(state, key, merchant_key.merchant_id.clone().into()) .await .change_context(errors::StorageError::DecryptionError) })) .await } } #[cfg(test)] mod tests { use std::{borrow::Cow, sync::Arc}; use common_utils::{type_name, types::keymanager::Identifier}; use time::macros::datetime; use tokio::sync::oneshot; use crate::{ db::{merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb}, routes::{ self, app::{settings::Settings, StorageImpl}, }, services, types::domain, }; #[allow(clippy::unwrap_used, clippy::expect_used)] #[tokio::test] async fn test_mock_db_merchant_key_store_interface() { let conf = Settings::new().expect("invalid settings"); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = &Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); #[allow(clippy::expect_used)] let mock_db = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create mock DB"); let master_key = mock_db.get_master_key(); let merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("merchant1")).unwrap(); let identifier = Identifier::Merchant(merchant_id.clone()); let key_manager_state = &state.into(); let merchant_key1 = mock_db .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), identifier.clone(), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await .unwrap(); let found_merchant_key1 = mock_db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &master_key.to_vec().into(), ) .await .unwrap(); assert_eq!(found_merchant_key1.merchant_id, merchant_key1.merchant_id); assert_eq!(found_merchant_key1.key, merchant_key1.key); let insert_duplicate_merchant_key1_result = mock_db .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), identifier.clone(), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await; assert!(insert_duplicate_merchant_key1_result.is_err()); let non_existent_merchant_id = common_utils::id_type::MerchantId::try_from(Cow::from("non_existent")).unwrap(); let find_non_existent_merchant_key_result = mock_db .get_merchant_key_store_by_merchant_id( key_manager_state, &non_existent_merchant_id, &master_key.to_vec().into(), ) .await; assert!(find_non_existent_merchant_key_result.is_err()); let find_merchant_key_with_incorrect_master_key_result = mock_db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &vec![0; 32].into(), ) .await; assert!(find_merchant_key_with_incorrect_master_key_result.is_err()); } }
3,424
1,472
hyperswitch
crates/router/src/db/blocklist_fingerprint.rs
.rs
use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::MockDb; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, types::storage, }; #[async_trait::async_trait] pub trait BlocklistFingerprintInterface { async fn insert_blocklist_fingerprint_entry( &self, pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError>; async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError>; } #[async_trait::async_trait] impl BlocklistFingerprintInterface for Store { #[instrument(skip_all)] async fn insert_blocklist_fingerprint_entry( &self, pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; pm_fingerprint_new .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::BlocklistFingerprint::find_by_merchant_id_fingerprint_id( &conn, merchant_id, fingerprint_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl BlocklistFingerprintInterface for MockDb { async fn insert_blocklist_fingerprint_entry( &self, _pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint_id: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl BlocklistFingerprintInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_fingerprint_entry( &self, pm_fingerprint_new: storage::BlocklistFingerprintNew, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { self.diesel_store .insert_blocklist_fingerprint_entry(pm_fingerprint_new) .await } #[instrument(skip_all)] async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> { self.diesel_store .find_blocklist_fingerprint_by_merchant_id_fingerprint_id(merchant_id, fingerprint) .await } }
779
1,473
hyperswitch
crates/router/src/db/blocklist_lookup.rs
.rs
use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::MockDb; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, types::storage, }; #[async_trait::async_trait] pub trait BlocklistLookupInterface { async fn insert_blocklist_lookup_entry( &self, blocklist_lookup_new: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError>; } #[async_trait::async_trait] impl BlocklistLookupInterface for Store { #[instrument(skip_all)] async fn insert_blocklist_lookup_entry( &self, blocklist_lookup_entry: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; blocklist_lookup_entry .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::BlocklistLookup::find_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::BlocklistLookup::delete_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl BlocklistLookupInterface for MockDb { #[instrument(skip_all)] async fn insert_blocklist_lookup_entry( &self, _blocklist_lookup_entry: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl BlocklistLookupInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_lookup_entry( &self, blocklist_lookup_entry: storage::BlocklistLookupNew, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { self.diesel_store .insert_blocklist_lookup_entry(blocklist_lookup_entry) .await } #[instrument(skip_all)] async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { self.diesel_store .find_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint) .await } #[instrument(skip_all)] async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::BlocklistLookup, errors::StorageError> { self.diesel_store .delete_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint) .await } }
1,091
1,474
hyperswitch
crates/router/src/db/merchant_connector_account.rs
.rs
use async_bb8_diesel::AsyncConnection; use common_utils::{ encryption::Encryption, ext_traits::{AsyncExt, ByteSliceExt, Encode}, types::keymanager::KeyManagerState, }; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; #[cfg(feature = "accounts_cache")] use storage_impl::redis::cache; use storage_impl::redis::kv_store::RedisConnInterface; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::{ self, domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage, }, }; #[async_trait::async_trait] pub trait ConnectorAccessToken { async fn get_access_token( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id_or_connector_name: &str, ) -> CustomResult<Option<types::AccessToken>, errors::StorageError>; async fn set_access_token( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id_or_connector_name: &str, access_token: types::AccessToken, ) -> CustomResult<(), errors::StorageError>; } #[async_trait::async_trait] impl ConnectorAccessToken for Store { #[instrument(skip_all)] async fn get_access_token( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id_or_connector_name: &str, ) -> CustomResult<Option<types::AccessToken>, errors::StorageError> { //TODO: Handle race condition // This function should acquire a global lock on some resource, if access token is already // being refreshed by other request then wait till it finishes and use the same access token let key = common_utils::access_token::create_access_token_key( merchant_id, merchant_connector_id_or_connector_name, ); let maybe_token = self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .get_key::<Option<Vec<u8>>>(&key.into()) .await .change_context(errors::StorageError::KVError) .attach_printable("DB error when getting access token")?; let access_token = maybe_token .map(|token| token.parse_struct::<types::AccessToken>("AccessToken")) .transpose() .change_context(errors::StorageError::DeserializationFailed)?; Ok(access_token) } #[instrument(skip_all)] async fn set_access_token( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id_or_connector_name: &str, access_token: types::AccessToken, ) -> CustomResult<(), errors::StorageError> { let key = common_utils::access_token::create_access_token_key( merchant_id, merchant_connector_id_or_connector_name, ); let serialized_access_token = access_token .encode_to_string_of_json() .change_context(errors::StorageError::SerializationFailed)?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .set_key_with_expiry(&key.into(), serialized_access_token, access_token.expires) .await .change_context(errors::StorageError::KVError) } } #[async_trait::async_trait] impl ConnectorAccessToken for MockDb { async fn get_access_token( &self, _merchant_id: &common_utils::id_type::MerchantId, _merchant_connector_id_or_connector_name: &str, ) -> CustomResult<Option<types::AccessToken>, errors::StorageError> { Ok(None) } async fn set_access_token( &self, _merchant_id: &common_utils::id_type::MerchantId, _merchant_connector_id_or_connector_name: &str, _access_token: types::AccessToken, ) -> CustomResult<(), errors::StorageError> { Ok(()) } } #[async_trait::async_trait] pub trait MerchantConnectorAccountInterface where domain::MerchantConnectorAccount: Conversion< DstType = storage::MerchantConnectorAccount, NewDstType = storage::MerchantConnectorAccountNew, >, { #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_label: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>; #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>; #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError>; async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>; #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>; #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>; async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, errors::StorageError>; #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError>; #[cfg(all(feature = "oltp", feature = "v2"))] async fn list_enabled_connector_accounts_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &domain::MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError>; async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>; async fn update_multiple_merchant_connector_accounts( &self, this: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), errors::StorageError>; #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, errors::StorageError>; #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, errors::StorageError>; } #[async_trait::async_trait] impl MerchantConnectorAccountInterface for Store { #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_label: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let find_call = || async { let conn = connection::pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_merchant_id_connector( &conn, merchant_id, connector_label, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert(state, key_store.key.get_inner(), merchant_id.clone().into()) .await .change_context(errors::StorageError::DeserializationFailed) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &format!("{}_{}", merchant_id.get_string_repr(), connector_label), find_call, &cache::ACCOUNTS_CACHE, ) .await .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let find_call = || async { let conn = connection::pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_profile_id_connector_name( &conn, profile_id, connector_name, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DeserializationFailed) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &format!("{}_{}", profile_id.get_string_repr(), connector_name), find_call, &cache::ACCOUNTS_CACHE, ) .await .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } } #[cfg(feature = "v1")] #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_merchant_id_connector_name( &conn, merchant_id, connector_name, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) }) .await } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let find_call = || async { let conn = connection::pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id( &conn, merchant_id, merchant_connector_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, &format!( "{}_{}", merchant_id.get_string_repr(), merchant_connector_id.get_string_repr() ), find_call, &cache::ACCOUNTS_CACHE, ) .await? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let find_call = || async { let conn = connection::pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::find_by_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(not(feature = "accounts_cache"))] { find_call() .await? .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "accounts_cache")] { cache::get_or_populate_in_memory( self, id.get_string_repr(), find_call, &cache::ACCOUNTS_CACHE, ) .await? .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(errors::StorageError::DecryptionError) } } #[instrument(skip_all)] async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; t.construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await } #[cfg(all(feature = "oltp", feature = "v2"))] async fn list_enabled_connector_accounts_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &domain::MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::list_enabled_by_profile_id( &conn, profile_id, connector_type, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) }) .await } #[instrument(skip_all)] async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; let merchant_connector_account_vec = storage::MerchantConnectorAccount::find_by_merchant_id( &conn, merchant_id, get_disabled, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) }) .await?; Ok(domain::MerchantConnectorAccounts::new( merchant_connector_account_vec, )) } #[instrument(skip_all)] #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; storage::MerchantConnectorAccount::list_by_profile_id(&conn, profile_id) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|items| async { let mut output = Vec::with_capacity(items.len()); for item in items.into_iter() { output.push( item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) }) .await } #[instrument(skip_all)] async fn update_multiple_merchant_connector_accounts( &self, merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; async fn update_call( connection: &diesel_models::PgPooledConn, (merchant_connector_account, mca_update): ( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, ), ) -> Result<(), error_stack::Report<storage_impl::errors::StorageError>> { Conversion::convert(merchant_connector_account) .await .change_context(errors::StorageError::EncryptionError)? .update(connection, mca_update) .await .map_err(|error| report!(errors::StorageError::from(error)))?; Ok(()) } conn.transaction_async(|connection_pool| async move { for (merchant_connector_account, update_merchant_connector_account) in merchant_connector_accounts { #[cfg(feature = "v1")] let _connector_name = merchant_connector_account.connector_name.clone(); #[cfg(feature = "v2")] let _connector_name = merchant_connector_account.connector_name.to_string(); let _profile_id = merchant_connector_account.profile_id.clone(); let _merchant_id = merchant_connector_account.merchant_id.clone(); let _merchant_connector_id = merchant_connector_account.get_id().clone(); let update = update_call( &connection_pool, ( merchant_connector_account, update_merchant_connector_account, ), ); #[cfg(feature = "accounts_cache")] // Redact all caches as any of might be used because of backwards compatibility Box::pin(cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( format!( "{}_{}", _merchant_id.get_string_repr(), _merchant_connector_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], || update, )) .await .map_err(|error| { // Returning `DatabaseConnectionError` after logging the actual error because // -> it is not possible to get the underlying from `error_stack::Report<C>` // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` // because of Rust's orphan rules router_env::logger::error!( ?error, "DB transaction for updating multiple merchant connector account failed" ); errors::StorageError::DatabaseConnectionError })?; #[cfg(not(feature = "accounts_cache"))] { update.await.map_err(|error| { // Returning `DatabaseConnectionError` after logging the actual error because // -> it is not possible to get the underlying from `error_stack::Report<C>` // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>` // because of Rust's orphan rules router_env::logger::error!( ?error, "DB transaction for updating multiple merchant connector account failed" ); errors::StorageError::DatabaseConnectionError })?; } } Ok::<_, errors::StorageError>(()) }) .await?; Ok(()) } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let _connector_name = this.connector_name.clone(); let _profile_id = this.profile_id.clone(); let _merchant_id = this.merchant_id.clone(); let _merchant_connector_id = this.merchant_connector_id.clone(); let update_call = || async { let conn = connection::pg_accounts_connection_write(self).await?; Conversion::convert(this) .await .change_context(errors::StorageError::EncryptionError)? .update(&conn, merchant_connector_account) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await }; #[cfg(feature = "accounts_cache")] { // Redact all caches as any of might be used because of backwards compatibility cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( format!( "{}_{}", _merchant_id.get_string_repr(), _merchant_connector_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr(), ) .into(), ), ], update_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { update_call().await } } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let _connector_name = this.connector_name; let _profile_id = this.profile_id.clone(); let _merchant_id = this.merchant_id.clone(); let _merchant_connector_id = this.get_id().clone(); let update_call = || async { let conn = connection::pg_accounts_connection_write(self).await?; Conversion::convert(this) .await .change_context(errors::StorageError::EncryptionError)? .update(&conn, merchant_connector_account) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|item| async { item.convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(errors::StorageError::DecryptionError) }) .await }; #[cfg(feature = "accounts_cache")] { // Redact all caches as any of might be used because of backwards compatibility cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(), ), cache::CacheKind::Accounts( _merchant_connector_id.get_string_repr().to_string().into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", _merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], update_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { update_call().await } } #[instrument(skip_all)] #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; let delete_call = || async { storage::MerchantConnectorAccount::delete_by_merchant_id_merchant_connector_id( &conn, merchant_id, merchant_connector_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(feature = "accounts_cache")] { // We need to fetch mca here because the key that's saved in cache in // {merchant_id}_{connector_label}. // Used function from storage model to reuse the connection that made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id( &conn, merchant_id, merchant_connector_id, ) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let _profile_id = mca.profile_id.ok_or(errors::StorageError::ValueNotFound( "profile_id".to_string(), ))?; cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!( "{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], delete_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { delete_call().await } } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; let delete_call = || async { storage::MerchantConnectorAccount::delete_by_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) }; #[cfg(feature = "accounts_cache")] { // We need to fetch mca here because the key that's saved in cache in // {merchant_id}_{connector_label}. // Used function from storage model to reuse the connection that made here instead of // creating new. let mca = storage::MerchantConnectorAccount::find_by_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error)))?; let _profile_id = mca.profile_id; cache::publish_and_redact_multiple( self, [ cache::CacheKind::Accounts( format!( "{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::CGraph( format!( "cgraph_{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), cache::CacheKind::PmFiltersCGraph( format!( "pm_filters_cgraph_{}_{}", mca.merchant_id.get_string_repr(), _profile_id.get_string_repr() ) .into(), ), ], delete_call, ) .await } #[cfg(not(feature = "accounts_cache"))] { delete_call().await } } } #[async_trait::async_trait] impl MerchantConnectorAccountInterface for MockDb { async fn update_multiple_merchant_connector_accounts( &self, _merchant_connector_accounts: Vec<( domain::MerchantConnectorAccount, storage::MerchantConnectorAccountUpdateInternal, )>, ) -> CustomResult<(), errors::StorageError> { // No need to implement this function for `MockDb` as this function will be removed after the // apple pay certificate migration Err(errors::StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_label( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { match self .merchant_connector_accounts .lock() .await .iter() .find(|account| { account.merchant_id == *merchant_id && account.connector_label == Some(connector.to_string()) }) .cloned() .async_map(|account| async { account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await { Some(result) => result, None => { return Err(errors::StorageError::ValueNotFound( "cannot find merchant connector account".to_string(), ) .into()) } } } #[cfg(all(feature = "oltp", feature = "v2"))] async fn list_enabled_connector_accounts_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &domain::MerchantKeyStore, connector_type: common_enums::ConnectorType, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { todo!() } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_merchant_id_connector_name( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { let accounts = self .merchant_connector_accounts .lock() .await .iter() .filter(|account| { account.merchant_id == *merchant_id && account.connector_name == connector_name }) .cloned() .collect::<Vec<_>>(); let mut output = Vec::with_capacity(accounts.len()); for account in accounts.into_iter() { output.push( account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) } #[cfg(feature = "v1")] async fn find_merchant_connector_account_by_profile_id_connector_name( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, connector_name: &str, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let maybe_mca = self .merchant_connector_accounts .lock() .await .iter() .find(|account| { account.profile_id.eq(&Some(profile_id.to_owned())) && account.connector_name == connector_name }) .cloned(); match maybe_mca { Some(mca) => mca .to_owned() .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError), None => Err(errors::StorageError::ValueNotFound( "cannot find merchant connector account".to_string(), ) .into()), } } #[cfg(feature = "v1")] async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { match self .merchant_connector_accounts .lock() .await .iter() .find(|account| { account.merchant_id == *merchant_id && account.merchant_connector_id == *merchant_connector_id }) .cloned() .async_map(|account| async { account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await { Some(result) => result, None => { return Err(errors::StorageError::ValueNotFound( "cannot find merchant connector account".to_string(), ) .into()) } } } #[cfg(feature = "v2")] async fn find_merchant_connector_account_by_id( &self, state: &KeyManagerState, id: &common_utils::id_type::MerchantConnectorAccountId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { match self .merchant_connector_accounts .lock() .await .iter() .find(|account| account.get_id() == *id) .cloned() .async_map(|account| async { account .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(errors::StorageError::DecryptionError) }) .await { Some(result) => result, None => { return Err(errors::StorageError::ValueNotFound( "cannot find merchant connector account".to_string(), ) .into()) } } } #[cfg(feature = "v1")] async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let mut accounts = self.merchant_connector_accounts.lock().await; let account = storage::MerchantConnectorAccount { merchant_id: t.merchant_id, connector_name: t.connector_name, connector_account_details: t.connector_account_details.into(), test_mode: t.test_mode, disabled: t.disabled, merchant_connector_id: t.merchant_connector_id.clone(), id: Some(t.merchant_connector_id), payment_methods_enabled: t.payment_methods_enabled, metadata: t.metadata, frm_configs: None, frm_config: t.frm_configs, connector_type: t.connector_type, connector_label: t.connector_label, business_country: t.business_country, business_label: t.business_label, business_sub_label: t.business_sub_label, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), connector_webhook_details: t.connector_webhook_details, profile_id: Some(t.profile_id), applepay_verified_domains: t.applepay_verified_domains, pm_auth_config: t.pm_auth_config, status: t.status, connector_wallets_details: t.connector_wallets_details.map(Encryption::from), additional_merchant_data: t.additional_merchant_data.map(|data| data.into()), version: t.version, }; accounts.push(account.clone()); account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[cfg(feature = "v2")] async fn insert_merchant_connector_account( &self, state: &KeyManagerState, t: domain::MerchantConnectorAccount, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let mut accounts = self.merchant_connector_accounts.lock().await; let account = storage::MerchantConnectorAccount { id: t.id, merchant_id: t.merchant_id, connector_name: t.connector_name, connector_account_details: t.connector_account_details.into(), disabled: t.disabled, payment_methods_enabled: t.payment_methods_enabled, metadata: t.metadata, frm_config: t.frm_configs, connector_type: t.connector_type, connector_label: t.connector_label, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), connector_webhook_details: t.connector_webhook_details, profile_id: t.profile_id, applepay_verified_domains: t.applepay_verified_domains, pm_auth_config: t.pm_auth_config, status: t.status, connector_wallets_details: t.connector_wallets_details.map(Encryption::from), additional_merchant_data: t.additional_merchant_data.map(|data| data.into()), version: t.version, feature_metadata: t.feature_metadata.map(From::from), }; accounts.push(account.clone()); account .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_merchant_connector_account_by_merchant_id_and_disabled_list( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, get_disabled: bool, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccounts, errors::StorageError> { let accounts = self .merchant_connector_accounts .lock() .await .iter() .filter(|account: &&storage::MerchantConnectorAccount| { if get_disabled { account.merchant_id == *merchant_id } else { account.merchant_id == *merchant_id && account.disabled == Some(false) } }) .cloned() .collect::<Vec<storage::MerchantConnectorAccount>>(); let mut output = Vec::with_capacity(accounts.len()); for account in accounts.into_iter() { output.push( account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ) } Ok(domain::MerchantConnectorAccounts::new(output)) } #[cfg(all(feature = "olap", feature = "v2"))] async fn list_connector_account_by_profile_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> { let accounts = self .merchant_connector_accounts .lock() .await .iter() .filter(|account: &&storage::MerchantConnectorAccount| { account.profile_id == *profile_id }) .cloned() .collect::<Vec<storage::MerchantConnectorAccount>>(); let mut output = Vec::with_capacity(accounts.len()); for account in accounts.into_iter() { output.push( account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ) } Ok(output) } #[cfg(feature = "v1")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let mca_update_res = self .merchant_connector_accounts .lock() .await .iter_mut() .find(|account| account.merchant_connector_id == this.merchant_connector_id) .map(|a| { let updated = merchant_connector_account.create_merchant_connector_account(a.clone()); *a = updated.clone(); updated }) .async_map(|account| async { account .convert( state, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await; match mca_update_res { Some(result) => result, None => { return Err(errors::StorageError::ValueNotFound( "cannot find merchant connector account to update".to_string(), ) .into()) } } } #[cfg(feature = "v2")] async fn update_merchant_connector_account( &self, state: &KeyManagerState, this: domain::MerchantConnectorAccount, merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal, key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let mca_update_res = self .merchant_connector_accounts .lock() .await .iter_mut() .find(|account| account.get_id() == this.get_id()) .map(|a| { let updated = merchant_connector_account.create_merchant_connector_account(a.clone()); *a = updated.clone(); updated }) .async_map(|account| async { account .convert( state, key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( key_store.merchant_id.clone(), ), ) .await .change_context(errors::StorageError::DecryptionError) }) .await; match mca_update_res { Some(result) => result, None => { return Err(errors::StorageError::ValueNotFound( "cannot find merchant connector account to update".to_string(), ) .into()) } } } #[cfg(feature = "v1")] async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &self, merchant_id: &common_utils::id_type::MerchantId, merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, errors::StorageError> { let mut accounts = self.merchant_connector_accounts.lock().await; match accounts.iter().position(|account| { account.merchant_id == *merchant_id && account.merchant_connector_id == *merchant_connector_id }) { Some(index) => { accounts.remove(index); return Ok(true); } None => { return Err(errors::StorageError::ValueNotFound( "cannot find merchant connector account to delete".to_string(), ) .into()) } } } #[cfg(feature = "v2")] async fn delete_merchant_connector_account_by_id( &self, id: &common_utils::id_type::MerchantConnectorAccountId, ) -> CustomResult<bool, errors::StorageError> { let mut accounts = self.merchant_connector_accounts.lock().await; match accounts.iter().position(|account| account.get_id() == *id) { Some(index) => { accounts.remove(index); return Ok(true); } None => { return Err(errors::StorageError::ValueNotFound( "cannot find merchant connector account to delete".to_string(), ) .into()) } } } } #[cfg(feature = "accounts_cache")] #[cfg(test)] mod merchant_connector_account_cache_tests { use std::sync::Arc; #[cfg(feature = "v1")] use api_models::enums::CountryAlpha2; use common_utils::{date_time, type_name, types::keymanager::Identifier}; use diesel_models::enums::ConnectorType; use error_stack::ResultExt; use masking::PeekInterface; use storage_impl::redis::{ cache::{self, CacheKey, CacheKind, ACCOUNTS_CACHE}, kv_store::RedisConnInterface, pub_sub::PubSubInterface, }; use time::macros::datetime; use tokio::sync::oneshot; use crate::{ core::errors, db::{ merchant_connector_account::MerchantConnectorAccountInterface, merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb, }, routes::{ self, app::{settings::Settings, StorageImpl}, }, services, types::{ domain::{self, behaviour::Conversion}, storage, }, }; #[allow(clippy::unwrap_used)] #[tokio::test] #[cfg(feature = "v1")] async fn test_connector_profile_id_cache() { let conf = Settings::new().unwrap(); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = &Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); #[allow(clippy::expect_used)] let db = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let redis_conn = db.get_redis_conn().unwrap(); let master_key = db.get_master_key(); redis_conn .subscribe("hyperswitch_invalidate") .await .unwrap(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("test_merchant")) .unwrap(); let connector_label = "stripe_USA"; let merchant_connector_id = "simple_merchant_connector_id"; let profile_id = common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("pro_max_ultra")) .unwrap(); let key_manager_state = &state.into(); db.insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), Identifier::Merchant(merchant_id.clone()), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await .unwrap(); let merchant_key = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &master_key.to_vec().into(), ) .await .unwrap(); let mca = domain::MerchantConnectorAccount { merchant_id: merchant_id.to_owned(), connector_name: "stripe".to_string(), connector_account_details: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()), Identifier::Merchant(merchant_key.merchant_id.clone()), merchant_key.key.get_inner().peek(), ) .await .and_then(|val| val.try_into_operation()) .unwrap(), test_mode: None, disabled: None, merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId::wrap( merchant_connector_id.to_string(), ) .unwrap(), payment_methods_enabled: None, connector_type: ConnectorType::FinOperations, metadata: None, frm_configs: None, connector_label: Some(connector_label.to_string()), business_country: Some(CountryAlpha2::US), business_label: Some("cloth".to_string()), business_sub_label: None, created_at: date_time::now(), modified_at: date_time::now(), connector_webhook_details: None, profile_id: profile_id.to_owned(), applepay_verified_domains: None, pm_auth_config: None, status: common_enums::ConnectorStatus::Inactive, connector_wallets_details: Some( domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()), Identifier::Merchant(merchant_key.merchant_id.clone()), merchant_key.key.get_inner().peek(), ) .await .and_then(|val| val.try_into_operation()) .unwrap(), ), additional_merchant_data: None, version: common_types::consts::API_VERSION, }; db.insert_merchant_connector_account(key_manager_state, mca.clone(), &merchant_key) .await .unwrap(); let find_call = || async { Conversion::convert( db.find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, &profile_id, &mca.connector_name, &merchant_key, ) .await .unwrap(), ) .await .change_context(errors::StorageError::DecryptionError) }; let _: storage::MerchantConnectorAccount = cache::get_or_populate_in_memory( &db, &format!( "{}_{}", merchant_id.get_string_repr(), profile_id.get_string_repr(), ), find_call, &ACCOUNTS_CACHE, ) .await .unwrap(); let delete_call = || async { db.delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &merchant_id, &common_utils::id_type::MerchantConnectorAccountId::wrap( merchant_connector_id.to_string(), ) .unwrap(), ) .await }; cache::publish_and_redact( &db, CacheKind::Accounts( format!("{}_{}", merchant_id.get_string_repr(), connector_label).into(), ), delete_call, ) .await .unwrap(); assert!(ACCOUNTS_CACHE .get_val::<domain::MerchantConnectorAccount>(CacheKey { key: format!("{}_{}", merchant_id.get_string_repr(), connector_label), prefix: String::default(), },) .await .is_none()) } #[allow(clippy::unwrap_used)] #[tokio::test] #[cfg(feature = "v2")] async fn test_connector_profile_id_cache() { let conf = Settings::new().unwrap(); let tx: oneshot::Sender<()> = oneshot::channel().0; let app_state = Box::pin(routes::AppState::with_storage( conf, StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = &Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); #[allow(clippy::expect_used)] let db = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let redis_conn = db.get_redis_conn().unwrap(); let master_key = db.get_master_key(); redis_conn .subscribe("hyperswitch_invalidate") .await .unwrap(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("test_merchant")) .unwrap(); let connector_label = "stripe_USA"; let id = common_utils::generate_merchant_connector_account_id_of_default_length(); let profile_id = common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("pro_max_ultra")) .unwrap(); let key_manager_state = &state.into(); db.insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), Identifier::Merchant(merchant_id.clone()), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await .unwrap(); let merchant_key = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &master_key.to_vec().into(), ) .await .unwrap(); let mca = domain::MerchantConnectorAccount { id: id.clone(), merchant_id: merchant_id.clone(), connector_name: common_enums::connector_enums::Connector::Stripe, connector_account_details: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()), Identifier::Merchant(merchant_key.merchant_id.clone()), merchant_key.key.get_inner().peek(), ) .await .and_then(|val| val.try_into_operation()) .unwrap(), disabled: None, payment_methods_enabled: None, connector_type: ConnectorType::FinOperations, metadata: None, frm_configs: None, connector_label: Some(connector_label.to_string()), created_at: date_time::now(), modified_at: date_time::now(), connector_webhook_details: None, profile_id: profile_id.to_owned(), applepay_verified_domains: None, pm_auth_config: None, status: common_enums::ConnectorStatus::Inactive, connector_wallets_details: Some( domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantConnectorAccount), domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()), Identifier::Merchant(merchant_key.merchant_id.clone()), merchant_key.key.get_inner().peek(), ) .await .and_then(|val| val.try_into_operation()) .unwrap(), ), additional_merchant_data: None, version: common_types::consts::API_VERSION, feature_metadata: None, }; db.insert_merchant_connector_account(key_manager_state, mca.clone(), &merchant_key) .await .unwrap(); let find_call = || async { #[cfg(feature = "v1")] let mca = db .find_merchant_connector_account_by_profile_id_connector_name( key_manager_state, profile_id, &mca.connector_name, &merchant_key, ) .await .unwrap(); #[cfg(feature = "v2")] let mca: domain::MerchantConnectorAccount = { todo!() }; Conversion::convert(mca) .await .change_context(errors::StorageError::DecryptionError) }; let _: storage::MerchantConnectorAccount = cache::get_or_populate_in_memory( &db, &format!( "{}_{}", merchant_id.clone().get_string_repr(), profile_id.get_string_repr() ), find_call, &ACCOUNTS_CACHE, ) .await .unwrap(); let delete_call = || async { db.delete_merchant_connector_account_by_id(&id).await }; cache::publish_and_redact( &db, CacheKind::Accounts( format!("{}_{}", merchant_id.get_string_repr(), connector_label).into(), ), delete_call, ) .await .unwrap(); assert!(ACCOUNTS_CACHE .get_val::<domain::MerchantConnectorAccount>(CacheKey { key: format!("{}_{}", merchant_id.get_string_repr(), connector_label), prefix: String::default(), },) .await .is_none()) } }
13,570
1,475
hyperswitch
crates/router/src/db/user_role.rs
.rs
use common_utils::id_type; use diesel_models::{ enums::{self, UserStatus}, user_role as storage, }; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; pub struct ListUserRolesByOrgIdPayload<'a> { pub user_id: Option<&'a String>, pub tenant_id: &'a id_type::TenantId, pub org_id: &'a id_type::OrganizationId, pub merchant_id: Option<&'a id_type::MerchantId>, pub profile_id: Option<&'a id_type::ProfileId>, pub version: Option<enums::UserRoleVersion>, pub limit: Option<u32>, } pub struct ListUserRolesByUserIdPayload<'a> { pub user_id: &'a str, pub tenant_id: &'a id_type::TenantId, pub org_id: Option<&'a id_type::OrganizationId>, pub merchant_id: Option<&'a id_type::MerchantId>, pub profile_id: Option<&'a id_type::ProfileId>, pub entity_id: Option<&'a String>, pub version: Option<enums::UserRoleVersion>, pub status: Option<UserStatus>, pub limit: Option<u32>, } #[async_trait::async_trait] pub trait UserRoleInterface { async fn insert_user_role( &self, user_role: storage::UserRoleNew, ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; #[allow(clippy::too_many_arguments)] async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, update: storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn list_user_roles_by_user_id<'a>( &self, payload: ListUserRolesByUserIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; async fn list_user_roles_by_user_id_across_tenants( &self, user_id: &str, limit: Option<u32>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; } #[async_trait::async_trait] impl UserRoleInterface for Store { #[instrument(skip_all)] async fn insert_user_role( &self, user_role: storage::UserRoleNew, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; user_role .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserRole::find_by_user_id_tenant_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(), tenant_id.to_owned(), org_id.to_owned(), merchant_id.to_owned(), profile_id.to_owned(), version, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, update: storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UserRole::update_by_user_id_tenant_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(), tenant_id.to_owned(), org_id.to_owned(), merchant_id.cloned(), profile_id.cloned(), update, version, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::UserRole::delete_by_user_id_tenant_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(), tenant_id.to_owned(), org_id.to_owned(), merchant_id.to_owned(), profile_id.to_owned(), version, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn list_user_roles_by_user_id<'a>( &self, payload: ListUserRolesByUserIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserRole::generic_user_roles_list_for_user( &conn, payload.user_id.to_owned(), payload.tenant_id.to_owned(), payload.org_id.cloned(), payload.merchant_id.cloned(), payload.profile_id.cloned(), payload.entity_id.cloned(), payload.status, payload.version, payload.limit, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn list_user_roles_by_user_id_across_tenants( &self, user_id: &str, limit: Option<u32>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserRole::list_user_roles_by_user_id_across_tenants( &conn, user_id.to_owned(), limit, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::UserRole::generic_user_roles_list_for_org_and_extra( &conn, payload.user_id.cloned(), payload.tenant_id.to_owned(), payload.org_id.to_owned(), payload.merchant_id.cloned(), payload.profile_id.cloned(), payload.version, payload.limit, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl UserRoleInterface for MockDb { async fn insert_user_role( &self, user_role: storage::UserRoleNew, ) -> CustomResult<storage::UserRole, errors::StorageError> { let mut db_user_roles = self.user_roles.lock().await; if db_user_roles .iter() .any(|user_role_inner| user_role_inner.user_id == user_role.user_id) { Err(errors::StorageError::DuplicateValue { entity: "user_id", key: None, })? } let user_role = storage::UserRole { id: i32::try_from(db_user_roles.len()) .change_context(errors::StorageError::MockDbError)?, user_id: user_role.user_id, merchant_id: user_role.merchant_id, role_id: user_role.role_id, status: user_role.status, created_by: user_role.created_by, created_at: user_role.created_at, last_modified: user_role.last_modified, last_modified_by: user_role.last_modified_by, org_id: user_role.org_id, profile_id: None, entity_id: None, entity_type: None, version: enums::UserRoleVersion::V1, tenant_id: user_role.tenant_id, }; db_user_roles.push(user_role.clone()); Ok(user_role) } async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let user_roles = self.user_roles.lock().await; for user_role in user_roles.iter() { let tenant_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.is_none() && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); let org_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); let merchant_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == Some(merchant_id) && user_role.profile_id.is_none(); let profile_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == Some(merchant_id) && user_role.profile_id.as_ref() == Some(profile_id); // Check if any condition matches and the version matches if user_role.user_id == user_id && (tenant_level_check || org_level_check || merchant_level_check || profile_level_check) && user_role.version == version { return Ok(user_role.clone()); } } Err(errors::StorageError::ValueNotFound(format!( "No user role available for user_id = {} in the current token hierarchy", user_id )) .into()) } async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, update: storage::UserRoleUpdate, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let mut user_roles = self.user_roles.lock().await; for user_role in user_roles.iter_mut() { let tenant_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.is_none() && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); let org_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); let merchant_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == merchant_id && user_role.profile_id.is_none(); let profile_level_check = user_role.tenant_id == *tenant_id && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == merchant_id && user_role.profile_id.as_ref() == profile_id; // Check if any condition matches and the version matches if user_role.user_id == user_id && (tenant_level_check || org_level_check || merchant_level_check || profile_level_check) && user_role.version == version { match &update { storage::UserRoleUpdate::UpdateRole { role_id, modified_by, } => { user_role.role_id = role_id.to_string(); user_role.last_modified_by = modified_by.to_string(); } storage::UserRoleUpdate::UpdateStatus { status, modified_by, } => { user_role.status = *status; user_role.last_modified_by = modified_by.to_string(); } } return Ok(user_role.clone()); } } Err( errors::StorageError::ValueNotFound("Cannot find user role to update".to_string()) .into(), ) } async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let mut user_roles = self.user_roles.lock().await; // Find the position of the user role to delete let index = user_roles.iter().position(|role| { let tenant_level_check = role.tenant_id == *tenant_id && role.org_id.is_none() && role.merchant_id.is_none() && role.profile_id.is_none(); let org_level_check = role.tenant_id == *tenant_id && role.org_id.as_ref() == Some(org_id) && role.merchant_id.is_none() && role.profile_id.is_none(); let merchant_level_check = role.tenant_id == *tenant_id && role.org_id.as_ref() == Some(org_id) && role.merchant_id.as_ref() == Some(merchant_id) && role.profile_id.is_none(); let profile_level_check = role.tenant_id == *tenant_id && role.org_id.as_ref() == Some(org_id) && role.merchant_id.as_ref() == Some(merchant_id) && role.profile_id.as_ref() == Some(profile_id); // Check if the user role matches the conditions and the version matches role.user_id == user_id && (tenant_level_check || org_level_check || merchant_level_check || profile_level_check) && role.version == version }); // Remove and return the user role if found match index { Some(idx) => Ok(user_roles.remove(idx)), None => Err(errors::StorageError::ValueNotFound( "Cannot find user role to delete".to_string(), ) .into()), } } async fn list_user_roles_by_user_id<'a>( &self, payload: ListUserRolesByUserIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let user_roles = self.user_roles.lock().await; let mut filtered_roles: Vec<_> = user_roles .iter() .filter_map(|role| { let mut filter_condition = role.user_id == payload.user_id; role.org_id .as_ref() .zip(payload.org_id) .inspect(|(role_org_id, org_id)| { filter_condition = filter_condition && role_org_id == org_id }); role.merchant_id.as_ref().zip(payload.merchant_id).inspect( |(role_merchant_id, merchant_id)| { filter_condition = filter_condition && role_merchant_id == merchant_id }, ); role.profile_id.as_ref().zip(payload.profile_id).inspect( |(role_profile_id, profile_id)| { filter_condition = filter_condition && role_profile_id == profile_id }, ); role.entity_id.as_ref().zip(payload.entity_id).inspect( |(role_entity_id, entity_id)| { filter_condition = filter_condition && role_entity_id == entity_id }, ); payload .version .inspect(|ver| filter_condition = filter_condition && ver == &role.version); payload.status.inspect(|status| { filter_condition = filter_condition && status == &role.status }); filter_condition.then(|| role.to_owned()) }) .collect(); if let Some(Ok(limit)) = payload.limit.map(|val| val.try_into()) { filtered_roles = filtered_roles.into_iter().take(limit).collect(); } Ok(filtered_roles) } async fn list_user_roles_by_user_id_across_tenants( &self, user_id: &str, limit: Option<u32>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let user_roles = self.user_roles.lock().await; let filtered_roles: Vec<_> = user_roles .iter() .filter(|role| role.user_id == user_id) .cloned() .collect(); if let Some(Ok(limit)) = limit.map(|val| val.try_into()) { return Ok(filtered_roles.into_iter().take(limit).collect()); } Ok(filtered_roles) } async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { let user_roles = self.user_roles.lock().await; let mut filtered_roles = Vec::new(); for role in user_roles.iter() { let role_org_id = role .org_id .as_ref() .ok_or(report!(errors::StorageError::MockDbError))?; let mut filter_condition = role_org_id == payload.org_id; if let Some(user_id) = payload.user_id { filter_condition = filter_condition && user_id == &role.user_id } role.merchant_id.as_ref().zip(payload.merchant_id).inspect( |(role_merchant_id, merchant_id)| { filter_condition = filter_condition && role_merchant_id == merchant_id }, ); role.profile_id.as_ref().zip(payload.profile_id).inspect( |(role_profile_id, profile_id)| { filter_condition = filter_condition && role_profile_id == profile_id }, ); payload .version .inspect(|ver| filter_condition = filter_condition && ver == &role.version); if filter_condition { filtered_roles.push(role.clone()) } } Ok(filtered_roles) } }
4,387
1,476
hyperswitch
crates/router/src/db/events.rs
.rs
use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage, }, }; #[async_trait::async_trait] pub trait EventInterface where domain::Event: Conversion<DstType = storage::events::Event, NewDstType = storage::events::EventNew>, { async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; #[allow(clippy::too_many_arguments)] async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; #[allow(clippy::too_many_arguments)] async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError>; async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError>; async fn count_initial_events_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError>; } #[async_trait::async_trait] impl EventInterface for Store { #[instrument(skip_all)] async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; event .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::find_by_merchant_id_event_id(&conn, merchant_id, event_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_merchant_id_primary_object_id( &conn, merchant_id, primary_object_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_merchant_id_constraints( &conn, merchant_id, created_after, created_before, limit, offset, is_delivered, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_by_merchant_id_initial_attempt_id( &conn, merchant_id, initial_attempt_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_profile_id_primary_object_id( &conn, profile_id, primary_object_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::list_initial_attempts_by_profile_id_constraints( &conn, profile_id, created_after, created_before, limit, offset, is_delivered, ) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|events| async { let mut domain_events = Vec::with_capacity(events.len()); for event in events.into_iter() { domain_events.push( event .convert( state, merchant_key_store.key.get_inner(), common_utils::types::keymanager::Identifier::Merchant( merchant_key_store.merchant_id.clone(), ), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_events) }) .await } #[instrument(skip_all)] async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Event::update_by_merchant_id_event_id(&conn, merchant_id, event_id, event.into()) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn count_initial_events_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Event::count_initial_attempts_by_constraints( &conn, merchant_id, profile_id, created_after, created_before, is_delivered, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl EventInterface for MockDb { async fn insert_event( &self, state: &KeyManagerState, event: domain::Event, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let mut locked_events = self.events.lock().await; let stored_event = Conversion::convert(event) .await .change_context(errors::StorageError::EncryptionError)?; locked_events.push(stored_event.clone()); stored_event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let locked_events = self.events.lock().await; locked_events .iter() .find(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.event_id == event_id }) .cloned() .async_map(|event| async { event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "No event available with merchant_id = {merchant_id:?} and event_id = {event_id}" )) .into(), ) } async fn list_initial_events_by_merchant_id_primary_object_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events = locked_events .iter() .filter(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && event.primary_object_id == primary_object_id }) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_initial_events_by_merchant_id_constraints( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events_iter = locked_events.iter().filter(|event| { let check = event.merchant_id == Some(merchant_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && (event.created_at >= created_after) && (event.created_at <= created_before) && (event.is_overall_delivery_successful == is_delivered); check }); let offset: usize = if let Some(offset) = offset { if offset < 0 { Err(errors::StorageError::MockDbError)?; } offset .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { 0 }; let limit: usize = if let Some(limit) = limit { if limit < 0 { Err(errors::StorageError::MockDbError)?; } limit .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { usize::MAX }; let events = events_iter .skip(offset) .take(limit) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_events_by_merchant_id_initial_attempt_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, initial_attempt_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events = locked_events .iter() .filter(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.initial_attempt_id == Some(initial_attempt_id.to_owned()) }) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_initial_events_by_profile_id_primary_object_id( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, primary_object_id: &str, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events = locked_events .iter() .filter(|event| { event.business_profile_id == Some(profile_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && event.primary_object_id == primary_object_id }) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn list_initial_events_by_profile_id_constraints( &self, state: &KeyManagerState, profile_id: &common_utils::id_type::ProfileId, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<Vec<domain::Event>, errors::StorageError> { let locked_events = self.events.lock().await; let events_iter = locked_events.iter().filter(|event| { let check = event.business_profile_id == Some(profile_id.to_owned()) && event.initial_attempt_id.as_ref() == Some(&event.event_id) && (event.created_at >= created_after) && (event.created_at <= created_before) && (event.is_overall_delivery_successful == is_delivered); check }); let offset: usize = if let Some(offset) = offset { if offset < 0 { Err(errors::StorageError::MockDbError)?; } offset .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { 0 }; let limit: usize = if let Some(limit) = limit { if limit < 0 { Err(errors::StorageError::MockDbError)?; } limit .try_into() .map_err(|_| errors::StorageError::MockDbError)? } else { usize::MAX }; let events = events_iter .skip(offset) .take(limit) .cloned() .collect::<Vec<_>>(); let mut domain_events = Vec::with_capacity(events.len()); for event in events { let domain_event = event .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_events.push(domain_event); } Ok(domain_events) } async fn update_event_by_merchant_id_event_id( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, event_id: &str, event: domain::EventUpdate, merchant_key_store: &domain::MerchantKeyStore, ) -> CustomResult<domain::Event, errors::StorageError> { let mut locked_events = self.events.lock().await; let event_to_update = locked_events .iter_mut() .find(|event| { event.merchant_id == Some(merchant_id.to_owned()) && event.event_id == event_id }) .ok_or(errors::StorageError::MockDbError)?; match event { domain::EventUpdate::UpdateResponse { is_webhook_notified, response, } => { event_to_update.is_webhook_notified = is_webhook_notified; event_to_update.response = response.map(Into::into); } domain::EventUpdate::OverallDeliveryStatusUpdate { is_overall_delivery_successful, } => { event_to_update.is_overall_delivery_successful = Some(is_overall_delivery_successful) } } event_to_update .clone() .convert( state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn count_initial_events_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, profile_id: Option<common_utils::id_type::ProfileId>, created_after: time::PrimitiveDateTime, created_before: time::PrimitiveDateTime, is_delivered: Option<bool>, ) -> CustomResult<i64, errors::StorageError> { let locked_events = self.events.lock().await; let iter_events = locked_events.iter().filter(|event| { let check = event.initial_attempt_id.as_ref() == Some(&event.event_id) && (event.merchant_id == Some(merchant_id.to_owned())) && (event.business_profile_id == profile_id) && (event.created_at >= created_after) && (event.created_at <= created_before) && (event.is_overall_delivery_successful == is_delivered); check }); let events = iter_events.cloned().collect::<Vec<_>>(); i64::try_from(events.len()) .change_context(errors::StorageError::MockDbError) .attach_printable("Failed to convert usize to i64") } } #[cfg(test)] mod tests { use std::sync::Arc; use common_utils::{type_name, types::keymanager::Identifier}; use diesel_models::{enums, events::EventMetadata}; use time::macros::datetime; use crate::{ db::{ events::EventInterface, merchant_key_store::MerchantKeyStoreInterface, MasterKeyInterface, MockDb, }, routes::{ self, app::{settings::Settings, StorageImpl}, }, services, types::domain, }; #[allow(clippy::unwrap_used)] #[tokio::test] async fn test_mockdb_event_interface() { #[allow(clippy::expect_used)] let mockdb = MockDb::new(&redis_interface::RedisSettings::default()) .await .expect("Failed to create Mock store"); let event_id = "test_event_id"; let (tx, _) = tokio::sync::oneshot::channel(); let app_state = Box::pin(routes::AppState::with_storage( Settings::default(), StorageImpl::PostgresqlTest, tx, Box::new(services::MockApiClient), )) .await; let state = &Arc::new(app_state) .get_session_state( &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), None, || {}, ) .unwrap(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_1")) .unwrap(); let business_profile_id = common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("profile1")).unwrap(); let payment_id = "test_payment_id"; let key_manager_state = &state.into(); let master_key = mockdb.get_master_key(); mockdb .insert_merchant_key_store( key_manager_state, domain::MerchantKeyStore { merchant_id: merchant_id.clone(), key: domain::types::crypto_operation( key_manager_state, type_name!(domain::MerchantKeyStore), domain::types::CryptoOperation::Encrypt( services::generate_aes256_key().unwrap().to_vec().into(), ), Identifier::Merchant(merchant_id.to_owned()), master_key, ) .await .and_then(|val| val.try_into_operation()) .unwrap(), created_at: datetime!(2023-02-01 0:00), }, &master_key.to_vec().into(), ) .await .unwrap(); let merchant_key_store = mockdb .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &master_key.to_vec().into(), ) .await .unwrap(); let event1 = mockdb .insert_event( key_manager_state, domain::Event { event_id: event_id.into(), event_type: enums::EventType::PaymentSucceeded, event_class: enums::EventClass::Payments, is_webhook_notified: false, primary_object_id: payment_id.into(), primary_object_type: enums::EventObjectType::PaymentDetails, created_at: common_utils::date_time::now(), merchant_id: Some(merchant_id.to_owned()), business_profile_id: Some(business_profile_id.to_owned()), primary_object_created_at: Some(common_utils::date_time::now()), idempotent_event_id: Some(event_id.into()), initial_attempt_id: Some(event_id.into()), request: None, response: None, delivery_attempt: Some(enums::WebhookDeliveryAttempt::InitialAttempt), metadata: Some(EventMetadata::Payment { payment_id: common_utils::id_type::PaymentId::try_from( std::borrow::Cow::Borrowed(payment_id), ) .unwrap(), }), is_overall_delivery_successful: Some(false), }, &merchant_key_store, ) .await .unwrap(); assert_eq!(event1.event_id, event_id); let updated_event = mockdb .update_event_by_merchant_id_event_id( key_manager_state, &merchant_id, event_id, domain::EventUpdate::UpdateResponse { is_webhook_notified: true, response: None, }, &merchant_key_store, ) .await .unwrap(); assert!(updated_event.is_webhook_notified); assert_eq!(updated_event.primary_object_id, payment_id); assert_eq!(updated_event.event_id, event_id); } }
6,534
1,477
hyperswitch
crates/router/src/db/reverse_lookup.rs
.rs
use super::{MockDb, Store}; use crate::{ errors::{self, CustomResult}, types::storage::{ enums, reverse_lookup::{ReverseLookup, ReverseLookupNew}, }, }; #[async_trait::async_trait] pub trait ReverseLookupInterface { async fn insert_reverse_lookup( &self, _new: ReverseLookupNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError>; async fn get_lookup_by_lookup_id( &self, _id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError>; } #[cfg(not(feature = "kv_store"))] mod storage { use error_stack::report; use router_env::{instrument, tracing}; use super::{ReverseLookupInterface, Store}; use crate::{ connection, errors::{self, CustomResult}, types::storage::{ enums, reverse_lookup::{ReverseLookup, ReverseLookupNew}, }, }; #[async_trait::async_trait] impl ReverseLookupInterface for Store { #[instrument(skip_all)] async fn insert_reverse_lookup( &self, new: ReverseLookupNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn get_lookup_by_lookup_id( &self, id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; ReverseLookup::find_by_lookup_id(id, &conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } } } #[cfg(feature = "kv_store")] mod storage { use error_stack::{report, ResultExt}; use redis_interface::SetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::{ decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey, }; use super::{ReverseLookupInterface, Store}; use crate::{ connection, core::errors::utils::RedisErrorExt, errors::{self, CustomResult}, types::storage::{ enums, kv, reverse_lookup::{ReverseLookup, ReverseLookupNew}, }, utils::db_utils, }; #[async_trait::async_trait] impl ReverseLookupInterface for Store { #[instrument(skip_all)] async fn insert_reverse_lookup( &self, new: ReverseLookupNew, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let storage_scheme = Box::pin(decide_storage_scheme::<_, ReverseLookup>( self, storage_scheme, Op::Insert, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => { let conn = connection::pg_connection_write(self).await?; new.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } enums::MerchantStorageScheme::RedisKv => { let created_rev_lookup = ReverseLookup { lookup_id: new.lookup_id.clone(), sk_id: new.sk_id.clone(), pk_id: new.pk_id.clone(), source: new.source.clone(), updated_by: storage_scheme.to_string(), }; let redis_entry = kv::TypedSql { op: kv::DBOperation::Insert { insertable: Box::new(kv::Insertable::ReverseLookUp(new)), }, }; match Box::pin(kv_wrapper::<ReverseLookup, _, _>( self, KvOperation::SetNx(&created_rev_lookup, redis_entry), PartitionKey::CombinationKey { combination: &format!( "reverse_lookup_{}", &created_rev_lookup.lookup_id ), }, )) .await .map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))? .try_into_setnx() { Ok(SetnxReply::KeySet) => Ok(created_rev_lookup), Ok(SetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue { entity: "reverse_lookup", key: Some(created_rev_lookup.lookup_id.clone()), } .into()), Err(er) => Err(er).change_context(errors::StorageError::KVError), } } } } #[instrument(skip_all)] async fn get_lookup_by_lookup_id( &self, id: &str, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let database_call = || async { let conn = connection::pg_connection_read(self).await?; ReverseLookup::find_by_lookup_id(id, &conn) .await .map_err(|error| report!(errors::StorageError::from(error))) }; let storage_scheme = Box::pin(decide_storage_scheme::<_, ReverseLookup>( self, storage_scheme, Op::Find, )) .await; match storage_scheme { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let redis_fut = async { Box::pin(kv_wrapper( self, KvOperation::<ReverseLookup>::Get, PartitionKey::CombinationKey { combination: &format!("reverse_lookup_{id}"), }, )) .await? .try_into_get() }; Box::pin(db_utils::try_redis_get_else_try_database_get( redis_fut, database_call, )) .await } } } } } #[async_trait::async_trait] impl ReverseLookupInterface for MockDb { async fn insert_reverse_lookup( &self, new: ReverseLookupNew, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { let reverse_lookup_insert = ReverseLookup::from(new); self.reverse_lookups .lock() .await .push(reverse_lookup_insert.clone()); Ok(reverse_lookup_insert) } async fn get_lookup_by_lookup_id( &self, lookup_id: &str, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<ReverseLookup, errors::StorageError> { self.reverse_lookups .lock() .await .iter() .find(|reverse_lookup| reverse_lookup.lookup_id == lookup_id) .ok_or( errors::StorageError::ValueNotFound(format!( "No reverse lookup found for lookup_id = {}", lookup_id )) .into(), ) .cloned() } }
1,520
1,478
hyperswitch
crates/router/src/db/configs.rs
.rs
use diesel_models::configs::ConfigUpdateInternal; use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::redis::cache::{self, CacheKind, CONFIG_CACHE}; use super::{MockDb, Store}; use crate::{ connection, core::errors::{self, CustomResult}, db::StorageInterface, types::storage, }; #[async_trait::async_trait] pub trait ConfigInterface { async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, errors::StorageError>; async fn find_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError>; async fn find_config_by_key_unwrap_or( &self, key: &str, // If the config is not found it will be created with the default value. default_config: Option<String>, ) -> CustomResult<storage::Config, errors::StorageError>; async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError>; async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError>; async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError>; async fn delete_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError>; } #[async_trait::async_trait] impl ConfigInterface for Store { #[instrument(skip_all)] async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let inserted = config .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))?; cache::redact_from_redis_and_publish( self.get_cache_store().as_ref(), [CacheKind::Config((&inserted.key).into())], ) .await?; Ok(inserted) } #[instrument(skip_all)] async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Config::update_by_key(&conn, key, config_update) .await .map_err(|error| report!(errors::StorageError::from(error))) } //update in DB and remove in redis and cache #[instrument(skip_all)] async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { cache::publish_and_redact(self, CacheKind::Config(key.into()), || { self.update_config_in_database(key, config_update) }) .await } #[instrument(skip_all)] async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(errors::StorageError::from(error))) } //check in cache, then redis then finally DB, and on the way back populate redis and cache #[instrument(skip_all)] async fn find_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { let find_config_by_key_from_db = || async { let conn = connection::pg_connection_write(self).await?; storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(errors::StorageError::from(error))) }; cache::get_or_populate_in_memory(self, key, find_config_by_key_from_db, &CONFIG_CACHE).await } #[instrument(skip_all)] async fn find_config_by_key_unwrap_or( &self, key: &str, // If the config is not found it will be cached with the default value. default_config: Option<String>, ) -> CustomResult<storage::Config, errors::StorageError> { let find_else_unwrap_or = || async { let conn = connection::pg_connection_write(self).await?; match storage::Config::find_by_key(&conn, key) .await .map_err(|error| report!(errors::StorageError::from(error))) { Ok(a) => Ok(a), Err(err) => { if err.current_context().is_db_not_found() { default_config .map(|c| { storage::ConfigNew { key: key.to_string(), config: c, } .into() }) .ok_or(err) } else { Err(err) } } } }; cache::get_or_populate_in_memory(self, key, find_else_unwrap_or, &CONFIG_CACHE).await } #[instrument(skip_all)] async fn delete_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; let deleted = storage::Config::delete_by_key(&conn, key) .await .map_err(|error| report!(errors::StorageError::from(error)))?; cache::redact_from_redis_and_publish( self.get_cache_store().as_ref(), [CacheKind::Config((&deleted.key).into())], ) .await?; Ok(deleted) } } #[async_trait::async_trait] impl ConfigInterface for MockDb { #[instrument(skip_all)] async fn insert_config( &self, config: storage::ConfigNew, ) -> CustomResult<storage::Config, errors::StorageError> { let mut configs = self.configs.lock().await; let config_new = storage::Config { key: config.key, config: config.config, }; configs.push(config_new.clone()); Ok(config_new) } async fn update_config_in_database( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { self.update_config_by_key(key, config_update).await } async fn update_config_by_key( &self, key: &str, config_update: storage::ConfigUpdate, ) -> CustomResult<storage::Config, errors::StorageError> { let result = self .configs .lock() .await .iter_mut() .find(|c| c.key == key) .ok_or_else(|| { errors::StorageError::ValueNotFound("cannot find config to update".to_string()) .into() }) .map(|c| { let config_updated = ConfigUpdateInternal::from(config_update).create_config(c.clone()); *c = config_updated.clone(); config_updated }); result } async fn delete_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { let mut configs = self.configs.lock().await; let result = configs .iter() .position(|c| c.key == key) .map(|index| configs.remove(index)) .ok_or_else(|| { errors::StorageError::ValueNotFound("cannot find config to delete".to_string()) .into() }); result } async fn find_config_by_key( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { let configs = self.configs.lock().await; let config = configs.iter().find(|c| c.key == key).cloned(); config.ok_or_else(|| { errors::StorageError::ValueNotFound("cannot find config".to_string()).into() }) } async fn find_config_by_key_unwrap_or( &self, key: &str, _default_config: Option<String>, ) -> CustomResult<storage::Config, errors::StorageError> { self.find_config_by_key(key).await } async fn find_config_by_key_from_db( &self, key: &str, ) -> CustomResult<storage::Config, errors::StorageError> { self.find_config_by_key(key).await } }
1,957
1,479
hyperswitch
crates/router/src/db/business_profile.rs
.rs
use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState}; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::MockDb, types::{ domain::{ self, behaviour::{Conversion, ReverseConversion}, }, storage, }, }; #[async_trait::async_trait] pub trait ProfileInterface where domain::Profile: Conversion<DstType = storage::Profile, NewDstType = storage::ProfileNew>, { async fn insert_business_profile( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, business_profile: domain::Profile, ) -> CustomResult<domain::Profile, errors::StorageError>; async fn find_business_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, errors::StorageError>; async fn find_business_profile_by_merchant_id_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, errors::StorageError>; async fn find_business_profile_by_profile_name_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_name: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<domain::Profile, errors::StorageError>; async fn update_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: domain::Profile, profile_update: domain::ProfileUpdate, ) -> CustomResult<domain::Profile, errors::StorageError>; async fn delete_profile_by_profile_id_merchant_id( &self, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError>; async fn list_profile_by_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<domain::Profile>, errors::StorageError>; } #[async_trait::async_trait] impl ProfileInterface for Store { #[instrument(skip_all)] async fn insert_business_profile( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, business_profile: domain::Profile, ) -> CustomResult<domain::Profile, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; business_profile .construct_new() .await .change_context(errors::StorageError::EncryptionError)? .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_business_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; storage::Profile::find_by_profile_id(&conn, profile_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_business_profile_by_merchant_id_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; storage::Profile::find_by_merchant_id_profile_id(&conn, merchant_id, profile_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn find_business_profile_by_profile_name_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_name: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<domain::Profile, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; storage::Profile::find_by_profile_name_merchant_id(&conn, profile_name, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn update_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: domain::Profile, profile_update: domain::ProfileUpdate, ) -> CustomResult<domain::Profile, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; Conversion::convert(current_state) .await .change_context(errors::StorageError::EncryptionError)? .update_by_profile_id(&conn, storage::ProfileUpdateInternal::from(profile_update)) .await .map_err(|error| report!(errors::StorageError::from(error)))? .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } #[instrument(skip_all)] async fn delete_profile_by_profile_id_merchant_id( &self, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let conn = connection::pg_accounts_connection_write(self).await?; storage::Profile::delete_by_profile_id_merchant_id(&conn, profile_id, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_profile_by_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<domain::Profile>, errors::StorageError> { let conn = connection::pg_accounts_connection_read(self).await?; storage::Profile::list_profile_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) .async_and_then(|business_profiles| async { let mut domain_business_profiles = Vec::with_capacity(business_profiles.len()); for business_profile in business_profiles.into_iter() { domain_business_profiles.push( business_profile .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?, ); } Ok(domain_business_profiles) }) .await } } #[async_trait::async_trait] impl ProfileInterface for MockDb { async fn insert_business_profile( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, business_profile: domain::Profile, ) -> CustomResult<domain::Profile, errors::StorageError> { let stored_business_profile = Conversion::convert(business_profile) .await .change_context(errors::StorageError::EncryptionError)?; self.business_profiles .lock() .await .push(stored_business_profile.clone()); stored_business_profile .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) } async fn find_business_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, errors::StorageError> { self.business_profiles .lock() .await .iter() .find(|business_profile| business_profile.get_id() == profile_id) .cloned() .async_map(|business_profile| async { business_profile .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "No business profile found for profile_id = {profile_id:?}" )) .into(), ) } async fn find_business_profile_by_merchant_id_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, profile_id: &common_utils::id_type::ProfileId, ) -> CustomResult<domain::Profile, errors::StorageError> { self.business_profiles .lock() .await .iter() .find(|business_profile| { business_profile.merchant_id == *merchant_id && business_profile.get_id() == profile_id }) .cloned() .async_map(|business_profile| async { business_profile .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "No business profile found for merchant_id = {merchant_id:?} and profile_id = {profile_id:?}" )) .into(), ) } async fn update_profile_by_profile_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, current_state: domain::Profile, profile_update: domain::ProfileUpdate, ) -> CustomResult<domain::Profile, errors::StorageError> { let profile_id = current_state.get_id().to_owned(); self.business_profiles .lock() .await .iter_mut() .find(|business_profile| business_profile.get_id() == current_state.get_id()) .async_map(|business_profile| async { let profile_updated = storage::ProfileUpdateInternal::from(profile_update) .apply_changeset( Conversion::convert(current_state) .await .change_context(errors::StorageError::EncryptionError)?, ); *business_profile = profile_updated.clone(); profile_updated .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "No business profile found for profile_id = {profile_id:?}", )) .into(), ) } async fn delete_profile_by_profile_id_merchant_id( &self, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<bool, errors::StorageError> { let mut business_profiles = self.business_profiles.lock().await; let index = business_profiles .iter() .position(|business_profile| { business_profile.get_id() == profile_id && business_profile.merchant_id == *merchant_id }) .ok_or::<errors::StorageError>(errors::StorageError::ValueNotFound(format!( "No business profile found for profile_id = {profile_id:?} and merchant_id = {merchant_id:?}" )))?; business_profiles.remove(index); Ok(true) } async fn list_profile_by_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<domain::Profile>, errors::StorageError> { let business_profiles = self .business_profiles .lock() .await .iter() .filter(|business_profile| business_profile.merchant_id == *merchant_id) .cloned() .collect::<Vec<_>>(); let mut domain_business_profiles = Vec::with_capacity(business_profiles.len()); for business_profile in business_profiles { let domain_profile = business_profile .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError)?; domain_business_profiles.push(domain_profile); } Ok(domain_business_profiles) } async fn find_business_profile_by_profile_name_merchant_id( &self, key_manager_state: &KeyManagerState, merchant_key_store: &domain::MerchantKeyStore, profile_name: &str, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<domain::Profile, errors::StorageError> { self.business_profiles .lock() .await .iter() .find(|business_profile| { business_profile.profile_name == profile_name && business_profile.merchant_id == *merchant_id }) .cloned() .async_map(|business_profile| async { business_profile .convert( key_manager_state, merchant_key_store.key.get_inner(), merchant_key_store.merchant_id.clone().into(), ) .await .change_context(errors::StorageError::DecryptionError) }) .await .transpose()? .ok_or( errors::StorageError::ValueNotFound(format!( "No business profile found for profile_name = {profile_name} and merchant_id = {merchant_id:?}" )) .into(), ) } }
3,470
1,480
hyperswitch
crates/router/src/db/blocklist.rs
.rs
use error_stack::report; use router_env::{instrument, tracing}; use storage_impl::MockDb; use super::Store; use crate::{ connection, core::errors::{self, CustomResult}, db::kafka_store::KafkaStore, types::storage, }; #[async_trait::async_trait] pub trait BlocklistInterface { async fn insert_blocklist_entry( &self, pm_blocklist_new: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError>; async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError>; async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError>; async fn list_blocklist_entries_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>; async fn list_blocklist_entries_by_merchant_id_data_kind( &self, merchant_id: &common_utils::id_type::MerchantId, data_kind: common_enums::BlocklistDataKind, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>; } #[async_trait::async_trait] impl BlocklistInterface for Store { #[instrument(skip_all)] async fn insert_blocklist_entry( &self, pm_blocklist: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; pm_blocklist .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Blocklist::find_by_merchant_id_fingerprint_id(&conn, merchant_id, fingerprint_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_blocklist_entries_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Blocklist::list_by_merchant_id(&conn, merchant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn list_blocklist_entries_by_merchant_id_data_kind( &self, merchant_id: &common_utils::id_type::MerchantId, data_kind: common_enums::BlocklistDataKind, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Blocklist::list_by_merchant_id_data_kind( &conn, merchant_id, data_kind, limit, offset, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Blocklist::delete_by_merchant_id_fingerprint_id(&conn, merchant_id, fingerprint_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl BlocklistInterface for MockDb { #[instrument(skip_all)] async fn insert_blocklist_entry( &self, _pm_blocklist: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn list_blocklist_entries_by_merchant_id( &self, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn list_blocklist_entries_by_merchant_id_data_kind( &self, _merchant_id: &common_utils::id_type::MerchantId, _data_kind: common_enums::BlocklistDataKind, _limit: i64, _offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, _merchant_id: &common_utils::id_type::MerchantId, _fingerprint_id: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { Err(errors::StorageError::MockDbError)? } } #[async_trait::async_trait] impl BlocklistInterface for KafkaStore { #[instrument(skip_all)] async fn insert_blocklist_entry( &self, pm_blocklist: storage::BlocklistNew, ) -> CustomResult<storage::Blocklist, errors::StorageError> { self.diesel_store.insert_blocklist_entry(pm_blocklist).await } #[instrument(skip_all)] async fn find_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { self.diesel_store .find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint) .await } #[instrument(skip_all)] async fn delete_blocklist_entry_by_merchant_id_fingerprint_id( &self, merchant_id: &common_utils::id_type::MerchantId, fingerprint: &str, ) -> CustomResult<storage::Blocklist, errors::StorageError> { self.diesel_store .delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint) .await } #[instrument(skip_all)] async fn list_blocklist_entries_by_merchant_id_data_kind( &self, merchant_id: &common_utils::id_type::MerchantId, data_kind: common_enums::BlocklistDataKind, limit: i64, offset: i64, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { self.diesel_store .list_blocklist_entries_by_merchant_id_data_kind(merchant_id, data_kind, limit, offset) .await } #[instrument(skip_all)] async fn list_blocklist_entries_by_merchant_id( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> { self.diesel_store .list_blocklist_entries_by_merchant_id(merchant_id) .await } }
1,801
1,481
hyperswitch
crates/router/src/db/cards_info.rs
.rs
use error_stack::report; use router_env::{instrument, tracing}; use crate::{ connection, core::errors::{self, CustomResult}, db::MockDb, services::Store, types::storage::cards_info::{CardInfo, UpdateCardInfo}, }; #[async_trait::async_trait] pub trait CardsInfoInterface { async fn get_card_info( &self, _card_iin: &str, ) -> CustomResult<Option<CardInfo>, errors::StorageError>; async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, errors::StorageError>; async fn update_card_info( &self, card_iin: String, data: UpdateCardInfo, ) -> CustomResult<CardInfo, errors::StorageError>; } #[async_trait::async_trait] impl CardsInfoInterface for Store { #[instrument(skip_all)] async fn get_card_info( &self, card_iin: &str, ) -> CustomResult<Option<CardInfo>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; CardInfo::find_by_iin(&conn, card_iin) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn add_card_info(&self, data: CardInfo) -> CustomResult<CardInfo, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; data.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_card_info( &self, card_iin: String, data: UpdateCardInfo, ) -> CustomResult<CardInfo, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; CardInfo::update(&conn, card_iin, data) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl CardsInfoInterface for MockDb { #[instrument(skip_all)] async fn get_card_info( &self, card_iin: &str, ) -> CustomResult<Option<CardInfo>, errors::StorageError> { Ok(self .cards_info .lock() .await .iter() .find(|ci| ci.card_iin == card_iin) .cloned()) } async fn add_card_info(&self, _data: CardInfo) -> CustomResult<CardInfo, errors::StorageError> { Err(errors::StorageError::MockDbError)? } async fn update_card_info( &self, _card_iin: String, _data: UpdateCardInfo, ) -> CustomResult<CardInfo, errors::StorageError> { Err(errors::StorageError::MockDbError)? } }
636
1,482
hyperswitch
crates/router/src/db/role.rs
.rs
use common_utils::id_type; use diesel_models::{ enums::{EntityType, RoleScope}, role as storage, }; use error_stack::report; use router_env::{instrument, tracing}; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait RoleInterface { async fn insert_role( &self, role: storage::RoleNew, ) -> CustomResult<storage::Role, errors::StorageError>; async fn find_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError>; async fn find_role_by_role_id_in_lineage( &self, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError>; async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError>; async fn update_role_by_role_id( &self, role_id: &str, role_update: storage::RoleUpdate, ) -> CustomResult<storage::Role, errors::StorageError>; async fn delete_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError>; //TODO: Remove once generic_list_roles_by_entity_type is stable async fn list_roles_for_org_by_parameters( &self, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError>; async fn generic_list_roles_by_entity_type( &self, payload: storage::ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError>; } #[async_trait::async_trait] impl RoleInterface for Store { #[instrument(skip_all)] async fn insert_role( &self, role: storage::RoleNew, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; role.insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::find_by_role_id(&conn, role_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_role_by_role_id_in_lineage( &self, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::find_by_role_id_in_lineage( &conn, role_id, merchant_id, org_id, profile_id, tenant_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::find_by_role_id_org_id_tenant_id(&conn, role_id, org_id, tenant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn update_role_by_role_id( &self, role_id: &str, role_update: storage::RoleUpdate, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Role::update_by_role_id(&conn, role_id, role_update) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn delete_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Role::delete_by_role_id(&conn, role_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } //TODO: Remove once generic_list_roles_by_entity_type is stable #[instrument(skip_all)] async fn list_roles_for_org_by_parameters( &self, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::generic_roles_list_for_org( &conn, tenant_id.to_owned(), org_id.to_owned(), merchant_id.cloned(), entity_type, limit, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] async fn generic_list_roles_by_entity_type( &self, payload: storage::ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Role::generic_list_roles_by_entity_type( &conn, payload, is_lineage_data_required, tenant_id, org_id, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl RoleInterface for MockDb { async fn insert_role( &self, role: storage::RoleNew, ) -> CustomResult<storage::Role, errors::StorageError> { let mut roles = self.roles.lock().await; if roles .iter() .any(|role_inner| role_inner.role_id == role.role_id) { Err(errors::StorageError::DuplicateValue { entity: "role_id", key: None, })? } let role = storage::Role { role_name: role.role_name, role_id: role.role_id, merchant_id: role.merchant_id, org_id: role.org_id, groups: role.groups, scope: role.scope, entity_type: role.entity_type, created_by: role.created_by, created_at: role.created_at, last_modified_at: role.last_modified_at, last_modified_by: role.last_modified_by, profile_id: role.profile_id, tenant_id: role.tenant_id, }; roles.push(role.clone()); Ok(role) } async fn find_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { let roles = self.roles.lock().await; roles .iter() .find(|role| role.role_id == role_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No role available role_id = {role_id}" )) .into(), ) } async fn find_role_by_role_id_in_lineage( &self, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, profile_id: &id_type::ProfileId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let roles = self.roles.lock().await; roles .iter() .find(|role| { role.role_id == role_id && (role.tenant_id == *tenant_id) && role.org_id == *org_id && ((role.scope == RoleScope::Organization) || (role.merchant_id == *merchant_id && role.scope == RoleScope::Merchant) || (role .profile_id .as_ref() .is_some_and(|profile_id_from_role| { profile_id_from_role == profile_id && role.scope == RoleScope::Profile }))) }) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No role available in merchant scope for role_id = {role_id}, \ merchant_id = {merchant_id:?} and org_id = {org_id:?}" )) .into(), ) } async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let roles = self.roles.lock().await; roles .iter() .find(|role| { role.role_id == role_id && role.org_id == *org_id && role.tenant_id == *tenant_id }) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "No role available in org scope for role_id = {role_id} and org_id = {org_id:?}" )) .into(), ) } async fn update_role_by_role_id( &self, role_id: &str, role_update: storage::RoleUpdate, ) -> CustomResult<storage::Role, errors::StorageError> { let mut roles = self.roles.lock().await; roles .iter_mut() .find(|role| role.role_id == role_id) .map(|role| { *role = match role_update { storage::RoleUpdate::UpdateDetails { groups, role_name, last_modified_at, last_modified_by, } => storage::Role { groups: groups.unwrap_or(role.groups.to_owned()), role_name: role_name.unwrap_or(role.role_name.to_owned()), last_modified_by, last_modified_at, ..role.to_owned() }, }; role.to_owned() }) .ok_or( errors::StorageError::ValueNotFound(format!( "No role available for role_id = {role_id}" )) .into(), ) } async fn delete_role_by_role_id( &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { let mut roles = self.roles.lock().await; let role_index = roles .iter() .position(|role| role.role_id == role_id) .ok_or(errors::StorageError::ValueNotFound(format!( "No role available for role_id = {role_id}" )))?; Ok(roles.remove(role_index)) } //TODO: Remove once generic_list_roles_by_entity_type is stable #[instrument(skip_all)] async fn list_roles_for_org_by_parameters( &self, tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let roles = self.roles.lock().await; let limit_usize = limit.unwrap_or(u32::MAX).try_into().unwrap_or(usize::MAX); let roles_list: Vec<_> = roles .iter() .filter(|role| { let matches_merchant = match merchant_id { Some(merchant_id) => role.merchant_id == *merchant_id, None => true, }; matches_merchant && role.org_id == *org_id && role.tenant_id == *tenant_id && Some(role.entity_type) == entity_type }) .take(limit_usize) .cloned() .collect(); Ok(roles_list) } #[instrument(skip_all)] async fn generic_list_roles_by_entity_type( &self, payload: storage::ListRolesByEntityPayload, is_lineage_data_required: bool, tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let roles = self.roles.lock().await; let roles_list: Vec<_> = roles .iter() .filter(|role| match &payload { storage::ListRolesByEntityPayload::Organization => { let entity_in_vec = if is_lineage_data_required { vec![ EntityType::Organization, EntityType::Merchant, EntityType::Profile, ] } else { vec![EntityType::Organization] }; role.tenant_id == tenant_id && role.org_id == org_id && entity_in_vec.contains(&role.entity_type) } storage::ListRolesByEntityPayload::Merchant(merchant_id) => { let entity_in_vec = if is_lineage_data_required { vec![EntityType::Merchant, EntityType::Profile] } else { vec![EntityType::Merchant] }; role.tenant_id == tenant_id && role.org_id == org_id && (role.scope == RoleScope::Organization || role.merchant_id == *merchant_id) && entity_in_vec.contains(&role.entity_type) } storage::ListRolesByEntityPayload::Profile(merchant_id, profile_id) => { let entity_in_vec = [EntityType::Profile]; let matches_merchant = role.merchant_id == *merchant_id && role.scope == RoleScope::Merchant; let matches_profile = role.profile_id .as_ref() .is_some_and(|profile_id_from_role| { profile_id_from_role == profile_id && role.scope == RoleScope::Profile }); role.tenant_id == tenant_id && role.org_id == org_id && (role.scope == RoleScope::Organization || matches_merchant || matches_profile) && entity_in_vec.contains(&role.entity_type) } }) .cloned() .collect(); Ok(roles_list) } }
3,408
1,483
hyperswitch
crates/router/src/db/user/sample_data.rs
.rs
use common_utils::types::keymanager::KeyManagerState; #[cfg(feature = "v1")] use diesel_models::user::sample_data::PaymentAttemptBatchNew; use diesel_models::{ dispute::{Dispute, DisputeNew}, errors::DatabaseError, query::user::sample_data as sample_data_queries, refund::{Refund, RefundNew}, }; use error_stack::{Report, ResultExt}; use futures::{future::try_join_all, FutureExt}; use hyperswitch_domain_models::{ behaviour::Conversion, merchant_key_store::MerchantKeyStore, payments::{payment_attempt::PaymentAttempt, PaymentIntent}, }; use storage_impl::{errors::StorageError, DataModelExt}; use crate::{connection::pg_connection_write, core::errors::CustomResult, services::Store}; #[async_trait::async_trait] pub trait BatchSampleDataInterface { #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, state: &KeyManagerState, batch: Vec<PaymentIntent>, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError>; #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, batch: Vec<PaymentAttemptBatchNew>, ) -> CustomResult<Vec<PaymentAttempt>, StorageError>; #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, batch: Vec<RefundNew>, ) -> CustomResult<Vec<Refund>, StorageError>; #[cfg(feature = "v1")] async fn insert_disputes_batch_for_sample_data( &self, batch: Vec<DisputeNew>, ) -> CustomResult<Vec<Dispute>, StorageError>; #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError>; #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<PaymentAttempt>, StorageError>; #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Refund>, StorageError>; #[cfg(feature = "v1")] async fn delete_disputes_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Dispute>, StorageError>; } #[async_trait::async_trait] impl BatchSampleDataInterface for Store { #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, state: &KeyManagerState, batch: Vec<PaymentIntent>, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; let new_intents = try_join_all(batch.into_iter().map(|payment_intent| async { payment_intent .construct_new() .await .change_context(StorageError::EncryptionError) })) .await?; sample_data_queries::insert_payment_intents(&conn, new_intents) .await .map_err(diesel_error_to_data_error) .map(|v| { try_join_all(v.into_iter().map(|payment_intent| { PaymentIntent::convert_back( state, payment_intent, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) })? .await } #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, batch: Vec<PaymentAttemptBatchNew>, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::insert_payment_attempts(&conn, batch) .await .map_err(diesel_error_to_data_error) .map(|res| { res.into_iter() .map(PaymentAttempt::from_storage_model) .collect() }) } #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, batch: Vec<RefundNew>, ) -> CustomResult<Vec<Refund>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::insert_refunds(&conn, batch) .await .map_err(diesel_error_to_data_error) } #[cfg(feature = "v1")] async fn insert_disputes_batch_for_sample_data( &self, batch: Vec<DisputeNew>, ) -> CustomResult<Vec<Dispute>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::insert_disputes(&conn, batch) .await .map_err(diesel_error_to_data_error) } #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::delete_payment_intents(&conn, merchant_id) .await .map_err(diesel_error_to_data_error) .map(|v| { try_join_all(v.into_iter().map(|payment_intent| { PaymentIntent::convert_back( state, payment_intent, key_store.key.get_inner(), key_store.merchant_id.clone().into(), ) })) .map(|join_result| join_result.change_context(StorageError::DecryptionError)) })? .await } #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::delete_payment_attempts(&conn, merchant_id) .await .map_err(diesel_error_to_data_error) .map(|res| { res.into_iter() .map(PaymentAttempt::from_storage_model) .collect() }) } #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Refund>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::delete_refunds(&conn, merchant_id) .await .map_err(diesel_error_to_data_error) } #[cfg(feature = "v1")] async fn delete_disputes_for_sample_data( &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Dispute>, StorageError> { let conn = pg_connection_write(self) .await .change_context(StorageError::DatabaseConnectionError)?; sample_data_queries::delete_disputes(&conn, merchant_id) .await .map_err(diesel_error_to_data_error) } } #[async_trait::async_trait] impl BatchSampleDataInterface for storage_impl::MockDb { #[cfg(feature = "v1")] async fn insert_payment_intents_batch_for_sample_data( &self, _state: &KeyManagerState, _batch: Vec<PaymentIntent>, _key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn insert_payment_attempts_batch_for_sample_data( &self, _batch: Vec<PaymentAttemptBatchNew>, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn insert_refunds_batch_for_sample_data( &self, _batch: Vec<RefundNew>, ) -> CustomResult<Vec<Refund>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn insert_disputes_batch_for_sample_data( &self, _batch: Vec<DisputeNew>, ) -> CustomResult<Vec<Dispute>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, _state: &KeyManagerState, _merchant_id: &common_utils::id_type::MerchantId, _key_store: &MerchantKeyStore, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn delete_payment_attempts_for_sample_data( &self, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<PaymentAttempt>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn delete_refunds_for_sample_data( &self, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Refund>, StorageError> { Err(StorageError::MockDbError)? } #[cfg(feature = "v1")] async fn delete_disputes_for_sample_data( &self, _merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Dispute>, StorageError> { Err(StorageError::MockDbError)? } } // TODO: This error conversion is re-used from storage_impl and is not DRY when it should be // Ideally the impl's here should be defined in that crate avoiding this re-definition fn diesel_error_to_data_error(diesel_error: Report<DatabaseError>) -> Report<StorageError> { let new_err = match diesel_error.current_context() { DatabaseError::DatabaseConnectionError => StorageError::DatabaseConnectionError, DatabaseError::NotFound => StorageError::ValueNotFound("Value not found".to_string()), DatabaseError::UniqueViolation => StorageError::DuplicateValue { entity: "entity ", key: None, }, err => StorageError::DatabaseError(error_stack::report!(*err)), }; diesel_error.change_context(new_err) }
2,488
1,484
hyperswitch
crates/router/src/db/user/theme.rs
.rs
use common_utils::types::theme::ThemeLineage; use diesel_models::user::theme as storage; use error_stack::report; use super::MockDb; use crate::{ connection, core::errors::{self, CustomResult}, services::Store, }; #[async_trait::async_trait] pub trait ThemeInterface { async fn insert_theme( &self, theme: storage::ThemeNew, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn find_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn find_most_specific_theme_in_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn find_theme_by_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError>; async fn delete_theme_by_lineage_and_theme_id( &self, theme_id: String, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError>; } #[async_trait::async_trait] impl ThemeInterface for Store { async fn insert_theme( &self, theme: storage::ThemeNew, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; theme .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Theme::find_by_theme_id(&conn, theme_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_most_specific_theme_in_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Theme::find_most_specific_theme_in_lineage(&conn, lineage) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_theme_by_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Theme::find_by_lineage(&conn, lineage) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn delete_theme_by_lineage_and_theme_id( &self, theme_id: String, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::Theme::delete_by_theme_id_and_lineage(&conn, theme_id, lineage) .await .map_err(|error| report!(errors::StorageError::from(error))) } } fn check_theme_with_lineage(theme: &storage::Theme, lineage: &ThemeLineage) -> bool { match lineage { ThemeLineage::Tenant { tenant_id } => { &theme.tenant_id == tenant_id && theme.org_id.is_none() && theme.merchant_id.is_none() && theme.profile_id.is_none() } ThemeLineage::Organization { tenant_id, org_id } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme.merchant_id.is_none() && theme.profile_id.is_none() } ThemeLineage::Merchant { tenant_id, org_id, merchant_id, } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme .merchant_id .as_ref() .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id) && theme.profile_id.is_none() } ThemeLineage::Profile { tenant_id, org_id, merchant_id, profile_id, } => { &theme.tenant_id == tenant_id && theme .org_id .as_ref() .is_some_and(|org_id_inner| org_id_inner == org_id) && theme .merchant_id .as_ref() .is_some_and(|merchant_id_inner| merchant_id_inner == merchant_id) && theme .profile_id .as_ref() .is_some_and(|profile_id_inner| profile_id_inner == profile_id) } } } #[async_trait::async_trait] impl ThemeInterface for MockDb { async fn insert_theme( &self, new_theme: storage::ThemeNew, ) -> CustomResult<storage::Theme, errors::StorageError> { let mut themes = self.themes.lock().await; for theme in themes.iter() { if new_theme.theme_id == theme.theme_id { return Err(errors::StorageError::DuplicateValue { entity: "theme_id", key: None, } .into()); } if new_theme.tenant_id == theme.tenant_id && new_theme.org_id == theme.org_id && new_theme.merchant_id == theme.merchant_id && new_theme.profile_id == theme.profile_id { return Err(errors::StorageError::DuplicateValue { entity: "lineage", key: None, } .into()); } } let theme = storage::Theme { theme_id: new_theme.theme_id, tenant_id: new_theme.tenant_id, org_id: new_theme.org_id, merchant_id: new_theme.merchant_id, profile_id: new_theme.profile_id, created_at: new_theme.created_at, last_modified_at: new_theme.last_modified_at, entity_type: new_theme.entity_type, theme_name: new_theme.theme_name, email_primary_color: new_theme.email_primary_color, email_foreground_color: new_theme.email_foreground_color, email_background_color: new_theme.email_background_color, email_entity_name: new_theme.email_entity_name, email_entity_logo_url: new_theme.email_entity_logo_url, }; themes.push(theme.clone()); Ok(theme) } async fn find_theme_by_theme_id( &self, theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError> { let themes = self.themes.lock().await; themes .iter() .find(|theme| theme.theme_id == theme_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "Theme with id {} not found", theme_id )) .into(), ) } async fn find_most_specific_theme_in_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let themes = self.themes.lock().await; let lineages = lineage.get_same_and_higher_lineages(); themes .iter() .filter(|theme| { lineages .iter() .any(|lineage| check_theme_with_lineage(theme, lineage)) }) .min_by_key(|theme| theme.entity_type) .ok_or( errors::StorageError::ValueNotFound("No theme found in lineage".to_string()).into(), ) .cloned() } async fn find_theme_by_lineage( &self, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let themes = self.themes.lock().await; themes .iter() .find(|theme| check_theme_with_lineage(theme, &lineage)) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( "Theme with lineage {:?} not found", lineage )) .into(), ) } async fn delete_theme_by_lineage_and_theme_id( &self, theme_id: String, lineage: ThemeLineage, ) -> CustomResult<storage::Theme, errors::StorageError> { let mut themes = self.themes.lock().await; let index = themes .iter() .position(|theme| { theme.theme_id == theme_id && check_theme_with_lineage(theme, &lineage) }) .ok_or(errors::StorageError::ValueNotFound(format!( "Theme with id {} and lineage {:?} not found", theme_id, lineage )))?; let theme = themes.remove(index); Ok(theme) } }
1,979
1,485
hyperswitch
crates/router/src/configs/settings.rs
.rs
use std::{ collections::{HashMap, HashSet}, path::PathBuf, sync::Arc, }; #[cfg(feature = "olap")] use analytics::{opensearch::OpenSearchConfig, ReportConfig}; use api_models::{enums, payment_methods::RequiredFieldInfo}; use common_utils::{ext_traits::ConfigExt, id_type, types::theme::EmailThemeConfig}; use config::{Environment, File}; use error_stack::ResultExt; #[cfg(feature = "email")] use external_services::email::EmailSettings; use external_services::{ file_storage::FileStorageConfig, grpc_client::GrpcClientSettings, managers::{ encryption_management::EncryptionManagementConfig, secrets_management::SecretsManagementConfig, }, }; pub use hyperswitch_interfaces::configs::Connectors; use hyperswitch_interfaces::secrets_interface::secret_state::{ RawSecret, SecretState, SecretStateContainer, SecuredSecret, }; use masking::Secret; use redis_interface::RedisSettings; pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use rust_decimal::Decimal; use scheduler::SchedulerSettings; use serde::Deserialize; use storage_impl::config::QueueStrategy; #[cfg(feature = "olap")] use crate::analytics::{AnalyticsConfig, AnalyticsProvider}; use crate::{ configs, core::errors::{ApplicationError, ApplicationResult}, env::{self, Env}, events::EventsConfig, routes::app, AppState, }; pub const REQUIRED_FIELDS_CONFIG_FILE: &str = "payment_required_fields_v2.toml"; #[derive(clap::Parser, Default)] #[cfg_attr(feature = "vergen", command(version = router_env::version!()))] pub struct CmdLineConf { /// Config file. /// Application will look for "config/config.toml" if this option isn't specified. #[arg(short = 'f', long, value_name = "FILE")] pub config_path: Option<PathBuf>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct Settings<S: SecretState> { pub server: Server, pub proxy: Proxy, pub env: Env, pub master_database: SecretStateContainer<Database, S>, #[cfg(feature = "olap")] pub replica_database: SecretStateContainer<Database, S>, pub redis: RedisSettings, pub log: Log, pub secrets: SecretStateContainer<Secrets, S>, pub fallback_merchant_ids_api_key_auth: Option<FallbackMerchantIds>, pub locker: Locker, pub key_manager: SecretStateContainer<KeyManagerConfig, S>, pub connectors: Connectors, pub forex_api: SecretStateContainer<ForexApi, S>, pub refund: Refund, pub eph_key: EphemeralConfig, pub scheduler: Option<SchedulerSettings>, #[cfg(feature = "kv_store")] pub drainer: DrainerSettings, pub jwekey: SecretStateContainer<Jwekey, S>, pub webhooks: WebhooksSettings, pub pm_filters: ConnectorFilters, pub bank_config: BankRedirectConfig, pub api_keys: SecretStateContainer<ApiKeys, S>, pub file_storage: FileStorageConfig, pub encryption_management: EncryptionManagementConfig, pub secrets_management: SecretsManagementConfig, pub tokenization: TokenizationConfig, pub connector_customer: ConnectorCustomer, #[cfg(feature = "dummy_connector")] pub dummy_connector: DummyConnector, #[cfg(feature = "email")] pub email: EmailSettings, pub user: UserSettings, pub cors: CorsSettings, pub mandates: Mandates, pub network_transaction_id_supported_connectors: NetworkTransactionIdSupportedConnectors, pub required_fields: RequiredFields, pub delayed_session_response: DelayedSessionConfig, pub webhook_source_verification_call: WebhookSourceVerificationCall, pub billing_connectors_payment_sync: BillingConnectorPaymentsSyncCall, pub payment_method_auth: SecretStateContainer<PaymentMethodAuth, S>, pub connector_request_reference_id_config: ConnectorRequestReferenceIdConfig, #[cfg(feature = "payouts")] pub payouts: Payouts, pub payout_method_filters: ConnectorFilters, pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>, pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>, pub google_pay_decrypt_keys: Option<GooglePayDecryptConfig>, pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors, pub applepay_merchant_configs: SecretStateContainer<ApplepayMerchantConfigs, S>, pub lock_settings: LockSettings, pub temp_locker_enable_config: TempLockerEnableConfig, pub generic_link: GenericLink, pub payment_link: PaymentLink, #[cfg(feature = "olap")] pub analytics: SecretStateContainer<AnalyticsConfig, S>, #[cfg(feature = "kv_store")] pub kv_config: KvConfig, #[cfg(feature = "frm")] pub frm: Frm, #[cfg(feature = "olap")] pub report_download_config: ReportConfig, #[cfg(feature = "olap")] pub opensearch: OpenSearchConfig, pub events: EventsConfig, #[cfg(feature = "olap")] pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>, pub unmasked_headers: UnmaskedHeaders, pub multitenancy: Multitenancy, pub saved_payment_methods: EligiblePaymentMethods, pub user_auth_methods: SecretStateContainer<UserAuthMethodSettings, S>, pub decision: Option<DecisionConfig>, pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList, pub grpc_client: GrpcClientSettings, #[cfg(feature = "v2")] pub cell_information: CellInformation, pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks, pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>, pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors, pub theme: ThemeSettings, pub platform: Platform, } #[derive(Debug, Deserialize, Clone, Default)] pub struct Platform { pub enabled: bool, } #[derive(Debug, Clone, Default, Deserialize)] pub struct Multitenancy { pub tenants: TenantConfig, pub enabled: bool, pub global_tenant: GlobalTenant, } impl Multitenancy { pub fn get_tenants(&self) -> &HashMap<id_type::TenantId, Tenant> { &self.tenants.0 } pub fn get_tenant_ids(&self) -> Vec<id_type::TenantId> { self.tenants .0 .values() .map(|tenant| tenant.tenant_id.clone()) .collect() } pub fn get_tenant(&self, tenant_id: &id_type::TenantId) -> Option<&Tenant> { self.tenants.0.get(tenant_id) } } #[derive(Debug, Deserialize, Clone, Default)] pub struct DecisionConfig { pub base_url: String, } #[derive(Debug, Clone, Default)] pub struct TenantConfig(pub HashMap<id_type::TenantId, Tenant>); impl TenantConfig { /// # Panics /// /// Panics if Failed to create event handler pub async fn get_store_interface_map( &self, storage_impl: &app::StorageImpl, conf: &configs::Settings, cache_store: Arc<storage_impl::redis::RedisStore>, testable: bool, ) -> HashMap<id_type::TenantId, Box<dyn app::StorageInterface>> { #[allow(clippy::expect_used)] let event_handler = conf .events .get_event_handler() .await .expect("Failed to create event handler"); futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async { let store = AppState::get_store_interface( storage_impl, &event_handler, conf, tenant, cache_store.clone(), testable, ) .await .get_storage_interface(); (tenant_name.clone(), store) })) .await .into_iter() .collect() } /// # Panics /// /// Panics if Failed to create event handler pub async fn get_accounts_store_interface_map( &self, storage_impl: &app::StorageImpl, conf: &configs::Settings, cache_store: Arc<storage_impl::redis::RedisStore>, testable: bool, ) -> HashMap<id_type::TenantId, Box<dyn app::AccountsStorageInterface>> { #[allow(clippy::expect_used)] let event_handler = conf .events .get_event_handler() .await .expect("Failed to create event handler"); futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async { let store = AppState::get_store_interface( storage_impl, &event_handler, conf, tenant, cache_store.clone(), testable, ) .await .get_accounts_storage_interface(); (tenant_name.clone(), store) })) .await .into_iter() .collect() } #[cfg(feature = "olap")] pub async fn get_pools_map( &self, analytics_config: &AnalyticsConfig, ) -> HashMap<id_type::TenantId, AnalyticsProvider> { futures::future::join_all(self.0.iter().map(|(tenant_name, tenant)| async { ( tenant_name.clone(), AnalyticsProvider::from_conf(analytics_config, tenant).await, ) })) .await .into_iter() .collect() } } #[derive(Debug, Clone)] pub struct Tenant { pub tenant_id: id_type::TenantId, pub base_url: String, pub schema: String, pub accounts_schema: String, pub redis_key_prefix: String, pub clickhouse_database: String, pub user: TenantUserConfig, } #[derive(Debug, Deserialize, Clone)] pub struct TenantUserConfig { pub control_center_url: String, } impl storage_impl::config::TenantConfig for Tenant { fn get_tenant_id(&self) -> &id_type::TenantId { &self.tenant_id } fn get_accounts_schema(&self) -> &str { self.accounts_schema.as_str() } fn get_schema(&self) -> &str { self.schema.as_str() } fn get_redis_key_prefix(&self) -> &str { self.redis_key_prefix.as_str() } fn get_clickhouse_database(&self) -> &str { self.clickhouse_database.as_str() } } // Todo: Global tenant should not be part of tenant config(https://github.com/juspay/hyperswitch/issues/7237) #[derive(Debug, Deserialize, Clone)] pub struct GlobalTenant { #[serde(default = "id_type::TenantId::get_default_global_tenant_id")] pub tenant_id: id_type::TenantId, pub schema: String, pub redis_key_prefix: String, pub clickhouse_database: String, } // Todo: Global tenant should not be part of tenant config impl storage_impl::config::TenantConfig for GlobalTenant { fn get_tenant_id(&self) -> &id_type::TenantId { &self.tenant_id } fn get_accounts_schema(&self) -> &str { self.schema.as_str() } fn get_schema(&self) -> &str { self.schema.as_str() } fn get_redis_key_prefix(&self) -> &str { self.redis_key_prefix.as_str() } fn get_clickhouse_database(&self) -> &str { self.clickhouse_database.as_str() } } #[derive(Debug, Deserialize, Clone, Default)] pub struct UnmaskedHeaders { #[serde(deserialize_with = "deserialize_hashset")] pub keys: HashSet<String>, } #[cfg(feature = "frm")] #[derive(Debug, Deserialize, Clone, Default)] pub struct Frm { pub enabled: bool, } #[derive(Debug, Deserialize, Clone)] pub struct KvConfig { pub ttl: u32, pub soft_kill: Option<bool>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct KeyManagerConfig { pub enabled: bool, pub url: String, #[cfg(feature = "keymanager_mtls")] pub cert: Secret<String>, #[cfg(feature = "keymanager_mtls")] pub ca: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct GenericLink { pub payment_method_collect: GenericLinkEnvConfig, pub payout_link: GenericLinkEnvConfig, } #[derive(Debug, Deserialize, Clone)] pub struct GenericLinkEnvConfig { pub sdk_url: url::Url, pub expiry: u32, pub ui_config: GenericLinkEnvUiConfig, #[serde(deserialize_with = "deserialize_hashmap")] pub enabled_payment_methods: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, } impl Default for GenericLinkEnvConfig { fn default() -> Self { Self { #[allow(clippy::expect_used)] sdk_url: url::Url::parse("http://localhost:9050/HyperLoader.js") .expect("Failed to parse default SDK URL"), expiry: 900, ui_config: GenericLinkEnvUiConfig::default(), enabled_payment_methods: HashMap::default(), } } } #[derive(Debug, Deserialize, Clone)] pub struct GenericLinkEnvUiConfig { pub logo: url::Url, pub merchant_name: Secret<String>, pub theme: String, } #[allow(clippy::panic)] impl Default for GenericLinkEnvUiConfig { fn default() -> Self { Self { #[allow(clippy::expect_used)] logo: url::Url::parse("https://hyperswitch.io/favicon.ico") .expect("Failed to parse default logo URL"), merchant_name: Secret::new("HyperSwitch".to_string()), theme: "#4285F4".to_string(), } } } #[derive(Debug, Deserialize, Clone, Default)] pub struct PaymentLink { pub sdk_url: String, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct ForexApi { pub api_key: Secret<String>, pub fallback_api_key: Secret<String>, pub data_expiration_delay_in_seconds: u32, pub redis_lock_timeout_in_seconds: u32, pub redis_ttl_in_seconds: u32, } #[derive(Debug, Deserialize, Clone, Default)] pub struct PaymentMethodAuth { pub redis_expiry: i64, pub pm_auth_key: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct EligiblePaymentMethods { #[serde(deserialize_with = "deserialize_hashset")] pub sdk_eligible_payment_methods: HashSet<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct DefaultExchangeRates { pub base_currency: String, pub conversion: HashMap<String, Conversion>, pub timestamp: i64, } #[derive(Debug, Deserialize, Clone, Default)] pub struct Conversion { #[serde(with = "rust_decimal::serde::str")] pub to_factor: Decimal, #[serde(with = "rust_decimal::serde::str")] pub from_factor: Decimal, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct ApplepayMerchantConfigs { pub merchant_cert: Secret<String>, pub merchant_cert_key: Secret<String>, pub common_merchant_identifier: Secret<String>, pub applepay_endpoint: String, } #[derive(Debug, Deserialize, Clone, Default)] pub struct MultipleApiVersionSupportedConnectors { #[serde(deserialize_with = "deserialize_hashset")] pub supported_connectors: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct TokenizationConfig(pub HashMap<String, PaymentMethodTokenFilter>); #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct TempLockerEnableConfig(pub HashMap<String, TempLockerEnablePaymentMethodFilter>); #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorCustomer { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<enums::Connector>, #[cfg(feature = "payouts")] #[serde(deserialize_with = "deserialize_hashset")] pub payout_connector_list: HashSet<enums::PayoutConnectors>, } #[cfg(feature = "dummy_connector")] #[derive(Debug, Deserialize, Clone, Default)] pub struct DummyConnector { pub enabled: bool, pub payment_ttl: i64, pub payment_duration: u64, pub payment_tolerance: u64, pub payment_retrieve_duration: u64, pub payment_retrieve_tolerance: u64, pub payment_complete_duration: i64, pub payment_complete_tolerance: i64, pub refund_ttl: i64, pub refund_duration: u64, pub refund_tolerance: u64, pub refund_retrieve_duration: u64, pub refund_retrieve_tolerance: u64, pub authorize_ttl: i64, pub assets_base_url: String, pub default_return_url: String, pub slack_invite_url: String, pub discord_invite_url: String, } #[derive(Debug, Deserialize, Clone)] pub struct CorsSettings { #[serde(default, deserialize_with = "deserialize_hashset")] pub origins: HashSet<String>, #[serde(default)] pub wildcard_origin: bool, pub max_age: usize, #[serde(deserialize_with = "deserialize_hashset")] pub allowed_methods: HashSet<String>, } #[derive(Debug, Deserialize, Clone)] pub struct Mandates { pub supported_payment_methods: SupportedPaymentMethodsForMandate, pub update_mandate_supported: SupportedPaymentMethodsForMandate, } #[derive(Debug, Deserialize, Clone, Default)] pub struct NetworkTransactionIdSupportedConnectors { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct NetworkTokenizationSupportedCardNetworks { #[serde(deserialize_with = "deserialize_hashset")] pub card_networks: HashSet<enums::CardNetwork>, } #[derive(Debug, Deserialize, Clone)] pub struct NetworkTokenizationService { pub generate_token_url: url::Url, pub fetch_token_url: url::Url, pub token_service_api_key: Secret<String>, pub public_key: Secret<String>, pub private_key: Secret<String>, pub key_id: String, pub delete_token_url: url::Url, pub check_token_status_url: url::Url, } #[derive(Debug, Deserialize, Clone)] pub struct SupportedPaymentMethodsForMandate( pub HashMap<enums::PaymentMethod, SupportedPaymentMethodTypesForMandate>, ); #[derive(Debug, Deserialize, Clone)] pub struct SupportedPaymentMethodTypesForMandate( pub HashMap<enums::PaymentMethodType, SupportedConnectorsForMandate>, ); #[derive(Debug, Deserialize, Clone)] pub struct SupportedConnectorsForMandate { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct PaymentMethodTokenFilter { #[serde(deserialize_with = "deserialize_hashset")] pub payment_method: HashSet<diesel_models::enums::PaymentMethod>, pub payment_method_type: Option<PaymentMethodTypeTokenFilter>, pub long_lived_token: bool, pub apple_pay_pre_decrypt_flow: Option<ApplePayPreDecryptFlow>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(deny_unknown_fields, rename_all = "snake_case")] pub enum ApplePayPreDecryptFlow { #[default] ConnectorTokenization, NetworkTokenization, } #[derive(Debug, Deserialize, Clone, Default)] pub struct TempLockerEnablePaymentMethodFilter { #[serde(deserialize_with = "deserialize_hashset")] pub payment_method: HashSet<diesel_models::enums::PaymentMethod>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde( deny_unknown_fields, tag = "type", content = "list", rename_all = "snake_case" )] pub enum PaymentMethodTypeTokenFilter { #[serde(deserialize_with = "deserialize_hashset")] EnableOnly(HashSet<diesel_models::enums::PaymentMethodType>), #[serde(deserialize_with = "deserialize_hashset")] DisableOnly(HashSet<diesel_models::enums::PaymentMethodType>), #[default] AllAccepted, } #[derive(Debug, Deserialize, Clone, Default)] pub struct BankRedirectConfig(pub HashMap<enums::PaymentMethodType, ConnectorBankNames>); #[derive(Debug, Deserialize, Clone)] pub struct ConnectorBankNames(pub HashMap<String, BanksVector>); #[derive(Debug, Deserialize, Clone)] pub struct BanksVector { #[serde(deserialize_with = "deserialize_hashset")] pub banks: HashSet<common_enums::enums::BankNames>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct ConnectorFilters(pub HashMap<String, PaymentMethodFilters>); #[derive(Debug, Deserialize, Clone, Default)] #[serde(transparent)] pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCountryFlowFilter>); #[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)] #[serde(untagged)] pub enum PaymentMethodFilterKey { PaymentMethodType(enums::PaymentMethodType), CardNetwork(enums::CardNetwork), } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct CurrencyCountryFlowFilter { #[serde(deserialize_with = "deserialize_optional_hashset")] pub currency: Option<HashSet<enums::Currency>>, #[serde(deserialize_with = "deserialize_optional_hashset")] pub country: Option<HashSet<enums::CountryAlpha2>>, pub not_available_flows: Option<NotAvailableFlows>, } #[derive(Debug, Deserialize, Copy, Clone, Default)] #[serde(default)] pub struct NotAvailableFlows { pub capture_method: Option<enums::CaptureMethod>, } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Clone)] #[cfg_attr(feature = "v2", derive(Default))] // Configs are read from the config file in config/payout_required_fields.toml pub struct PayoutRequiredFields(pub HashMap<enums::PaymentMethod, PaymentMethodType>); #[derive(Debug, Deserialize, Clone)] #[cfg_attr(feature = "v2", derive(Default))] // Configs are read from the config file in config/payment_required_fields.toml pub struct RequiredFields(pub HashMap<enums::PaymentMethod, PaymentMethodType>); #[derive(Debug, Deserialize, Clone)] pub struct PaymentMethodType(pub HashMap<enums::PaymentMethodType, ConnectorFields>); #[derive(Debug, Deserialize, Clone)] pub struct ConnectorFields { pub fields: HashMap<enums::Connector, RequiredFieldFinal>, } #[cfg(feature = "v1")] #[derive(Debug, Deserialize, Clone)] pub struct RequiredFieldFinal { pub mandate: HashMap<String, RequiredFieldInfo>, pub non_mandate: HashMap<String, RequiredFieldInfo>, pub common: HashMap<String, RequiredFieldInfo>, } #[cfg(feature = "v2")] #[derive(Debug, Deserialize, Clone)] pub struct RequiredFieldFinal { pub mandate: Option<Vec<RequiredFieldInfo>>, pub non_mandate: Option<Vec<RequiredFieldInfo>>, pub common: Option<Vec<RequiredFieldInfo>>, } #[derive(Debug, Default, Deserialize, Clone)] #[serde(default)] pub struct Secrets { pub jwt_secret: Secret<String>, pub admin_api_key: Secret<String>, pub master_enc_key: Secret<String>, } #[derive(Debug, Default, Deserialize, Clone)] #[serde(default)] pub struct FallbackMerchantIds { #[serde(deserialize_with = "deserialize_merchant_ids")] pub merchant_ids: HashSet<id_type::MerchantId>, } #[derive(Debug, Clone, Default, Deserialize)] pub struct UserSettings { pub password_validity_in_days: u16, pub two_factor_auth_expiry_in_secs: i64, pub totp_issuer_name: String, pub base_url: String, pub force_two_factor_auth: bool, pub force_cookies: bool, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Locker { pub host: String, pub host_rs: String, pub mock_locker: bool, pub basilisk_host: String, pub locker_signing_key_id: String, pub locker_enabled: bool, pub ttl_for_storage_in_secs: i64, pub decryption_scheme: DecryptionScheme, } #[derive(Debug, Deserialize, Clone, Default)] pub enum DecryptionScheme { #[default] #[serde(rename = "RSA-OAEP")] RsaOaep, #[serde(rename = "RSA-OAEP-256")] RsaOaep256, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Refund { pub max_attempts: usize, pub max_age: i64, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct EphemeralConfig { pub validity: i64, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct Jwekey { pub vault_encryption_key: Secret<String>, pub rust_locker_encryption_key: Secret<String>, pub vault_private_key: Secret<String>, pub tunnel_private_key: Secret<String>, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Proxy { pub http_url: Option<String>, pub https_url: Option<String>, pub idle_pool_connection_timeout: Option<u64>, pub bypass_proxy_hosts: Option<String>, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Server { pub port: u16, pub workers: usize, pub host: String, pub request_body_limit: usize, pub shutdown_timeout: u64, #[cfg(feature = "tls")] pub tls: Option<ServerTls>, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Database { pub username: String, pub password: Secret<String>, pub host: String, pub port: u16, pub dbname: String, pub pool_size: u32, pub connection_timeout: u64, pub queue_strategy: QueueStrategy, pub min_idle: Option<u32>, pub max_lifetime: Option<u64>, } impl From<Database> for storage_impl::config::Database { fn from(val: Database) -> Self { Self { username: val.username, password: val.password, host: val.host, port: val.port, dbname: val.dbname, pool_size: val.pool_size, connection_timeout: val.connection_timeout, queue_strategy: val.queue_strategy, min_idle: val.min_idle, max_lifetime: val.max_lifetime, } } } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct SupportedConnectors { pub wallets: Vec<String>, } #[cfg(feature = "kv_store")] #[derive(Debug, Clone, Deserialize)] #[serde(default)] pub struct DrainerSettings { pub stream_name: String, pub num_partitions: u8, pub max_read_count: u64, pub shutdown_interval: u32, // in milliseconds pub loop_interval: u32, // in milliseconds } #[derive(Debug, Clone, Default, Deserialize)] #[serde(default)] pub struct WebhooksSettings { pub outgoing_enabled: bool, pub ignore_error: WebhookIgnoreErrorSettings, } #[derive(Debug, Clone, Deserialize, Default)] #[serde(default)] pub struct WebhookIgnoreErrorSettings { pub event_type: Option<bool>, pub payment_not_found: Option<bool>, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct ApiKeys { /// Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating /// hashes of API keys pub hash_key: Secret<String>, // Specifies the number of days before API key expiry when email reminders should be sent #[cfg(feature = "email")] pub expiry_reminder_days: Vec<u8>, #[cfg(feature = "partial-auth")] pub checksum_auth_context: Secret<String>, #[cfg(feature = "partial-auth")] pub checksum_auth_key: Secret<String>, #[cfg(feature = "partial-auth")] pub enable_partial_auth: bool, } #[derive(Debug, Deserialize, Clone, Default)] pub struct DelayedSessionConfig { #[serde(deserialize_with = "deserialize_hashset")] pub connectors_with_delayed_session_response: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct WebhookSourceVerificationCall { #[serde(deserialize_with = "deserialize_hashset")] pub connectors_with_webhook_source_verification_call: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct BillingConnectorPaymentsSyncCall { #[serde(deserialize_with = "deserialize_hashset")] pub billing_connectors_which_require_payment_sync: HashSet<enums::Connector>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct ApplePayDecryptConfig { pub apple_pay_ppc: Secret<String>, pub apple_pay_ppc_key: Secret<String>, pub apple_pay_merchant_cert: Secret<String>, pub apple_pay_merchant_cert_key: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct PazeDecryptConfig { pub paze_private_key: Secret<String>, pub paze_private_key_passphrase: Secret<String>, } #[derive(Debug, Deserialize, Clone)] pub struct GooglePayDecryptConfig { pub google_pay_root_signing_keys: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct LockerBasedRecipientConnectorList { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorRequestReferenceIdConfig { pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<id_type::MerchantId>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct UserAuthMethodSettings { pub encryption_key: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct NetworkTokenizationSupportedConnectors { #[serde(deserialize_with = "deserialize_hashset")] pub connector_list: HashSet<enums::Connector>, } impl Settings<SecuredSecret> { pub fn new() -> ApplicationResult<Self> { Self::with_config_path(None) } pub fn with_config_path(config_path: Option<PathBuf>) -> ApplicationResult<Self> { // Configuration values are picked up in the following priority order (1 being least // priority): // 1. Defaults from the implementation of the `Default` trait. // 2. Values from config file. The config file accessed depends on the environment // specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of // `development`, `sandbox` or `production`. If nothing is specified for `RUN_ENV`, // `/config/development.toml` file is read. // 3. Environment variables prefixed with `ROUTER` and each level separated by double // underscores. // // Values in config file override the defaults in `Default` trait, and the values set using // environment variables override both the defaults and the config file values. let environment = env::which(); let config_path = router_env::Config::config_path(&environment.to_string(), config_path); let config = router_env::Config::builder(&environment.to_string()) .change_context(ApplicationError::ConfigurationError)? .add_source(File::from(config_path).required(false)); #[cfg(feature = "v2")] let config = { let required_fields_config_file = router_env::Config::get_config_directory().join(REQUIRED_FIELDS_CONFIG_FILE); config.add_source(File::from(required_fields_config_file).required(false)) }; let config = config .add_source( Environment::with_prefix("ROUTER") .try_parsing(true) .separator("__") .list_separator(",") .with_list_parse_key("log.telemetry.route_to_trace") .with_list_parse_key("redis.cluster_urls") .with_list_parse_key("events.kafka.brokers") .with_list_parse_key("connectors.supported.wallets") .with_list_parse_key("connector_request_reference_id_config.merchant_ids_send_payment_id_as_connector_request_id"), ) .build() .change_context(ApplicationError::ConfigurationError)?; serde_path_to_error::deserialize(config) .attach_printable("Unable to deserialize application configuration") .change_context(ApplicationError::ConfigurationError) } pub fn validate(&self) -> ApplicationResult<()> { self.server.validate()?; self.master_database.get_inner().validate()?; #[cfg(feature = "olap")] self.replica_database.get_inner().validate()?; // The logger may not yet be initialized when validating the application configuration #[allow(clippy::print_stderr)] self.redis.validate().map_err(|error| { eprintln!("{error}"); ApplicationError::InvalidConfigurationValueError("Redis configuration".into()) })?; if self.log.file.enabled { if self.log.file.file_name.is_default_or_empty() { return Err(error_stack::Report::from( ApplicationError::InvalidConfigurationValueError( "log file name must not be empty".into(), ), )); } if self.log.file.path.is_default_or_empty() { return Err(error_stack::Report::from( ApplicationError::InvalidConfigurationValueError( "log directory path must not be empty".into(), ), )); } } self.secrets.get_inner().validate()?; self.locker.validate()?; self.connectors.validate("connectors")?; self.cors.validate()?; self.scheduler .as_ref() .map(|scheduler_settings| scheduler_settings.validate()) .transpose()?; #[cfg(feature = "kv_store")] self.drainer.validate()?; self.api_keys.get_inner().validate()?; self.file_storage .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; self.lock_settings.validate()?; self.events.validate()?; #[cfg(feature = "olap")] self.opensearch.validate()?; self.encryption_management .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; self.secrets_management .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; self.generic_link.payment_method_collect.validate()?; self.generic_link.payout_link.validate()?; #[cfg(feature = "v2")] self.cell_information.validate()?; self.network_tokenization_service .as_ref() .map(|x| x.get_inner().validate()) .transpose()?; self.paze_decrypt_keys .as_ref() .map(|x| x.get_inner().validate()) .transpose()?; self.google_pay_decrypt_keys .as_ref() .map(|x| x.validate()) .transpose()?; self.key_manager.get_inner().validate()?; #[cfg(feature = "email")] self.email .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; self.theme .storage .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; Ok(()) } } impl Settings<RawSecret> { #[cfg(feature = "kv_store")] pub fn is_kv_soft_kill_mode(&self) -> bool { self.kv_config.soft_kill.unwrap_or(false) } #[cfg(not(feature = "kv_store"))] pub fn is_kv_soft_kill_mode(&self) -> bool { false } } #[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Clone, Default)] pub struct Payouts { pub payout_eligibility: bool, #[serde(default)] pub required_fields: PayoutRequiredFields, } #[derive(Debug, Clone, Default)] pub struct LockSettings { pub redis_lock_expiry_seconds: u32, pub delay_between_retries_in_milliseconds: u32, pub lock_retries: u32, } impl<'de> Deserialize<'de> for LockSettings { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Inner { redis_lock_expiry_seconds: u32, delay_between_retries_in_milliseconds: u32, } let Inner { redis_lock_expiry_seconds, delay_between_retries_in_milliseconds, } = Inner::deserialize(deserializer)?; let redis_lock_expiry_milliseconds = redis_lock_expiry_seconds * 1000; Ok(Self { redis_lock_expiry_seconds, delay_between_retries_in_milliseconds, lock_retries: redis_lock_expiry_milliseconds / delay_between_retries_in_milliseconds, }) } } #[cfg(feature = "olap")] #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorOnboarding { pub paypal: PayPalOnboarding, } #[cfg(feature = "olap")] #[derive(Debug, Deserialize, Clone, Default)] pub struct PayPalOnboarding { pub client_id: Secret<String>, pub client_secret: Secret<String>, pub partner_id: Secret<String>, pub enabled: bool, } #[cfg(feature = "tls")] #[derive(Debug, Deserialize, Clone)] pub struct ServerTls { /// Port to host the TLS secure server on pub port: u16, /// Use a different host (optional) (defaults to the host provided in [`Server`] config) pub host: Option<String>, /// private key file path associated with TLS (path to the private key file (`pem` format)) pub private_key: PathBuf, /// certificate file associated with TLS (path to the certificate file (`pem` format)) pub certificate: PathBuf, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] pub struct CellInformation { pub id: id_type::CellId, } #[cfg(feature = "v2")] impl Default for CellInformation { fn default() -> Self { // We provide a static default cell id for constructing application settings. // This will only panic at application startup if we're unable to construct the default, // around the time of deserializing application settings. // And a panic at application startup is considered acceptable. #[allow(clippy::expect_used)] let cell_id = id_type::CellId::from_string("defid").expect("Failed to create a default for Cell Id"); Self { id: cell_id } } } #[derive(Debug, Deserialize, Clone, Default)] pub struct ThemeSettings { pub storage: FileStorageConfig, pub email_config: EmailThemeConfig, } fn deserialize_hashmap_inner<K, V>( value: HashMap<String, String>, ) -> Result<HashMap<K, HashSet<V>>, String> where K: Eq + std::str::FromStr + std::hash::Hash, V: Eq + std::str::FromStr + std::hash::Hash, <K as std::str::FromStr>::Err: std::fmt::Display, <V as std::str::FromStr>::Err: std::fmt::Display, { let (values, errors) = value .into_iter() .map( |(k, v)| match (K::from_str(k.trim()), deserialize_hashset_inner(v)) { (Err(error), _) => Err(format!( "Unable to deserialize `{}` as `{}`: {error}", k, std::any::type_name::<K>() )), (_, Err(error)) => Err(error), (Ok(key), Ok(value)) => Ok((key, value)), }, ) .fold( (HashMap::new(), Vec::new()), |(mut values, mut errors), result| match result { Ok((key, value)) => { values.insert(key, value); (values, errors) } Err(error) => { errors.push(error); (values, errors) } }, ); if !errors.is_empty() { Err(format!("Some errors occurred:\n{}", errors.join("\n"))) } else { Ok(values) } } fn deserialize_hashmap<'a, D, K, V>(deserializer: D) -> Result<HashMap<K, HashSet<V>>, D::Error> where D: serde::Deserializer<'a>, K: Eq + std::str::FromStr + std::hash::Hash, V: Eq + std::str::FromStr + std::hash::Hash, <K as std::str::FromStr>::Err: std::fmt::Display, <V as std::str::FromStr>::Err: std::fmt::Display, { use serde::de::Error; deserialize_hashmap_inner(<HashMap<String, String>>::deserialize(deserializer)?) .map_err(D::Error::custom) } fn deserialize_hashset_inner<T>(value: impl AsRef<str>) -> Result<HashSet<T>, String> where T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { let (values, errors) = value .as_ref() .trim() .split(',') .map(|s| { T::from_str(s.trim()).map_err(|error| { format!( "Unable to deserialize `{}` as `{}`: {error}", s.trim(), std::any::type_name::<T>() ) }) }) .fold( (HashSet::new(), Vec::new()), |(mut values, mut errors), result| match result { Ok(t) => { values.insert(t); (values, errors) } Err(error) => { errors.push(error); (values, errors) } }, ); if !errors.is_empty() { Err(format!("Some errors occurred:\n{}", errors.join("\n"))) } else { Ok(values) } } fn deserialize_hashset<'a, D, T>(deserializer: D) -> Result<HashSet<T>, D::Error> where D: serde::Deserializer<'a>, T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { use serde::de::Error; deserialize_hashset_inner(<String>::deserialize(deserializer)?).map_err(D::Error::custom) } fn deserialize_optional_hashset<'a, D, T>(deserializer: D) -> Result<Option<HashSet<T>>, D::Error> where D: serde::Deserializer<'a>, T: Eq + std::str::FromStr + std::hash::Hash, <T as std::str::FromStr>::Err: std::fmt::Display, { use serde::de::Error; <Option<String>>::deserialize(deserializer).map(|value| { value.map_or(Ok(None), |inner: String| { let list = deserialize_hashset_inner(inner).map_err(D::Error::custom)?; match list.len() { 0 => Ok(None), _ => Ok(Some(list)), } }) })? } fn deserialize_merchant_ids_inner( value: impl AsRef<str>, ) -> Result<HashSet<id_type::MerchantId>, String> { let (values, errors) = value .as_ref() .trim() .split(',') .map(|s| { let trimmed = s.trim(); id_type::MerchantId::wrap(trimmed.to_owned()).map_err(|error| { format!( "Unable to deserialize `{}` as `MerchantId`: {error}", trimmed ) }) }) .fold( (HashSet::new(), Vec::new()), |(mut values, mut errors), result| match result { Ok(t) => { values.insert(t); (values, errors) } Err(error) => { errors.push(error); (values, errors) } }, ); if !errors.is_empty() { Err(format!("Some errors occurred:\n{}", errors.join("\n"))) } else { Ok(values) } } fn deserialize_merchant_ids<'de, D>( deserializer: D, ) -> Result<HashSet<id_type::MerchantId>, D::Error> where D: serde::Deserializer<'de>, { let s = String::deserialize(deserializer)?; deserialize_merchant_ids_inner(s).map_err(serde::de::Error::custom) } impl<'de> Deserialize<'de> for TenantConfig { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] struct Inner { base_url: String, schema: String, accounts_schema: String, redis_key_prefix: String, clickhouse_database: String, user: TenantUserConfig, } let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?; Ok(Self( hashmap .into_iter() .map(|(key, value)| { ( key.clone(), Tenant { tenant_id: key, base_url: value.base_url, schema: value.schema, accounts_schema: value.accounts_schema, redis_key_prefix: value.redis_key_prefix, clickhouse_database: value.clickhouse_database, user: value.user, }, ) }) .collect(), )) } } #[cfg(test)] mod hashmap_deserialization_test { #![allow(clippy::unwrap_used)] use std::collections::{HashMap, HashSet}; use serde::de::{ value::{Error as ValueError, MapDeserializer}, IntoDeserializer, }; use super::deserialize_hashmap; #[test] fn test_payment_method_and_payment_method_types() { use diesel_models::enums::{PaymentMethod, PaymentMethodType}; let input_map: HashMap<String, String> = HashMap::from([ ("bank_transfer".to_string(), "ach,bacs".to_string()), ("wallet".to_string(), "paypal,venmo".to_string()), ]); let deserializer: MapDeserializer< '_, std::collections::hash_map::IntoIter<String, String>, ValueError, > = input_map.into_deserializer(); let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer); let expected_result = HashMap::from([ ( PaymentMethod::BankTransfer, HashSet::from([PaymentMethodType::Ach, PaymentMethodType::Bacs]), ), ( PaymentMethod::Wallet, HashSet::from([PaymentMethodType::Paypal, PaymentMethodType::Venmo]), ), ]); assert!(result.is_ok()); assert_eq!(result.unwrap(), expected_result); } #[test] fn test_payment_method_and_payment_method_types_with_spaces() { use diesel_models::enums::{PaymentMethod, PaymentMethodType}; let input_map: HashMap<String, String> = HashMap::from([ (" bank_transfer ".to_string(), " ach , bacs ".to_string()), ("wallet ".to_string(), " paypal , pix , venmo ".to_string()), ]); let deserializer: MapDeserializer< '_, std::collections::hash_map::IntoIter<String, String>, ValueError, > = input_map.into_deserializer(); let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer); let expected_result = HashMap::from([ ( PaymentMethod::BankTransfer, HashSet::from([PaymentMethodType::Ach, PaymentMethodType::Bacs]), ), ( PaymentMethod::Wallet, HashSet::from([ PaymentMethodType::Paypal, PaymentMethodType::Pix, PaymentMethodType::Venmo, ]), ), ]); assert!(result.is_ok()); assert_eq!(result.unwrap(), expected_result); } #[test] fn test_payment_method_deserializer_error() { use diesel_models::enums::{PaymentMethod, PaymentMethodType}; let input_map: HashMap<String, String> = HashMap::from([ ("unknown".to_string(), "ach,bacs".to_string()), ("wallet".to_string(), "paypal,unknown".to_string()), ]); let deserializer: MapDeserializer< '_, std::collections::hash_map::IntoIter<String, String>, ValueError, > = input_map.into_deserializer(); let result = deserialize_hashmap::<'_, _, PaymentMethod, PaymentMethodType>(deserializer); assert!(result.is_err()); } } #[cfg(test)] mod hashset_deserialization_test { #![allow(clippy::unwrap_used)] use std::collections::HashSet; use serde::de::{ value::{Error as ValueError, StrDeserializer}, IntoDeserializer, }; use super::deserialize_hashset; #[test] fn test_payment_method_hashset_deserializer() { use diesel_models::enums::PaymentMethod; let deserializer: StrDeserializer<'_, ValueError> = "wallet,card".into_deserializer(); let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); let expected_payment_methods = HashSet::from([PaymentMethod::Wallet, PaymentMethod::Card]); assert!(payment_methods.is_ok()); assert_eq!(payment_methods.unwrap(), expected_payment_methods); } #[test] fn test_payment_method_hashset_deserializer_with_spaces() { use diesel_models::enums::PaymentMethod; let deserializer: StrDeserializer<'_, ValueError> = "wallet, card, bank_debit".into_deserializer(); let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); let expected_payment_methods = HashSet::from([ PaymentMethod::Wallet, PaymentMethod::Card, PaymentMethod::BankDebit, ]); assert!(payment_methods.is_ok()); assert_eq!(payment_methods.unwrap(), expected_payment_methods); } #[test] fn test_payment_method_hashset_deserializer_error() { use diesel_models::enums::PaymentMethod; let deserializer: StrDeserializer<'_, ValueError> = "wallet, card, unknown".into_deserializer(); let payment_methods = deserialize_hashset::<'_, _, PaymentMethod>(deserializer); assert!(payment_methods.is_err()); } }
10,969
1,486
hyperswitch
crates/router/src/configs/validations.rs
.rs
use common_utils::ext_traits::ConfigExt; use masking::PeekInterface; use storage_impl::errors::ApplicationError; impl super::settings::Secrets { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.jwt_secret.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "JWT secret must not be empty".into(), )) })?; when(self.admin_api_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "admin API key must not be empty".into(), )) })?; when(self.master_enc_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Master encryption key must not be empty".into(), )) }) } } impl super::settings::Locker { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(!self.mock_locker && self.host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "locker host must not be empty when mock locker is disabled".into(), )) })?; when( !self.mock_locker && self.basilisk_host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "basilisk host must not be empty when mock locker is disabled".into(), )) }, ) } } impl super::settings::Server { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "server host must not be empty".into(), )) })?; when(self.workers == 0, || { Err(ApplicationError::InvalidConfigurationValueError( "number of workers must be greater than 0".into(), )) }) } } impl super::settings::Database { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "database host must not be empty".into(), )) })?; when(self.dbname.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "database name must not be empty".into(), )) })?; when(self.username.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "database user username must not be empty".into(), )) })?; when(self.password.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "database user password must not be empty".into(), )) }) } } impl super::settings::SupportedConnectors { pub fn validate(&self) -> Result<(), ApplicationError> { common_utils::fp_utils::when(self.wallets.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "list of connectors supporting wallets must not be empty".into(), )) }) } } impl super::settings::CorsSettings { pub fn validate(&self) -> Result<(), ApplicationError> { common_utils::fp_utils::when(self.wildcard_origin && !self.origins.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Allowed Origins must be empty when wildcard origin is true".to_string(), )) })?; common_utils::fp_utils::when(!self.wildcard_origin && self.origins.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Allowed origins must not be empty. Please either enable wildcard origin or provide Allowed Origin".to_string(), )) }) } } #[cfg(feature = "kv_store")] impl super::settings::DrainerSettings { pub fn validate(&self) -> Result<(), ApplicationError> { common_utils::fp_utils::when(self.stream_name.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "drainer stream name must not be empty".into(), )) }) } } impl super::settings::ApiKeys { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.hash_key.peek().is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "API key hashing key must not be empty".into(), )) })?; #[cfg(feature = "email")] when(self.expiry_reminder_days.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "API key expiry reminder days must not be empty".into(), )) })?; Ok(()) } } impl super::settings::LockSettings { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.redis_lock_expiry_seconds.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "redis_lock_expiry_seconds must not be empty or 0".into(), )) })?; when( self.delay_between_retries_in_milliseconds .is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "delay_between_retries_in_milliseconds must not be empty or 0".into(), )) }, )?; when(self.lock_retries.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "lock_retries must not be empty or 0".into(), )) }) } } impl super::settings::GenericLinkEnvConfig { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.expiry == 0, || { Err(ApplicationError::InvalidConfigurationValueError( "link's expiry should not be 0".into(), )) }) } } #[cfg(feature = "v2")] impl super::settings::CellInformation { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::{fp_utils::when, id_type}; when(self == &Self::default(), || { Err(ApplicationError::InvalidConfigurationValueError( "CellId cannot be set to a default".into(), )) }) } } impl super::settings::NetworkTokenizationService { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.token_service_api_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "token_service_api_key must not be empty".into(), )) })?; when(self.public_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "public_key must not be empty".into(), )) })?; when(self.key_id.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "key_id must not be empty".into(), )) })?; when(self.private_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "private_key must not be empty".into(), )) }) } } impl super::settings::PazeDecryptConfig { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.paze_private_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "paze_private_key must not be empty".into(), )) })?; when( self.paze_private_key_passphrase.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "paze_private_key_passphrase must not be empty".into(), )) }, ) } } impl super::settings::GooglePayDecryptConfig { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when( self.google_pay_root_signing_keys.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "google_pay_root_signing_keys must not be empty".into(), )) }, ) } } impl super::settings::KeyManagerConfig { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; #[cfg(feature = "keymanager_mtls")] when( self.enabled && (self.ca.is_default_or_empty() || self.cert.is_default_or_empty()), || { Err(ApplicationError::InvalidConfigurationValueError( "Invalid CA or Certificate for Keymanager.".into(), )) }, )?; when(self.enabled && self.url.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "Invalid URL for Keymanager".into(), )) }) } }
1,914
1,487
hyperswitch
crates/router/src/configs/defaults.rs
.rs
use std::collections::{HashMap, HashSet}; use api_models::{enums, payment_methods::RequiredFieldInfo}; use common_utils::id_type; #[cfg(feature = "payouts")] pub mod payout_required_fields; pub mod payment_connector_required_fields; impl Default for super::settings::Server { fn default() -> Self { Self { port: 8080, workers: num_cpus::get_physical(), host: "localhost".into(), request_body_limit: 16 * 1024, // POST request body is limited to 16KiB shutdown_timeout: 30, #[cfg(feature = "tls")] tls: None, } } } impl Default for super::settings::CorsSettings { fn default() -> Self { Self { origins: HashSet::from_iter(["http://localhost:8080".to_string()]), allowed_methods: HashSet::from_iter( ["GET", "PUT", "POST", "DELETE"] .into_iter() .map(ToString::to_string), ), wildcard_origin: false, max_age: 30, } } } impl Default for super::settings::Database { fn default() -> Self { Self { username: String::new(), password: String::new().into(), host: "localhost".into(), port: 5432, dbname: String::new(), pool_size: 5, connection_timeout: 10, queue_strategy: Default::default(), min_idle: None, max_lifetime: None, } } } impl Default for super::settings::Proxy { fn default() -> Self { Self { http_url: Default::default(), https_url: Default::default(), idle_pool_connection_timeout: Some(90), bypass_proxy_hosts: Default::default(), } } } impl Default for super::settings::Locker { fn default() -> Self { Self { host: "localhost".into(), host_rs: "localhost".into(), mock_locker: true, basilisk_host: "localhost".into(), locker_signing_key_id: "1".into(), //true or false locker_enabled: true, //Time to live for storage entries in locker ttl_for_storage_in_secs: 60 * 60 * 24 * 365 * 7, decryption_scheme: Default::default(), } } } impl Default for super::settings::SupportedConnectors { fn default() -> Self { Self { wallets: ["klarna", "braintree"].map(Into::into).into(), /* cards: [ "adyen", "authorizedotnet", "braintree", "checkout", "cybersource", "fiserv", "rapyd", "stripe", ] .map(Into::into) .into(), */ } } } impl Default for super::settings::Refund { fn default() -> Self { Self { max_attempts: 10, max_age: 365, } } } impl Default for super::settings::EphemeralConfig { fn default() -> Self { Self { validity: 1 } } } #[cfg(feature = "kv_store")] impl Default for super::settings::DrainerSettings { fn default() -> Self { Self { stream_name: "DRAINER_STREAM".into(), num_partitions: 64, max_read_count: 100, shutdown_interval: 1000, loop_interval: 100, } } } #[cfg(feature = "kv_store")] impl Default for super::settings::KvConfig { fn default() -> Self { Self { ttl: 900, soft_kill: Some(false), } } } impl Default for super::settings::GlobalTenant { fn default() -> Self { Self { tenant_id: id_type::TenantId::get_default_global_tenant_id(), schema: String::from("global"), redis_key_prefix: String::from("global"), clickhouse_database: String::from("global"), } } } #[allow(clippy::derivable_impls)] impl Default for super::settings::ApiKeys { fn default() -> Self { Self { // Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating // hashes of API keys hash_key: String::new().into(), // Specifies the number of days before API key expiry when email reminders should be sent #[cfg(feature = "email")] expiry_reminder_days: vec![7, 3, 1], // Hex-encoded key used for calculating checksum for partial auth #[cfg(feature = "partial-auth")] checksum_auth_key: String::new().into(), // context used for blake3 #[cfg(feature = "partial-auth")] checksum_auth_context: String::new().into(), #[cfg(feature = "partial-auth")] enable_partial_auth: false, } } } pub fn get_billing_required_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, }, ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, }, ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, }, ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, }, ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, }, ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry { options: vec!["ALL".to_string()], }, value: None, }, ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, }, ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line2".to_string(), display_name: "line2".to_string(), field_type: enums::FieldType::UserAddressLine2, value: None, }, ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, }, ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, }, ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, }, ), ]) } pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ ( "shipping.address.first_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.first_name".to_string(), display_name: "shipping_first_name".to_string(), field_type: enums::FieldType::UserShippingName, value: None, }, ), ( "shipping.address.last_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.last_name".to_string(), display_name: "shipping_last_name".to_string(), field_type: enums::FieldType::UserShippingName, value: None, }, ), ( "shipping.address.city".to_string(), RequiredFieldInfo { required_field: "shipping.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserShippingAddressCity, value: None, }, ), ( "shipping.address.state".to_string(), RequiredFieldInfo { required_field: "shipping.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserShippingAddressState, value: None, }, ), ( "shipping.address.zip".to_string(), RequiredFieldInfo { required_field: "shipping.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserShippingAddressPincode, value: None, }, ), ( "shipping.address.country".to_string(), RequiredFieldInfo { required_field: "shipping.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserShippingAddressCountry { options: vec!["ALL".to_string()], }, value: None, }, ), ( "shipping.address.line1".to_string(), RequiredFieldInfo { required_field: "shipping.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserShippingAddressLine1, value: None, }, ), ( "shipping.phone.number".to_string(), RequiredFieldInfo { required_field: "shipping.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, }, ), ( "shipping.phone.country_code".to_string(), RequiredFieldInfo { required_field: "shipping.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, }, ), ( "shipping.email".to_string(), RequiredFieldInfo { required_field: "shipping.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, }, ), ]) }
2,511
1,488
hyperswitch
crates/router/src/configs/secrets_transformers.rs
.rs
use common_utils::{errors::CustomResult, ext_traits::AsyncExt}; use hyperswitch_interfaces::secrets_interface::{ secret_handler::SecretsHandler, secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, SecretManagementInterface, SecretsManagementError, }; use crate::settings::{self, Settings}; #[async_trait::async_trait] impl SecretsHandler for settings::Database { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let db = value.get_inner(); let db_password = secret_management_client .get_secret(db.password.clone()) .await?; Ok(value.transition_state(|db| Self { password: db_password, ..db })) } } #[async_trait::async_trait] impl SecretsHandler for settings::Jwekey { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let jwekey = value.get_inner(); let ( vault_encryption_key, rust_locker_encryption_key, vault_private_key, tunnel_private_key, ) = tokio::try_join!( secret_management_client.get_secret(jwekey.vault_encryption_key.clone()), secret_management_client.get_secret(jwekey.rust_locker_encryption_key.clone()), secret_management_client.get_secret(jwekey.vault_private_key.clone()), secret_management_client.get_secret(jwekey.tunnel_private_key.clone()) )?; Ok(value.transition_state(|_| Self { vault_encryption_key, rust_locker_encryption_key, vault_private_key, tunnel_private_key, })) } } #[cfg(feature = "olap")] #[async_trait::async_trait] impl SecretsHandler for settings::ConnectorOnboarding { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let onboarding_config = &value.get_inner().paypal; let (client_id, client_secret, partner_id) = tokio::try_join!( secret_management_client.get_secret(onboarding_config.client_id.clone()), secret_management_client.get_secret(onboarding_config.client_secret.clone()), secret_management_client.get_secret(onboarding_config.partner_id.clone()) )?; Ok(value.transition_state(|onboarding_config| Self { paypal: settings::PayPalOnboarding { client_id, client_secret, partner_id, ..onboarding_config.paypal }, })) } } #[async_trait::async_trait] impl SecretsHandler for settings::ForexApi { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let forex_api = value.get_inner(); let (api_key, fallback_api_key) = tokio::try_join!( secret_management_client.get_secret(forex_api.api_key.clone()), secret_management_client.get_secret(forex_api.fallback_api_key.clone()), )?; Ok(value.transition_state(|forex_api| Self { api_key, fallback_api_key, ..forex_api })) } } #[async_trait::async_trait] impl SecretsHandler for settings::ApiKeys { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let api_keys = value.get_inner(); let hash_key = secret_management_client .get_secret(api_keys.hash_key.clone()) .await?; #[cfg(feature = "email")] let expiry_reminder_days = api_keys.expiry_reminder_days.clone(); #[cfg(feature = "partial-auth")] let enable_partial_auth = api_keys.enable_partial_auth; #[cfg(feature = "partial-auth")] let (checksum_auth_context, checksum_auth_key) = { if enable_partial_auth { let checksum_auth_context = secret_management_client .get_secret(api_keys.checksum_auth_context.clone()) .await?; let checksum_auth_key = secret_management_client .get_secret(api_keys.checksum_auth_key.clone()) .await?; (checksum_auth_context, checksum_auth_key) } else { (String::new().into(), String::new().into()) } }; Ok(value.transition_state(|_| Self { hash_key, #[cfg(feature = "email")] expiry_reminder_days, #[cfg(feature = "partial-auth")] checksum_auth_key, #[cfg(feature = "partial-auth")] checksum_auth_context, #[cfg(feature = "partial-auth")] enable_partial_auth, })) } } #[async_trait::async_trait] impl SecretsHandler for settings::ApplePayDecryptConfig { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let applepay_decrypt_keys = value.get_inner(); let ( apple_pay_ppc, apple_pay_ppc_key, apple_pay_merchant_cert, apple_pay_merchant_cert_key, ) = tokio::try_join!( secret_management_client.get_secret(applepay_decrypt_keys.apple_pay_ppc.clone()), secret_management_client.get_secret(applepay_decrypt_keys.apple_pay_ppc_key.clone()), secret_management_client .get_secret(applepay_decrypt_keys.apple_pay_merchant_cert.clone()), secret_management_client .get_secret(applepay_decrypt_keys.apple_pay_merchant_cert_key.clone()), )?; Ok(value.transition_state(|_| Self { apple_pay_ppc, apple_pay_ppc_key, apple_pay_merchant_cert, apple_pay_merchant_cert_key, })) } } #[async_trait::async_trait] impl SecretsHandler for settings::PazeDecryptConfig { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let paze_decrypt_keys = value.get_inner(); let (paze_private_key, paze_private_key_passphrase) = tokio::try_join!( secret_management_client.get_secret(paze_decrypt_keys.paze_private_key.clone()), secret_management_client .get_secret(paze_decrypt_keys.paze_private_key_passphrase.clone()), )?; Ok(value.transition_state(|_| Self { paze_private_key, paze_private_key_passphrase, })) } } #[async_trait::async_trait] impl SecretsHandler for settings::ApplepayMerchantConfigs { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let applepay_merchant_configs = value.get_inner(); let (merchant_cert, merchant_cert_key, common_merchant_identifier) = tokio::try_join!( secret_management_client.get_secret(applepay_merchant_configs.merchant_cert.clone()), secret_management_client .get_secret(applepay_merchant_configs.merchant_cert_key.clone()), secret_management_client .get_secret(applepay_merchant_configs.common_merchant_identifier.clone()), )?; Ok(value.transition_state(|applepay_merchant_configs| Self { merchant_cert, merchant_cert_key, common_merchant_identifier, ..applepay_merchant_configs })) } } #[async_trait::async_trait] impl SecretsHandler for settings::PaymentMethodAuth { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let payment_method_auth = value.get_inner(); let pm_auth_key = secret_management_client .get_secret(payment_method_auth.pm_auth_key.clone()) .await?; Ok(value.transition_state(|payment_method_auth| Self { pm_auth_key, ..payment_method_auth })) } } #[async_trait::async_trait] impl SecretsHandler for settings::KeyManagerConfig { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, _secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { #[cfg(feature = "keymanager_mtls")] let keyconfig = value.get_inner(); #[cfg(feature = "keymanager_mtls")] let ca = if keyconfig.enabled { _secret_management_client .get_secret(keyconfig.ca.clone()) .await? } else { keyconfig.ca.clone() }; #[cfg(feature = "keymanager_mtls")] let cert = if keyconfig.enabled { _secret_management_client .get_secret(keyconfig.cert.clone()) .await? } else { keyconfig.ca.clone() }; Ok(value.transition_state(|keyconfig| Self { #[cfg(feature = "keymanager_mtls")] ca, #[cfg(feature = "keymanager_mtls")] cert, ..keyconfig })) } } #[async_trait::async_trait] impl SecretsHandler for settings::Secrets { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let secrets = value.get_inner(); let (jwt_secret, admin_api_key, master_enc_key) = tokio::try_join!( secret_management_client.get_secret(secrets.jwt_secret.clone()), secret_management_client.get_secret(secrets.admin_api_key.clone()), secret_management_client.get_secret(secrets.master_enc_key.clone()) )?; Ok(value.transition_state(|_| Self { jwt_secret, admin_api_key, master_enc_key, })) } } #[async_trait::async_trait] impl SecretsHandler for settings::UserAuthMethodSettings { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let user_auth_methods = value.get_inner(); let encryption_key = secret_management_client .get_secret(user_auth_methods.encryption_key.clone()) .await?; Ok(value.transition_state(|_| Self { encryption_key })) } } #[async_trait::async_trait] impl SecretsHandler for settings::NetworkTokenizationService { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let network_tokenization = value.get_inner(); let token_service_api_key = secret_management_client .get_secret(network_tokenization.token_service_api_key.clone()) .await?; let public_key = secret_management_client .get_secret(network_tokenization.public_key.clone()) .await?; let private_key = secret_management_client .get_secret(network_tokenization.private_key.clone()) .await?; Ok(value.transition_state(|network_tokenization| Self { public_key, private_key, token_service_api_key, ..network_tokenization })) } } /// # Panics /// /// Will panic even if kms decryption fails for at least one field pub(crate) async fn fetch_raw_secrets( conf: Settings<SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> Settings<RawSecret> { #[allow(clippy::expect_used)] let master_database = settings::Database::convert_to_raw_secret(conf.master_database, secret_management_client) .await .expect("Failed to decrypt master database configuration"); #[cfg(feature = "olap")] #[allow(clippy::expect_used)] let analytics = analytics::AnalyticsConfig::convert_to_raw_secret(conf.analytics, secret_management_client) .await .expect("Failed to decrypt analytics configuration"); #[cfg(feature = "olap")] #[allow(clippy::expect_used)] let replica_database = settings::Database::convert_to_raw_secret(conf.replica_database, secret_management_client) .await .expect("Failed to decrypt replica database configuration"); #[allow(clippy::expect_used)] let secrets = settings::Secrets::convert_to_raw_secret(conf.secrets, secret_management_client) .await .expect("Failed to decrypt secrets"); #[allow(clippy::expect_used)] let forex_api = settings::ForexApi::convert_to_raw_secret(conf.forex_api, secret_management_client) .await .expect("Failed to decrypt forex api configs"); #[allow(clippy::expect_used)] let jwekey = settings::Jwekey::convert_to_raw_secret(conf.jwekey, secret_management_client) .await .expect("Failed to decrypt jwekey configs"); #[allow(clippy::expect_used)] let api_keys = settings::ApiKeys::convert_to_raw_secret(conf.api_keys, secret_management_client) .await .expect("Failed to decrypt api_keys configs"); #[cfg(feature = "olap")] #[allow(clippy::expect_used)] let connector_onboarding = settings::ConnectorOnboarding::convert_to_raw_secret( conf.connector_onboarding, secret_management_client, ) .await .expect("Failed to decrypt connector_onboarding configs"); #[allow(clippy::expect_used)] let applepay_decrypt_keys = settings::ApplePayDecryptConfig::convert_to_raw_secret( conf.applepay_decrypt_keys, secret_management_client, ) .await .expect("Failed to decrypt applepay decrypt configs"); #[allow(clippy::expect_used)] let paze_decrypt_keys = if let Some(paze_keys) = conf.paze_decrypt_keys { Some( settings::PazeDecryptConfig::convert_to_raw_secret(paze_keys, secret_management_client) .await .expect("Failed to decrypt paze decrypt configs"), ) } else { None }; #[allow(clippy::expect_used)] let applepay_merchant_configs = settings::ApplepayMerchantConfigs::convert_to_raw_secret( conf.applepay_merchant_configs, secret_management_client, ) .await .expect("Failed to decrypt applepay merchant configs"); #[allow(clippy::expect_used)] let payment_method_auth = settings::PaymentMethodAuth::convert_to_raw_secret( conf.payment_method_auth, secret_management_client, ) .await .expect("Failed to decrypt payment method auth configs"); #[allow(clippy::expect_used)] let key_manager = settings::KeyManagerConfig::convert_to_raw_secret( conf.key_manager, secret_management_client, ) .await .expect("Failed to decrypt keymanager configs"); #[allow(clippy::expect_used)] let user_auth_methods = settings::UserAuthMethodSettings::convert_to_raw_secret( conf.user_auth_methods, secret_management_client, ) .await .expect("Failed to decrypt user_auth_methods configs"); #[allow(clippy::expect_used)] let network_tokenization_service = conf .network_tokenization_service .async_map(|network_tokenization_service| async { settings::NetworkTokenizationService::convert_to_raw_secret( network_tokenization_service, secret_management_client, ) .await .expect("Failed to decrypt network tokenization service configs") }) .await; Settings { server: conf.server, master_database, redis: conf.redis, log: conf.log, #[cfg(feature = "kv_store")] drainer: conf.drainer, encryption_management: conf.encryption_management, secrets_management: conf.secrets_management, proxy: conf.proxy, env: conf.env, key_manager, #[cfg(feature = "olap")] replica_database, secrets, fallback_merchant_ids_api_key_auth: conf.fallback_merchant_ids_api_key_auth, locker: conf.locker, connectors: conf.connectors, forex_api, refund: conf.refund, eph_key: conf.eph_key, scheduler: conf.scheduler, jwekey, webhooks: conf.webhooks, pm_filters: conf.pm_filters, payout_method_filters: conf.payout_method_filters, bank_config: conf.bank_config, api_keys, file_storage: conf.file_storage, tokenization: conf.tokenization, connector_customer: conf.connector_customer, #[cfg(feature = "dummy_connector")] dummy_connector: conf.dummy_connector, #[cfg(feature = "email")] email: conf.email, user: conf.user, mandates: conf.mandates, network_transaction_id_supported_connectors: conf .network_transaction_id_supported_connectors, required_fields: conf.required_fields, delayed_session_response: conf.delayed_session_response, webhook_source_verification_call: conf.webhook_source_verification_call, billing_connectors_payment_sync: conf.billing_connectors_payment_sync, payment_method_auth, connector_request_reference_id_config: conf.connector_request_reference_id_config, #[cfg(feature = "payouts")] payouts: conf.payouts, applepay_decrypt_keys, paze_decrypt_keys, google_pay_decrypt_keys: conf.google_pay_decrypt_keys, multiple_api_version_supported_connectors: conf.multiple_api_version_supported_connectors, applepay_merchant_configs, lock_settings: conf.lock_settings, temp_locker_enable_config: conf.temp_locker_enable_config, generic_link: conf.generic_link, payment_link: conf.payment_link, #[cfg(feature = "olap")] analytics, #[cfg(feature = "olap")] opensearch: conf.opensearch, #[cfg(feature = "kv_store")] kv_config: conf.kv_config, #[cfg(feature = "frm")] frm: conf.frm, #[cfg(feature = "olap")] report_download_config: conf.report_download_config, events: conf.events, #[cfg(feature = "olap")] connector_onboarding, cors: conf.cors, unmasked_headers: conf.unmasked_headers, saved_payment_methods: conf.saved_payment_methods, multitenancy: conf.multitenancy, user_auth_methods, decision: conf.decision, locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors, grpc_client: conf.grpc_client, #[cfg(feature = "v2")] cell_information: conf.cell_information, network_tokenization_supported_card_networks: conf .network_tokenization_supported_card_networks, network_tokenization_service, network_tokenization_supported_connectors: conf.network_tokenization_supported_connectors, theme: conf.theme, platform: conf.platform, } }
4,170
1,489
hyperswitch
crates/router/src/configs/defaults/payment_connector_required_fields.rs
.rs
use std::collections::{HashMap, HashSet}; use api_models::{enums, payment_methods::RequiredFieldInfo}; use crate::settings::{ self, ConnectorFields, Mandates, PaymentMethodType, RequiredFieldFinal, SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate, SupportedPaymentMethodsForMandate, }; impl Default for Mandates { fn default() -> Self { Self { supported_payment_methods: SupportedPaymentMethodsForMandate(HashMap::from([ ( enums::PaymentMethod::PayLater, SupportedPaymentMethodTypesForMandate(HashMap::from([( enums::PaymentMethodType::Klarna, SupportedConnectorsForMandate { connector_list: HashSet::from([enums::Connector::Adyen]), }, )])), ), ( enums::PaymentMethod::Wallet, SupportedPaymentMethodTypesForMandate(HashMap::from([ ( enums::PaymentMethodType::GooglePay, SupportedConnectorsForMandate { connector_list: HashSet::from([ enums::Connector::Stripe, enums::Connector::Adyen, enums::Connector::Globalpay, enums::Connector::Multisafepay, enums::Connector::Bankofamerica, enums::Connector::Novalnet, enums::Connector::Noon, enums::Connector::Cybersource, enums::Connector::Wellsfargo, ]), }, ), ( enums::PaymentMethodType::ApplePay, SupportedConnectorsForMandate { connector_list: HashSet::from([ enums::Connector::Stripe, enums::Connector::Adyen, enums::Connector::Bankofamerica, enums::Connector::Cybersource, enums::Connector::Novalnet, enums::Connector::Wellsfargo, ]), }, ), ( enums::PaymentMethodType::SamsungPay, SupportedConnectorsForMandate { connector_list: HashSet::from([enums::Connector::Cybersource]), }, ), ])), ), ( enums::PaymentMethod::Card, SupportedPaymentMethodTypesForMandate(HashMap::from([ ( enums::PaymentMethodType::Credit, SupportedConnectorsForMandate { connector_list: HashSet::from([ enums::Connector::Aci, enums::Connector::Adyen, enums::Connector::Authorizedotnet, enums::Connector::Globalpay, enums::Connector::Worldpay, enums::Connector::Fiuu, enums::Connector::Multisafepay, enums::Connector::Nexinets, enums::Connector::Noon, enums::Connector::Novalnet, enums::Connector::Payme, enums::Connector::Stripe, enums::Connector::Bankofamerica, enums::Connector::Cybersource, enums::Connector::Wellsfargo, ]), }, ), ( enums::PaymentMethodType::Debit, SupportedConnectorsForMandate { connector_list: HashSet::from([ enums::Connector::Aci, enums::Connector::Adyen, enums::Connector::Authorizedotnet, enums::Connector::Globalpay, enums::Connector::Worldpay, enums::Connector::Fiuu, enums::Connector::Multisafepay, enums::Connector::Nexinets, enums::Connector::Noon, enums::Connector::Novalnet, enums::Connector::Payme, enums::Connector::Stripe, ]), }, ), ])), ), ])), update_mandate_supported: SupportedPaymentMethodsForMandate(HashMap::default()), } } } #[cfg(feature = "v1")] impl Default for settings::RequiredFields { fn default() -> Self { Self(HashMap::from([ ( enums::PaymentMethod::Card, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::Debit, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Aci, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), } ), ( enums::Connector::Airwallex, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Authorizedotnet, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Bambora, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Bankofamerica, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ] ), } ), ( enums::Connector::Billwerk, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Bluesnap, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Boku, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Braintree, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Checkout, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Coinbase, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Cybersource, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common:HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ) ] ), } ), ( enums::Connector::Datatrans, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), } ), ( enums::Connector::Deutschebank, RequiredFieldFinal { mandate: HashMap::new(), non_mandate : HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "first_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "last_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Dlocal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ) ] ), common:HashMap::new(), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector1, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector2, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector3, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector4, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector5, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector6, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector7, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Elavon, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Fiserv, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Fiuu, RequiredFieldFinal { mandate: HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ]), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Forte, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), common:HashMap::new(), } ), ( enums::Connector::Globalpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ]), } ), ( enums::Connector::Hipay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), } ), ( enums::Connector::Helcim, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Iatapay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Mollie, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Moneris, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Multisafepay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate:HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line2".to_string(), display_name: "line2".to_string(), field_type: enums::FieldType::UserAddressLine2, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ) ] ), } ), ( enums::Connector::Nexinets, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Nexixpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "first_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "last_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ] ), } ), ( enums::Connector::Nmi, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "billing_zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Noon, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), } ), ( enums::Connector::Novalnet, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "first_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "last_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email_address".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ] ), } ), ( enums::Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Paybox, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ) ] ), } ), ( enums::Connector::Payme, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), } ), ( enums::Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Payu, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Powertranz, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Rapyd, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Redsys, RequiredFieldFinal { mandate: HashMap::new(), common: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Shift4, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Square, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Stax, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common:HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ] ), common: HashMap::new() } ), ( enums::Connector::Tsys, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new() } ), ( enums::Connector::Wellsfargo, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common:HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ) ] ), } ), ( enums::Connector::Worldline, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ) ]), common: HashMap::new(), } ), ( enums::Connector::Worldpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: { let mut pmd_fields = HashMap::from([ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ) ]); pmd_fields.extend(get_worldpay_billing_required_fields()); pmd_fields }, } ), ( enums::Connector::Xendit, RequiredFieldFinal { mandate: HashMap::new(), non_mandate:HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ) ] ), } ), ( enums::Connector::Zen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ]), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Credit, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Aci, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), } ), ( enums::Connector::Airwallex, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Authorizedotnet, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Bambora, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Bankofamerica, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ] ), } ), ( enums::Connector::Billwerk, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Bluesnap, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Boku, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Braintree, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Checkout, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Coinbase, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Cybersource, RequiredFieldFinal { mandate: HashMap::new(), non_mandate:HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ) ] ), } ), ( enums::Connector::Datatrans, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), } ), ( enums::Connector::Deutschebank, RequiredFieldFinal { mandate: HashMap::new(), non_mandate : HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "first_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "last_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Dlocal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ) ] ), common:HashMap::new(), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector1, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector2, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector3, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector4, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector5, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector6, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), #[cfg(feature = "dummy_connector")] ( enums::Connector::DummyConnector7, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Elavon, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Fiserv, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Fiuu, RequiredFieldFinal { mandate: HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ]), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Forte, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), common:HashMap::new(), } ), ( enums::Connector::Getnet, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "payment_method_data.card.card_network".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_network".to_string(), display_name: "card_network".to_string(), field_type: enums::FieldType::UserCardNetwork, value: None, } ), ] ), } ), ( enums::Connector::Globalpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ]), } ), ( enums::Connector::Hipay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), } ), ( enums::Connector::Helcim, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Iatapay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Mollie, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Moneris, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Multisafepay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate:HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line2".to_string(), display_name: "line2".to_string(), field_type: enums::FieldType::UserAddressLine2, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ) ] ), } ), ( enums::Connector::Nexinets, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Nexixpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "first_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "last_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ] ), } ), ( enums::Connector::Nmi, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "billing_zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Noon, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), } ), ( enums::Connector::Novalnet, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "first_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "last_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email_address".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ] ), } ), ( enums::Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ),( enums::Connector::Paybox, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ) ] ), } ), ( enums::Connector::Payme, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), } ), ( enums::Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Payu, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Powertranz, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Rapyd, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Redsys, RequiredFieldFinal { mandate: HashMap::new(), common: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Shift4, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new(), } ), ( enums::Connector::Square, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Stax, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), common: HashMap::new(), } ), ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common:HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), } ), ( enums::Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ] ), common: HashMap::new() } ), ( enums::Connector::Tsys, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ) ] ), common: HashMap::new() } ), ( enums::Connector::Wellsfargo, RequiredFieldFinal { mandate: HashMap::new(), non_mandate:HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ) ] ), } ), ( enums::Connector::Worldline, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ) ]), common: HashMap::new(), } ), ( enums::Connector::Worldpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: { let mut pmd_fields = HashMap::from([ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ) ]); pmd_fields.extend(get_worldpay_billing_required_fields()); pmd_fields }, } ), ( enums::Connector::Xendit, RequiredFieldFinal { mandate: HashMap::new(), non_mandate:HashMap::new(), common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "payment_method_data.card.card_cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_cvc".to_string(), display_name: "card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ) ] ), } ), ( enums::Connector::Zen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "payment_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ]), common: HashMap::new(), } ), ]), }, ), ])), ), ( enums::PaymentMethod::BankRedirect, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::OpenBankingUk, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Volt, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ]), common: HashMap::new(), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap:: from([ ( "payment_method_data.bank_redirect.open_banking_uk.issuer".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.open_banking_uk.issuer".to_string(), display_name: "issuer".to_string(), field_type: enums::FieldType::UserBank, value: None, } ) ]), common: HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::Trustly, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::OnlineBankingCzechRepublic, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "payment_method_data.bank_redirect.open_banking_czech_republic.issuer".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.open_banking_czech_republic.issuer".to_string(), display_name: "issuer".to_string(), field_type: enums::FieldType::UserBank, value: None, } ) ]), common: HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::OnlineBankingFinland, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ]), common: HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::OnlineBankingPoland, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "payment_method_data.bank_redirect.open_banking_poland.issuer".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.open_banking_poland.issuer".to_string(), display_name: "issuer".to_string(), field_type: enums::FieldType::UserBank, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ]), common: HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::OnlineBankingSlovakia, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "payment_method_data.bank_redirect.open_banking_slovakia.issuer".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.open_banking_slovakia.issuer".to_string(), display_name: "issuer".to_string(), field_type: enums::FieldType::UserBank, value: None, } ), ]), common: HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::OnlineBankingFpx, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "payment_method_data.bank_redirect.open_banking_fpx.issuer".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.open_banking_fpx.issuer".to_string(), display_name: "issuer".to_string(), field_type: enums::FieldType::UserBank, value: None, } ) ]), common: HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::OnlineBankingThailand, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "payment_method_data.bank_redirect.open_banking_thailand.issuer".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.open_banking_thailand.issuer".to_string(), display_name: "issuer".to_string(), field_type: enums::FieldType::UserBank, value: None, } ) ]), common: HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::Bizum, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::Przelewy24, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ) ]), common: HashMap::new(), } )]), }, ), ( enums::PaymentMethodType::BancontactCard, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Mollie, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ) ]), non_mandate: HashMap::new(), common: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ]), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "payment_method_data.bank_redirect.bancontact_card.card_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.bancontact_card.card_number".to_string(), display_name: "card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.bank_redirect.bancontact_card.card_exp_month".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.bancontact_card.card_exp_month".to_string(), display_name: "card_exp_month".to_string(), field_type: enums::FieldType::UserCardExpiryMonth, value: None, } ), ( "payment_method_data.bank_redirect.bancontact_card.card_exp_year".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.bancontact_card.card_exp_year".to_string(), display_name: "card_exp_year".to_string(), field_type: enums::FieldType::UserCardExpiryYear, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ]), } ) ]), }, ), ( enums::PaymentMethodType::Giropay, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Aci, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserCountry { options: vec![ "DE".to_string(), ]}, value: None, } ) ]), common: HashMap::new(), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Globalpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ("billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry { options: vec![ "DE".to_string(), ] }, value: None, } ) ]), } ), ( enums::Connector::Mollie, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate:HashMap::from([ ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "DE".to_string(), ] }, value: None, } )] ), common: HashMap::new(), } ), ( enums::Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserCountry { options: vec![ "DE".to_string(), ] }, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ) ]), common: HashMap::new(), } ), ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ) ]), common: HashMap::new(), } ), ( enums::Connector::Shift4, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry { options: vec![ "DE".to_string(), ] }, value: None, } ), ]), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Ideal, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Aci, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "payment_method_data.bank_redirect.ideal.bank_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.ideal.bank_name".to_string(), display_name: "bank_name".to_string(), field_type: enums::FieldType::UserBank, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserCountry { options: vec![ "NL".to_string(), ] }, value: None, } ) ]), common: HashMap::new(), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "payment_method_data.bank_redirect.ideal.bank_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.ideal.bank_name".to_string(), display_name: "bank_name".to_string(), field_type: enums::FieldType::UserBank, value: None, } ), ]), } ), ( enums::Connector::Globalpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Mollie, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Nexinets, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "NL".to_string(), ] }, value: None, } ) ]), common: HashMap::new(), } ), ( enums::Connector::Shift4, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserCountry{ options: vec![ "NL".to_string(), ] }, value: None, } ) ]), common: HashMap::new(), } ), ( enums::Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserCountry{ options: vec![ "NL".to_string(), ] }, value: None, } ) ]), common: HashMap::new(), } ), ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "billing_email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ) ]), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "NL".to_string(), ] }, value: None, } ), ]), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Sofort, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Aci, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ("billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserCountry { options: vec![ "ES".to_string(), "GB".to_string(), "SE".to_string(), "AT".to_string(), "NL".to_string(), "DE".to_string(), "CH".to_string(), "BE".to_string(), "FR".to_string(), "FI".to_string(), "IT".to_string(), "PL".to_string(), ] }, value: None, } ) ]), common: HashMap::new(), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Globalpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ("billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry { options: vec![ "AT".to_string(), "BE".to_string(), "DE".to_string(), "ES".to_string(), "IT".to_string(), "NL".to_string(), ] }, value: None, } ) ]), } ), ( enums::Connector::Mollie, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Nexinets, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate:HashMap::from([ ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ES".to_string(), "GB".to_string(), "IT".to_string(), "DE".to_string(), "FR".to_string(), "AT".to_string(), "BE".to_string(), "NL".to_string(), "BE".to_string(), "SK".to_string(), ] }, value: None, } )] ), common: HashMap::new(), } ), ( enums::Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserCountry { options: vec![ "ES".to_string(), "GB".to_string(), "AT".to_string(), "NL".to_string(), "DE".to_string(), "BE".to_string(), ] }, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ) ]), common: HashMap::new(), } ), ( enums::Connector::Shift4, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ) ]), non_mandate : HashMap::new(), common: HashMap::from([ ("billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserCountry { options: vec![ "ES".to_string(), "AT".to_string(), "NL".to_string(), "DE".to_string(), "BE".to_string(), ] }, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "account_holder_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "account_holder_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } )]), } ), ( enums::Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry { options: vec![ "ES".to_string(), "GB".to_string(), "SE".to_string(), "AT".to_string(), "NL".to_string(), "DE".to_string(), "CH".to_string(), "BE".to_string(), "FR".to_string(), "FI".to_string(), "IT".to_string(), "PL".to_string(), ] }, value: None, } ), ]), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Eps, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "payment_method_data.bank_redirect.eps.bank_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.eps.bank_name".to_string(), display_name: "bank_name".to_string(), field_type: enums::FieldType::UserBank, value: None, } ) ]), } ), ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ]), common: HashMap::new(), } ), ( enums::Connector::Aci, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "bank_account_country".to_string(), field_type: enums::FieldType::UserCountry { options: vec![ "AT".to_string(), ] }, value: None, } ) ]), common: HashMap::new(), } ), ( enums::Connector::Globalpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry { options: vec![ "AT".to_string(), ] }, value: None, } ) ]) } ), ( enums::Connector::Mollie, RequiredFieldFinal { mandate: HashMap::new(), non_mandate:HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "bank_account_country".to_string(), field_type: enums::FieldType::UserCountry { options: vec![ "AT".to_string(), ] }, value: None, } ) ]), common: HashMap::new(), } ), ( enums::Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "AT".to_string(), ] }, value: None, } ), ]), common: HashMap::new(), } ), ( enums::Connector::Shift4, RequiredFieldFinal { mandate: HashMap::new(), non_mandate:HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "AT".to_string(), ] }, value: None, } )] ), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Blik, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "payment_method_data.bank_redirect.blik.blik_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.blik.blik_code".to_string(), display_name: "blik_code".to_string(), field_type: enums::FieldType::UserBlikCode, value: None, } ) ]), } ), ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "payment_method_data.bank_redirect.blik.blik_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.blik.blik_code".to_string(), display_name: "blik_code".to_string(), field_type: enums::FieldType::UserBlikCode, value: None, } ) ]), } ), ( enums::Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ]), } ) ]), }, ), ])), ), ( enums::PaymentMethod::Wallet, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::ApplePay, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Bankofamerica, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ) ] ), } ), ( enums::Connector::Cybersource, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ) ] ), } ), ( enums::Connector::Novalnet, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email_address".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ] ), } ), ( enums::Connector::Wellsfargo, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "shipping.address.first_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.first_name".to_string(), display_name: "shipping_first_name".to_string(), field_type: enums::FieldType::UserShippingName, value: None, } ), ( "shipping.address.last_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.last_name".to_string(), display_name: "shipping_last_name".to_string(), field_type: enums::FieldType::UserShippingName, value: None, } ), ( "shipping.address.city".to_string(), RequiredFieldInfo { required_field: "shipping.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserShippingAddressCity, value: None, } ), ( "shipping.address.state".to_string(), RequiredFieldInfo { required_field: "shipping.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserShippingAddressState, value: None, } ), ( "shipping.address.zip".to_string(), RequiredFieldInfo { required_field: "shipping.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserShippingAddressPincode, value: None, } ), ( "shipping.address.country".to_string(), RequiredFieldInfo { required_field: "shipping.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserShippingAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "shipping.address.line1".to_string(), RequiredFieldInfo { required_field: "shipping.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserShippingAddressLine1, value: None, } ), ] ), } ), ]), }, ), ( enums::PaymentMethodType::SamsungPay, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Cybersource, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ) ] ), } ), ]), }, ), ( enums::PaymentMethodType::GooglePay, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Bankofamerica, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ) ] ), } ), ( enums::Connector::Bluesnap, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Noon, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Novalnet, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email_address".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ] ), } ), ( enums::Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Airwallex, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Authorizedotnet, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Checkout, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Globalpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Multisafepay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line2".to_string(), display_name: "line2".to_string(), field_type: enums::FieldType::UserAddressLine2, value: None, } )] ), } ), ( enums::Connector::Cybersource, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ) ] ), } ), ( enums::Connector::Payu, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Rapyd, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Wellsfargo, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "shipping.address.first_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.first_name".to_string(), display_name: "shipping_first_name".to_string(), field_type: enums::FieldType::UserShippingName, value: None, } ), ( "shipping.address.last_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.last_name".to_string(), display_name: "shipping_last_name".to_string(), field_type: enums::FieldType::UserShippingName, value: None, } ), ( "shipping.address.city".to_string(), RequiredFieldInfo { required_field: "shipping.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserShippingAddressCity, value: None, } ), ( "shipping.address.state".to_string(), RequiredFieldInfo { required_field: "shipping.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserShippingAddressState, value: None, } ), ( "shipping.address.zip".to_string(), RequiredFieldInfo { required_field: "shipping.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserShippingAddressPincode, value: None, } ), ( "shipping.address.country".to_string(), RequiredFieldInfo { required_field: "shipping.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserShippingAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "shipping.address.line1".to_string(), RequiredFieldInfo { required_field: "shipping.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserShippingAddressLine1, value: None, } ), ] ), } ), ]), }, ), ( enums::PaymentMethodType::WeChatPay, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::AliPay, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::AliPayHk, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::AmazonPay, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Cashapp, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::MbWay, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), common: HashMap::new(), non_mandate: HashMap::from([ ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ] ), } ), ]), }, ), ( enums::PaymentMethodType::KakaoPay, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Twint, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Gcash, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Vipps, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Dana, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Momo, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Swish, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::TouchNGo, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ), ( // Added shipping fields for the SDK flow to accept it from wallet directly, // this won't show up in SDK in payment's sheet but will be used in the background enums::PaymentMethodType::Paypal, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } )] ), } ), ( enums::Connector::Braintree, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Novalnet, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email_address".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ] ), } ), ( enums::Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new( ), common: HashMap::from( [ ( "shipping.address.first_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.first_name".to_string(), display_name: "shipping_first_name".to_string(), field_type: enums::FieldType::UserShippingName, value: None, } ), ( "shipping.address.last_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.last_name".to_string(), display_name: "shipping_last_name".to_string(), field_type: enums::FieldType::UserShippingName, value: None, } ), ( "shipping.address.city".to_string(), RequiredFieldInfo { required_field: "shipping.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserShippingAddressCity, value: None, } ), ( "shipping.address.state".to_string(), RequiredFieldInfo { required_field: "shipping.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserShippingAddressState, value: None, } ), ( "shipping.address.zip".to_string(), RequiredFieldInfo { required_field: "shipping.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserShippingAddressPincode, value: None, } ), ( "shipping.address.country".to_string(), RequiredFieldInfo { required_field: "shipping.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserShippingAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "shipping.address.line1".to_string(), RequiredFieldInfo { required_field: "shipping.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserShippingAddressLine1, value: None, } ), ] ), } ), ]), }, ), ( enums::PaymentMethodType::Mifinity, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Mifinity, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "payment_method_data.wallet.mifinity.date_of_birth".to_string(), RequiredFieldInfo { required_field: "payment_method_data.wallet.mifinity.date_of_birth".to_string(), display_name: "date_of_birth".to_string(), field_type: enums::FieldType::UserDateOfBirth, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "first_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "last_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "nationality".to_string(), field_type: enums::FieldType::UserCountry{ options: vec![ "BR".to_string(), "CN".to_string(), "SG".to_string(), "MY".to_string(), "DE".to_string(), "CH".to_string(), "DK".to_string(), "GB".to_string(), "ES".to_string(), "AD".to_string(), "GI".to_string(), "FI".to_string(), "FR".to_string(), "GR".to_string(), "HR".to_string(), "IT".to_string(), "JP".to_string(), "MX".to_string(), "AR".to_string(), "CO".to_string(), "CL".to_string(), "PE".to_string(), "VE".to_string(), "UY".to_string(), "PY".to_string(), "BO".to_string(), "EC".to_string(), "GT".to_string(), "HN".to_string(), "SV".to_string(), "NI".to_string(), "CR".to_string(), "PA".to_string(), "DO".to_string(), "CU".to_string(), "PR".to_string(), "NL".to_string(), "NO".to_string(), "PL".to_string(), "PT".to_string(), "SE".to_string(), "RU".to_string(), "TR".to_string(), "TW".to_string(), "HK".to_string(), "MO".to_string(), "AX".to_string(), "AL".to_string(), "DZ".to_string(), "AS".to_string(), "AO".to_string(), "AI".to_string(), "AG".to_string(), "AM".to_string(), "AW".to_string(), "AU".to_string(), "AT".to_string(), "AZ".to_string(), "BS".to_string(), "BH".to_string(), "BD".to_string(), "BB".to_string(), "BE".to_string(), "BZ".to_string(), "BJ".to_string(), "BM".to_string(), "BT".to_string(), "BQ".to_string(), "BA".to_string(), "BW".to_string(), "IO".to_string(), "BN".to_string(), "BG".to_string(), "BF".to_string(), "BI".to_string(), "KH".to_string(), "CM".to_string(), "CA".to_string(), "CV".to_string(), "KY".to_string(), "CF".to_string(), "TD".to_string(), "CX".to_string(), "CC".to_string(), "KM".to_string(), "CG".to_string(), "CK".to_string(), "CI".to_string(), "CW".to_string(), "CY".to_string(), "CZ".to_string(), "DJ".to_string(), "DM".to_string(), "EG".to_string(), "GQ".to_string(), "ER".to_string(), "EE".to_string(), "ET".to_string(), "FK".to_string(), "FO".to_string(), "FJ".to_string(), "GF".to_string(), "PF".to_string(), "TF".to_string(), "GA".to_string(), "GM".to_string(), "GE".to_string(), "GH".to_string(), "GL".to_string(), "GD".to_string(), "GP".to_string(), "GU".to_string(), "GG".to_string(), "GN".to_string(), "GW".to_string(), "GY".to_string(), "HT".to_string(), "HM".to_string(), "VA".to_string(), "IS".to_string(), "IN".to_string(), "ID".to_string(), "IE".to_string(), "IM".to_string(), "IL".to_string(), "JE".to_string(), "JO".to_string(), "KZ".to_string(), "KE".to_string(), "KI".to_string(), "KW".to_string(), "KG".to_string(), "LA".to_string(), "LV".to_string(), "LB".to_string(), "LS".to_string(), "LI".to_string(), "LT".to_string(), "LU".to_string(), "MK".to_string(), "MG".to_string(), "MW".to_string(), "MV".to_string(), "ML".to_string(), "MT".to_string(), "MH".to_string(), "MQ".to_string(), "MR".to_string(), "MU".to_string(), "YT".to_string(), "FM".to_string(), "MD".to_string(), "MC".to_string(), "MN".to_string(), "ME".to_string(), "MS".to_string(), "MA".to_string(), "MZ".to_string(), "NA".to_string(), "NR".to_string(), "NP".to_string(), "NC".to_string(), "NZ".to_string(), "NE".to_string(), "NG".to_string(), "NU".to_string(), "NF".to_string(), "MP".to_string(), "OM".to_string(), "PK".to_string(), "PW".to_string(), "PS".to_string(), "PG".to_string(), "PH".to_string(), "PN".to_string(), "QA".to_string(), "RE".to_string(), "RO".to_string(), "RW".to_string(), "BL".to_string(), "SH".to_string(), "KN".to_string(), "LC".to_string(), "MF".to_string(), "PM".to_string(), "VC".to_string(), "WS".to_string(), "SM".to_string(), "ST".to_string(), "SA".to_string(), "SN".to_string(), "RS".to_string(), "SC".to_string(), "SL".to_string(), "SX".to_string(), "SK".to_string(), "SI".to_string(), "SB".to_string(), "SO".to_string(), "ZA".to_string(), "GS".to_string(), "KR".to_string(), "LK".to_string(), "SR".to_string(), "SJ".to_string(), "SZ".to_string(), "TH".to_string(), "TL".to_string(), "TG".to_string(), "TK".to_string(), "TO".to_string(), "TT".to_string(), "TN".to_string(), "TM".to_string(), "TC".to_string(), "TV".to_string(), "UG".to_string(), "UA".to_string(), "AE".to_string(), "UZ".to_string(), "VU".to_string(), "VN".to_string(), "VG".to_string(), "VI".to_string(), "WF".to_string(), "EH".to_string(), "ZM".to_string(), ] }, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email_address".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "payment_method_data.wallet.mifinity.language_preference".to_string(), RequiredFieldInfo { required_field: "payment_method_data.wallet.mifinity.language_preference".to_string(), display_name: "language_preference".to_string(), field_type: enums::FieldType::LanguagePreference{ options: vec![ "BR".to_string(), "PT_BR".to_string(), "CN".to_string(), "ZH_CN".to_string(), "DE".to_string(), "DK".to_string(), "DA".to_string(), "DA_DK".to_string(), "EN".to_string(), "ES".to_string(), "FI".to_string(), "FR".to_string(), "GR".to_string(), "EL".to_string(), "EL_GR".to_string(), "HR".to_string(), "IT".to_string(), "JP".to_string(), "JA".to_string(), "JA_JP".to_string(), "LA".to_string(), "ES_LA".to_string(), "NL".to_string(), "NO".to_string(), "PL".to_string(), "PT".to_string(), "RU".to_string(), "SV".to_string(), "SE".to_string(), "SV_SE".to_string(), "ZH".to_string(), "TW".to_string(), "ZH_TW".to_string(), ] }, value: None, } ), ]), } ), ]), } ), ])), ), ( enums::PaymentMethod::PayLater, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::AfterpayClearpay, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate : HashMap::new(), non_mandate: HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "GB".to_string(), "AU".to_string(), "CA".to_string(), "US".to_string(), "NZ".to_string(), ] }, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "shipping.address.first_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.first_name".to_string(), display_name: "shipping_first_name".to_string(), field_type: enums::FieldType::UserShippingName, value: None, } ), ( "shipping.address.last_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.last_name".to_string(), display_name: "shipping_last_name".to_string(), field_type: enums::FieldType::UserShippingName, value: None, } ), ( "shipping.address.city".to_string(), RequiredFieldInfo { required_field: "shipping.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserShippingAddressCity, value: None, } ), ( "shipping.address.state".to_string(), RequiredFieldInfo { required_field: "shipping.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserShippingAddressState, value: None, } ), ( "shipping.address.zip".to_string(), RequiredFieldInfo { required_field: "shipping.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserShippingAddressPincode, value: None, } ), ( "shipping.address.country".to_string(), RequiredFieldInfo { required_field: "shipping.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserShippingAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "shipping.address.line1".to_string(), RequiredFieldInfo { required_field: "shipping.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserShippingAddressLine1, value: None, } ), ]), common : HashMap::new(), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate: HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line2".to_string(), display_name: "line2".to_string(), field_type: enums::FieldType::UserAddressLine2, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "GB".to_string(), "AU".to_string(), "CA".to_string(), "US".to_string(), "NZ".to_string(), ] }, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "shipping.address.city".to_string(), RequiredFieldInfo { required_field: "shipping.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserShippingAddressCity, value: None, } ), ( "shipping.address.zip".to_string(), RequiredFieldInfo { required_field: "shipping.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserShippingAddressPincode, value: None, } ), ( "shipping.address.country".to_string(), RequiredFieldInfo { required_field: "shipping.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserShippingAddressCountry{ options: vec![ "GB".to_string(), "AU".to_string(), "CA".to_string(), "US".to_string(), "NZ".to_string(), ] }, value: None, } ), ( "shipping.address.line1".to_string(), RequiredFieldInfo { required_field: "shipping.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserShippingAddressLine1, value: None, } ), ( "shipping.address.line2".to_string(), RequiredFieldInfo { required_field: "shipping.address.line2".to_string(), display_name: "line2".to_string(), field_type: enums::FieldType::UserShippingAddressLine2, value: None, } ), ]), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::Klarna, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate : HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "billing_country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "AU".to_string(), "AT".to_string(), "BE".to_string(), "CA".to_string(), "CZ".to_string(), "DK".to_string(), "FI".to_string(), "FR".to_string(), "GR".to_string(), "DE".to_string(), "IE".to_string(), "IT".to_string(), "NL".to_string(), "NZ".to_string(), "NO".to_string(), "PL".to_string(), "PT".to_string(), "RO".to_string(), "ES".to_string(), "SE".to_string(), "CH".to_string(), "GB".to_string(), "US".to_string(), ] }, value: None, }), ("billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, }) ]), common : HashMap::new(), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate: HashMap::new(), common : HashMap::from([ ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "billing_country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, }), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ]), } ), ( enums::Connector::Klarna, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "AU".to_string(), "AT".to_string(), "BE".to_string(), "CA".to_string(), "CZ".to_string(), "DK".to_string(), "FI".to_string(), "FR".to_string(), "DE".to_string(), "GR".to_string(), "IE".to_string(), "IT".to_string(), "NL".to_string(), "NZ".to_string(), "NO".to_string(), "PL".to_string(), "PT".to_string(), "ES".to_string(), "SE".to_string(), "CH".to_string(), "GB".to_string(), "US".to_string(), ] }, value: None, } ) ]), } ) ]), }, ), ( enums::PaymentMethodType::Affirm, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "US".to_string(), ] }, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line2".to_string(), display_name: "line2".to_string(), field_type: enums::FieldType::UserAddressLine2, value: None, } ), ( "shipping.address.line1".to_string(), RequiredFieldInfo { required_field: "shipping.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "shipping.address.line2".to_string(), RequiredFieldInfo { required_field: "shipping.address.line2".to_string(), display_name: "line2".to_string(), field_type: enums::FieldType::UserAddressLine2, value: None, } ), ( "shipping.address.zip".to_string(), RequiredFieldInfo { required_field: "shipping.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserShippingAddressPincode, value: None, } ), ( "shipping.address.city".to_string(), RequiredFieldInfo { required_field: "shipping.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserShippingAddressCity, value: None, } ), ( "shipping.address.country".to_string(), RequiredFieldInfo { required_field: "shipping.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserCountry { options: vec![ "US".to_string(), ]}, value: None, } ), ] ), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::PayBright, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "CA".to_string(), ] }, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line2".to_string(), display_name: "line2".to_string(), field_type: enums::FieldType::UserAddressLine2, value: None, } ), ( "shipping.address.city".to_string(), RequiredFieldInfo { required_field: "shipping.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserShippingAddressCity, value: None, } ), ( "shipping.address.zip".to_string(), RequiredFieldInfo { required_field: "shipping.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserShippingAddressPincode, value: None, } ), ( "shipping.address.country".to_string(), RequiredFieldInfo { required_field: "shipping.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserShippingAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ( "shipping.address.line1".to_string(), RequiredFieldInfo { required_field: "shipping.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserShippingAddressLine1, value: None, } ), ( "shipping.address.line2".to_string(), RequiredFieldInfo { required_field: "shipping.address.line2".to_string(), display_name: "line2".to_string(), field_type: enums::FieldType::UserShippingAddressLine2, value: None, } ), ] ), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Walley, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "DK".to_string(), "FI".to_string(), "NO".to_string(), "SE".to_string(), ]}, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ] ), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Alma, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "FR".to_string(), ] }, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line2".to_string(), display_name: "line2".to_string(), field_type: enums::FieldType::UserAddressLine2, value: None, } ) ] ), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Atome, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "MY".to_string(), "SG".to_string() ] }, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line2".to_string(), display_name: "line2".to_string(), field_type: enums::FieldType::UserAddressLine2, value: None, } ) ] ), common: HashMap::new(), } ), ]), }, ), ])), ), ( enums::PaymentMethod::Crypto, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::CryptoCurrency, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Cryptopay, RequiredFieldFinal { mandate : HashMap::new(), non_mandate: HashMap::from([ ( "payment_method_data.crypto.pay_currency".to_string(), RequiredFieldInfo { required_field: "payment_method_data.crypto.pay_currency".to_string(), display_name: "currency".to_string(), field_type: enums::FieldType::UserCurrency{ options: vec![ "BTC".to_string(), "LTC".to_string(), "ETH".to_string(), "XRP".to_string(), "XLM".to_string(), "BCH".to_string(), "ADA".to_string(), "SOL".to_string(), "SHIB".to_string(), "TRX".to_string(), "DOGE".to_string(), "BNB".to_string(), "USDT".to_string(), "USDC".to_string(), "DAI".to_string(), ] }, value: None, } ), ( "payment_method_data.crypto.network".to_string(), RequiredFieldInfo { required_field: "payment_method_data.crypto.network".to_string(), display_name: "network".to_string(), field_type: enums::FieldType::UserCryptoCurrencyNetwork, value: None, } ), ]), common : HashMap::new(), } ), ]), }, ), ])), ), ( enums::PaymentMethod::Voucher, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::Boleto, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "payment_method_data.voucher.boleto.social_security_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.voucher.boleto.social_security_number".to_string(), display_name: "social_security_number".to_string(), field_type: enums::FieldType::UserSocialSecurityNumber, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: enums::FieldType::UserAddressState, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "BR".to_string(), ] }, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line2".to_string(), display_name: "line2".to_string(), field_type: enums::FieldType::UserAddressLine2, value: None, } ), ]), common : HashMap::new(), } ), ( enums::Connector::Zen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::Alfamart, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ]), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::Indomaret, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ]), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::Oxxo, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::new(), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::SevenEleven, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ) ] ), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::Lawson, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ] ), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::MiniStop, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ] ), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::FamilyMart, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ] ), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::Seicomart, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ] ), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::PayEasy, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ] ), common : HashMap::new(), } ) ]), }, ), ])), ), ( enums::PaymentMethod::Upi, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::UpiCollect, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Razorpay, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::new(), common : HashMap::from([ ( "payment_method_data.upi.upi_collect.vpa_id".to_string(), RequiredFieldInfo { required_field: "payment_method_data.upi.upi_collect.vpa_id".to_string(), display_name: "vpa_id".to_string(), field_type: enums::FieldType::UserVpaId, value: None, } ), ]), } ), ]), }, ), ])), ), ( enums::PaymentMethod::BankDebit, PaymentMethodType(HashMap::from([( enums::PaymentMethodType::Ach, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "owner_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "payment_method_data.bank_debit.ach_bank_debit.account_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.ach_bank_debit.account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: enums::FieldType::UserBankAccountNumber, value: None, } ), ( "payment_method_data.bank_debit.ach_bank_debit.routing_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.ach_bank_debit.routing_number".to_string(), display_name: "bank_routing_number".to_string(), field_type: enums::FieldType::UserBankRoutingNumber, value: None, } ) ]), }), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "owner_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, }), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "owner_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "payment_method_data.bank_debit.ach_bank_debit.account_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.ach_bank_debit.account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: enums::FieldType::UserBankAccountNumber, value: None, } ), ( "payment_method_data.bank_debit.ach_bank_debit.routing_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.ach_bank_debit.routing_number".to_string(), display_name: "bank_routing_number".to_string(), field_type: enums::FieldType::UserBankRoutingNumber, value: None, } ) ]), }) ] )} ), ( enums::PaymentMethodType::Sepa, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "owner_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(), display_name: "iban".to_string(), field_type: enums::FieldType::UserIban, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ) ]), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "owner_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, }), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "owner_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(), display_name: "iban".to_string(), field_type: enums::FieldType::UserIban, value: None, } ) ]), } ), ( enums::Connector::Deutschebank, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "owner_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, }), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "owner_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(), display_name: "iban".to_string(), field_type: enums::FieldType::UserIban, value: None, } ) ]), } ), ( enums::Connector::Inespay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.sepa_bank_debit.iban".to_string(), display_name: "iban".to_string(), field_type: enums::FieldType::UserIban, value: None, } ) ]), } ) ]), }, ), ( enums::PaymentMethodType::Bacs, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "payment_method_data.bank_debit.bacs_bank_debit.account_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.bacs_bank_debit.account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: enums::FieldType::UserBankAccountNumber, value: None, } ), ( "payment_method_data.bank_debit.bacs_bank_debit.sort_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.bacs_bank_debit.sort_code".to_string(), display_name: "bank_sort_code".to_string(), field_type: enums::FieldType::UserBankSortCode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry { options: vec!["UK".to_string()], }, value: None, }, ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, }, ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, }, ) ]), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "owner_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, }), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "owner_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "payment_method_data.bank_debit.bacs_bank_debit.account_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.bacs_bank_debit.account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: enums::FieldType::UserBankAccountNumber, value: None, } ), ( "payment_method_data.bank_debit.bacs_bank_debit.sort_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.bacs_bank_debit.sort_code".to_string(), display_name: "bank_sort_code".to_string(), field_type: enums::FieldType::UserBankSortCode, value: None, } ) ]), }) ]), }, ), ( enums::PaymentMethodType::Becs, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "owner_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "payment_method_data.bank_debit.becs_bank_debit.account_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.becs_bank_debit.account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: enums::FieldType::UserBankAccountNumber, value: None, } ), ( "payment_method_data.bank_debit.becs_bank_debit.bsb_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.becs_bank_debit.bsb_number".to_string(), display_name: "bsb_number".to_string(), field_type: enums::FieldType::UserBsbNumber, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ) ]), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "owner_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, }), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "owner_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "payment_method_data.bank_debit.becs_bank_debit.account_number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.becs_bank_debit.account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: enums::FieldType::UserBankAccountNumber, value: None, } ), ( "payment_method_data.bank_debit.becs_bank_debit.sort_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.becs_bank_debit.sort_code".to_string(), display_name: "bank_sort_code".to_string(), field_type: enums::FieldType::UserBankSortCode, value: None, } ) ]), }) ]), }, ), ]))), ( enums::PaymentMethod::BankTransfer, PaymentMethodType(HashMap::from([( enums::PaymentMethodType::Multibanco, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ) ]), common: HashMap::new(), } ), ])}), (enums::PaymentMethodType::LocalBankTransfer, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Zsl, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "CN".to_string(), ] }, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, }, ), ]), common: HashMap::new(), } ), ])}), (enums::PaymentMethodType::Ach, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ) ]) } ), ])}), (enums::PaymentMethodType::Pix, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Itaubank, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.bank_transfer.pix.pix_key".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_transfer.pix.pix_key".to_string(), display_name: "pix_key".to_string(), field_type: enums::FieldType::UserPixKey, value: None, } ), ( "payment_method_data.bank_transfer.pix.cnpj".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_transfer.pix.cnpj".to_string(), display_name: "cnpj".to_string(), field_type: enums::FieldType::UserCnpj, value: None, } ), ( "payment_method_data.bank_transfer.pix.cpf".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_transfer.pix.cpf".to_string(), display_name: "cpf".to_string(), field_type: enums::FieldType::UserCpf, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ] ), } ), ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ])}), ( enums::PaymentMethodType::PermataBankTransfer, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ]), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::BcaBankTransfer, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ]), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::BniVa, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ]), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::BriVa, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ]), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::CimbVa, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ]), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::DanamonVa, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ]), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::MandiriVa, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ]), common : HashMap::new(), } ) ]), }, ), ( enums::PaymentMethodType::SepaBankTransfer, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::new(), common : HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry { options: vec![ "BE".to_string(), "DE".to_string(), "ES".to_string(), "FR".to_string(), "IE".to_string(), "NL".to_string(), ], }, value: None, }, ), ]), } ), ( enums::Connector::Trustpay, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::new(), common : HashMap::from([ ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ]), } ) ]), }, ), ( enums::PaymentMethodType::InstantBankTransfer, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Trustpay, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::new(), common : HashMap::from([ ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "billing_first_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "billing_last_name".to_string(), field_type: enums::FieldType::UserBillingName, value: None, } ), ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, } ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, } ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, } ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ "ALL".to_string(), ] }, value: None, } ), ]), } ) ]) } ), ( enums::PaymentMethodType::Bacs, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Stripe, RequiredFieldFinal { mandate : HashMap::new(), non_mandate : HashMap::new(), common : HashMap::from([ ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "card_holder_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ) ]), } ) ]), }, ), ]))), ( enums::PaymentMethod::GiftCard, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::PaySafeCard, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Givex, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ ( "payment_method_data.gift_card.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.gift_card.givex.number".to_string(), display_name: "gift_card_number".to_string(), field_type: enums::FieldType::UserCardNumber, value: None, } ), ( "payment_method_data.gift_card.cvc".to_string(), RequiredFieldInfo { required_field: "payment_method_data.gift_card.givex.cvc".to_string(), display_name: "gift_card_cvc".to_string(), field_type: enums::FieldType::UserCardCvc, value: None, } ), ]), common: HashMap::new(), } ), ]), }, ), ])) ), ( enums::PaymentMethod::CardRedirect, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::Benefit, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "first_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "last_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ) ] ), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::Knet, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from( [( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: "first_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: "last_name".to_string(), field_type: enums::FieldType::UserFullName, value: None, } ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: enums::FieldType::UserPhoneNumber, value: None, } ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: enums::FieldType::UserPhoneNumberCountryCode, value: None, } ), ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: enums::FieldType::UserEmailAddress, value: None, } ) ] ), common: HashMap::new(), } ), ]), }, ), ( enums::PaymentMethodType::MomoAtm, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::new(), } ), ]), }, ) ])) ), ( enums::PaymentMethod::MobilePayment, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::DirectCarrierBilling, ConnectorFields { fields: HashMap::from([ ( enums::Connector::Digitalvirgo, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from( [ ( "payment_method_data.mobile_payment.direct_carrier_billing.msisdn".to_string(), RequiredFieldInfo { required_field: "payment_method_data.mobile_payment.direct_carrier_billing.msisdn".to_string(), display_name: "mobile_number".to_string(), field_type: enums::FieldType::UserMsisdn, value: None, } ), ( "payment_method_data.mobile_payment.direct_carrier_billing.client_uid".to_string(), RequiredFieldInfo { required_field: "payment_method_data.mobile_payment.direct_carrier_billing.client_uid".to_string(), display_name: "client_identifier".to_string(), field_type: enums::FieldType::UserClientIdentifier, value: None, } ), ( "order_details.0.product_name".to_string(), RequiredFieldInfo { required_field: "order_details.0.product_name".to_string(), display_name: "product_name".to_string(), field_type: enums::FieldType::OrderDetailsProductName, value: None, } ), ] ), } ), ]) } ) ])) ) ])) } } pub fn get_worldpay_billing_required_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: enums::FieldType::UserAddressLine1, value: None, }, ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry { options: vec![ "AF".to_string(), "AU".to_string(), "AW".to_string(), "AZ".to_string(), "BS".to_string(), "BH".to_string(), "BD".to_string(), "BB".to_string(), "BZ".to_string(), "BM".to_string(), "BT".to_string(), "BO".to_string(), "BA".to_string(), "BW".to_string(), "BR".to_string(), "BN".to_string(), "BG".to_string(), "BI".to_string(), "KH".to_string(), "CA".to_string(), "CV".to_string(), "KY".to_string(), "CL".to_string(), "CO".to_string(), "KM".to_string(), "CD".to_string(), "CR".to_string(), "CZ".to_string(), "DZ".to_string(), "DK".to_string(), "DJ".to_string(), "ST".to_string(), "DO".to_string(), "EC".to_string(), "EG".to_string(), "SV".to_string(), "ER".to_string(), "ET".to_string(), "FK".to_string(), "FJ".to_string(), "GM".to_string(), "GE".to_string(), "GH".to_string(), "GI".to_string(), "GT".to_string(), "GN".to_string(), "GY".to_string(), "HT".to_string(), "HN".to_string(), "HK".to_string(), "HU".to_string(), "IS".to_string(), "IN".to_string(), "ID".to_string(), "IR".to_string(), "IQ".to_string(), "IE".to_string(), "IL".to_string(), "IT".to_string(), "JM".to_string(), "JP".to_string(), "JO".to_string(), "KZ".to_string(), "KE".to_string(), "KW".to_string(), "LA".to_string(), "LB".to_string(), "LS".to_string(), "LR".to_string(), "LY".to_string(), "LT".to_string(), "MO".to_string(), "MK".to_string(), "MG".to_string(), "MW".to_string(), "MY".to_string(), "MV".to_string(), "MR".to_string(), "MU".to_string(), "MX".to_string(), "MD".to_string(), "MN".to_string(), "MA".to_string(), "MZ".to_string(), "MM".to_string(), "NA".to_string(), "NZ".to_string(), "NI".to_string(), "NG".to_string(), "KP".to_string(), "NO".to_string(), "AR".to_string(), "PK".to_string(), "PG".to_string(), "PY".to_string(), "PE".to_string(), "UY".to_string(), "PH".to_string(), "PL".to_string(), "GB".to_string(), "QA".to_string(), "OM".to_string(), "RO".to_string(), "RU".to_string(), "RW".to_string(), "WS".to_string(), "SG".to_string(), "ST".to_string(), "ZA".to_string(), "KR".to_string(), "LK".to_string(), "SH".to_string(), "SD".to_string(), "SR".to_string(), "SZ".to_string(), "SE".to_string(), "CH".to_string(), "SY".to_string(), "TW".to_string(), "TJ".to_string(), "TZ".to_string(), "TH".to_string(), "TT".to_string(), "TN".to_string(), "TR".to_string(), "UG".to_string(), "UA".to_string(), "US".to_string(), "UZ".to_string(), "VU".to_string(), "VE".to_string(), "VN".to_string(), "ZM".to_string(), "ZW".to_string(), ], }, value: None, }, ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: enums::FieldType::UserAddressCity, value: None, }, ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: enums::FieldType::UserAddressPincode, value: None, }, ), ]) }
95,271
1,490
hyperswitch
crates/router/src/configs/defaults/payout_required_fields.rs
.rs
use std::collections::HashMap; use api_models::{ enums::{ CountryAlpha2, FieldType, PaymentMethod::{BankTransfer, Card, Wallet}, PaymentMethodType, PayoutConnectors, }, payment_methods::RequiredFieldInfo, }; use crate::settings::{ ConnectorFields, PaymentMethodType as PaymentMethodTypeInfo, PayoutRequiredFields, RequiredFieldFinal, }; #[cfg(feature = "v1")] impl Default for PayoutRequiredFields { fn default() -> Self { Self(HashMap::from([ ( Card, PaymentMethodTypeInfo(HashMap::from([ // Adyen get_connector_payment_method_type_fields( PayoutConnectors::Adyenplatform, PaymentMethodType::Debit, ), get_connector_payment_method_type_fields( PayoutConnectors::Adyenplatform, PaymentMethodType::Credit, ), ])), ), ( BankTransfer, PaymentMethodTypeInfo(HashMap::from([ // Adyen get_connector_payment_method_type_fields( PayoutConnectors::Adyenplatform, PaymentMethodType::Sepa, ), // Ebanx get_connector_payment_method_type_fields( PayoutConnectors::Ebanx, PaymentMethodType::Pix, ), // Wise get_connector_payment_method_type_fields( PayoutConnectors::Wise, PaymentMethodType::Bacs, ), ])), ), ( Wallet, PaymentMethodTypeInfo(HashMap::from([ // Adyen get_connector_payment_method_type_fields( PayoutConnectors::Adyenplatform, PaymentMethodType::Paypal, ), ])), ), ])) } } #[cfg(feature = "v1")] fn get_connector_payment_method_type_fields( connector: PayoutConnectors, payment_method_type: PaymentMethodType, ) -> (PaymentMethodType, ConnectorFields) { let mut common_fields = get_billing_details(connector); match payment_method_type { // Card PaymentMethodType::Debit => { common_fields.extend(get_card_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } PaymentMethodType::Credit => { common_fields.extend(get_card_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } // Banks PaymentMethodType::Bacs => { common_fields.extend(get_bacs_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } PaymentMethodType::Pix => { common_fields.extend(get_pix_bank_transfer_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } PaymentMethodType::Sepa => { common_fields.extend(get_sepa_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } // Wallets PaymentMethodType::Paypal => { common_fields.extend(get_paypal_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } _ => ( payment_method_type, ConnectorFields { fields: HashMap::new(), }, ), } } fn get_card_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ ( "payout_method_data.card.card_number".to_string(), RequiredFieldInfo { required_field: "payout_method_data.card.card_number".to_string(), display_name: "card_number".to_string(), field_type: FieldType::UserCardNumber, value: None, }, ), ( "payout_method_data.card.expiry_month".to_string(), RequiredFieldInfo { required_field: "payout_method_data.card.expiry_month".to_string(), display_name: "exp_month".to_string(), field_type: FieldType::UserCardExpiryMonth, value: None, }, ), ( "payout_method_data.card.expiry_year".to_string(), RequiredFieldInfo { required_field: "payout_method_data.card.expiry_year".to_string(), display_name: "exp_year".to_string(), field_type: FieldType::UserCardExpiryYear, value: None, }, ), ( "payout_method_data.card.card_holder_name".to_string(), RequiredFieldInfo { required_field: "payout_method_data.card.card_holder_name".to_string(), display_name: "card_holder_name".to_string(), field_type: FieldType::UserFullName, value: None, }, ), ]) } fn get_bacs_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ ( "payout_method_data.bank.bank_sort_code".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank.bank_sort_code".to_string(), display_name: "bank_sort_code".to_string(), field_type: FieldType::Text, value: None, }, ), ( "payout_method_data.bank.bank_account_number".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank.bank_account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: FieldType::Text, value: None, }, ), ]) } fn get_pix_bank_transfer_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ ( "payout_method_data.bank.bank_account_number".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank.bank_account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: FieldType::Text, value: None, }, ), ( "payout_method_data.bank.pix_key".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank.pix_key".to_string(), display_name: "pix_key".to_string(), field_type: FieldType::Text, value: None, }, ), ]) } fn get_sepa_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ ( "payout_method_data.bank.iban".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank.iban".to_string(), display_name: "iban".to_string(), field_type: FieldType::Text, value: None, }, ), ( "payout_method_data.bank.bic".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank.bic".to_string(), display_name: "bic".to_string(), field_type: FieldType::Text, value: None, }, ), ]) } fn get_paypal_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([( "payout_method_data.wallet.telephone_number".to_string(), RequiredFieldInfo { required_field: "payout_method_data.wallet.telephone_number".to_string(), display_name: "telephone_number".to_string(), field_type: FieldType::Text, value: None, }, )]) } fn get_countries_for_connector(connector: PayoutConnectors) -> Vec<CountryAlpha2> { match connector { PayoutConnectors::Adyenplatform => vec![ CountryAlpha2::ES, CountryAlpha2::SK, CountryAlpha2::AT, CountryAlpha2::NL, CountryAlpha2::DE, CountryAlpha2::BE, CountryAlpha2::FR, CountryAlpha2::FI, CountryAlpha2::PT, CountryAlpha2::IE, CountryAlpha2::EE, CountryAlpha2::LT, CountryAlpha2::LV, CountryAlpha2::IT, CountryAlpha2::CZ, CountryAlpha2::DE, CountryAlpha2::HU, CountryAlpha2::NO, CountryAlpha2::PL, CountryAlpha2::SE, CountryAlpha2::GB, CountryAlpha2::CH, ], PayoutConnectors::Stripe => vec![CountryAlpha2::US], _ => vec![], } } fn get_billing_details(connector: PayoutConnectors) -> HashMap<String, RequiredFieldInfo> { match connector { PayoutConnectors::Adyen => HashMap::from([ ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "billing.address.line1".to_string(), display_name: "billing_address_line1".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "billing.address.line2".to_string(), display_name: "billing_address_line2".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "billing.address.city".to_string(), display_name: "billing_address_city".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "billing.address.zip".to_string(), display_name: "billing_address_zip".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "billing.address.country".to_string(), display_name: "billing_address_country".to_string(), field_type: FieldType::UserAddressCountry { options: get_countries_for_connector(connector) .iter() .map(|country| country.to_string()) .collect::<Vec<String>>(), }, value: None, }, ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "billing.address.last_name".to_string(), display_name: "billing_address_last_name".to_string(), field_type: FieldType::Text, value: None, }, ), ]), PayoutConnectors::Adyenplatform => HashMap::from([ ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "billing.address.line1".to_string(), display_name: "billing_address_line1".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "billing.address.line2".to_string(), display_name: "billing_address_line2".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "billing.address.city".to_string(), display_name: "billing_address_city".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "billing.address.zip".to_string(), display_name: "billing_address_zip".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "billing.address.country".to_string(), display_name: "billing_address_country".to_string(), field_type: FieldType::UserAddressCountry { options: get_countries_for_connector(connector) .iter() .map(|country| country.to_string()) .collect::<Vec<String>>(), }, value: None, }, ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ), ]), PayoutConnectors::Wise => HashMap::from([ ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "billing.address.line1".to_string(), display_name: "billing_address_line1".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "billing.address.city".to_string(), display_name: "billing_address_city".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "billing.address.state".to_string(), display_name: "billing_address_state".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "billing.address.zip".to_string(), display_name: "billing_address_zip".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "billing.address.country".to_string(), display_name: "billing_address_country".to_string(), field_type: FieldType::UserAddressCountry { options: get_countries_for_connector(connector) .iter() .map(|country| country.to_string()) .collect::<Vec<String>>(), }, value: None, }, ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ), ]), _ => HashMap::from([ ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "billing.address.line1".to_string(), display_name: "billing_address_line1".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "billing.address.line2".to_string(), display_name: "billing_address_line2".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "billing.address.city".to_string(), display_name: "billing_address_city".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "billing.address.zip".to_string(), display_name: "billing_address_zip".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "billing.address.country".to_string(), display_name: "billing_address_country".to_string(), field_type: FieldType::UserAddressCountry { options: get_countries_for_connector(connector) .iter() .map(|country| country.to_string()) .collect::<Vec<String>>(), }, value: None, }, ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "billing.address.last_name".to_string(), display_name: "billing_address_last_name".to_string(), field_type: FieldType::Text, value: None, }, ), ]), } }
3,755
1,491
hyperswitch
crates/router/src/connector/stripe.rs
.rs
pub mod transformers; use std::collections::HashMap; use common_utils::{ request::RequestContent, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use diesel_models::enums; use error_stack::ResultExt; use hyperswitch_domain_models::router_request_types::SplitRefundsRequest; use masking::PeekInterface; use router_env::{instrument, tracing}; use stripe::auth_headers; use self::transformers as stripe; use super::utils::{self as connector_utils, PaymentMethodDataType, RefundsRequestData}; #[cfg(feature = "payouts")] use super::utils::{PayoutsData, RouterData}; use crate::{ configs::settings, consts, core::{ errors::{self, CustomResult}, payments, }, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, domain, }, utils::{crypto, ByteSliceExt, BytesExt, OptionExt}, }; #[derive(Clone)] pub struct Stripe { amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Stripe { pub const fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, } } } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Stripe where Self: services::ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), Self::common_get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Stripe { fn id(&self) -> &'static str { "stripe" } fn common_get_content_type(&self) -> &'static str { "application/x-www-form-urlencoded" } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { // &self.base_url connectors.stripe.base_url.as_ref() } fn get_auth_header( &self, auth_type: &types::ConnectorAuthType, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let auth = stripe::StripeAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![ ( headers::AUTHORIZATION.to_string(), format!("Bearer {}", auth.api_key.peek()).into_masked(), ), ( auth_headers::STRIPE_API_VERSION.to_string(), auth_headers::STRIPE_VERSION.to_string().into_masked(), ), ]) } #[cfg(feature = "payouts")] fn build_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::StripeConnectErrorResponse = res .response .parse_struct("StripeConnectErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message, attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl ConnectorValidation for Stripe { fn validate_connector_against_payment_request( &self, capture_method: Option<enums::CaptureMethod>, _payment_method: enums::PaymentMethod, _pmt: Option<enums::PaymentMethodType>, ) -> CustomResult<(), errors::ConnectorError> { let capture_method = capture_method.unwrap_or_default(); match capture_method { enums::CaptureMethod::SequentialAutomatic | enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( connector_utils::construct_not_supported_error_report(capture_method, self.id()), ), } } fn validate_mandate_payment( &self, pm_type: Option<types::storage::enums::PaymentMethodType>, pm_data: domain::payments::PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([ PaymentMethodDataType::Card, PaymentMethodDataType::ApplePay, PaymentMethodDataType::GooglePay, PaymentMethodDataType::AchBankDebit, PaymentMethodDataType::BacsBankDebit, PaymentMethodDataType::BecsBankDebit, PaymentMethodDataType::SepaBankDebit, PaymentMethodDataType::Sofort, PaymentMethodDataType::Ideal, PaymentMethodDataType::BancontactCard, ]); connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } impl api::Payment for Stripe {} impl api::PaymentAuthorize for Stripe {} impl api::PaymentSync for Stripe {} impl api::PaymentVoid for Stripe {} impl api::PaymentCapture for Stripe {} impl api::PaymentSession for Stripe {} impl api::ConnectorAccessToken for Stripe {} impl services::ConnectorIntegration< api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken, > for Stripe { // Not Implemented (R) } impl services::ConnectorIntegration< api::Session, types::PaymentsSessionData, types::PaymentsResponseData, > for Stripe { // Not Implemented (R) } impl api::ConnectorCustomer for Stripe {} impl services::ConnectorIntegration< api::CreateConnectorCustomer, types::ConnectorCustomerData, types::PaymentsResponseData, > for Stripe { fn get_headers( &self, req: &types::ConnectorCustomerRouterData, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), types::ConnectorCustomerType::get_content_type(self) .to_string() .into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::ConnectorCustomerRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "v1/customers")) } fn get_request_body( &self, req: &types::ConnectorCustomerRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = stripe::CustomerRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::ConnectorCustomerRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::ConnectorCustomerType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::ConnectorCustomerType::get_headers( self, req, connectors, )?) .set_body(types::ConnectorCustomerType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::ConnectorCustomerRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::ConnectorCustomerRouterData, errors::ConnectorError> where types::PaymentsResponseData: Clone, { let response: stripe::StripeCustomerResponse = res .response .parse_struct("StripeCustomerResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error .decline_code .map(|decline_code| { format!("message - {}, decline_code - {}", message, decline_code) }) .unwrap_or(message) }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl api::PaymentToken for Stripe {} impl services::ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Stripe { fn get_headers( &self, req: &types::TokenizationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), types::TokenizationType::get_content_type(self) .to_string() .into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::TokenizationRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "v1/tokens")) } fn get_request_body( &self, req: &types::TokenizationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = stripe::TokenRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::TokenizationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::TokenizationType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::TokenizationType::get_headers(self, req, connectors)?) .set_body(types::TokenizationType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::TokenizationRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> where types::PaymentsResponseData: Clone, { let response: stripe::StripeTokenResponse = res .response .parse_struct("StripeTokenResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error .decline_code .map(|decline_code| { format!("message - {}, decline_code - {}", message, decline_code) }) .unwrap_or(message) }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl api::MandateSetup for Stripe {} impl services::ConnectorIntegration< api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData, > for Stripe { fn get_headers( &self, req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), Self::common_get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::PaymentsCaptureRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = req.request.connector_transaction_id.as_str(); Ok(format!( "{}{}/{}/capture", self.base_url(connectors), "v1/payment_intents", id )) } fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, )?; let connector_req = stripe::CaptureRequest::try_from(amount)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PaymentsCaptureRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> where types::PaymentsCaptureData: Clone, types::PaymentsResponseData: Clone, { let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let response_integrity_object = connector_utils::get_capture_integrity_object( self.amount_converter, response.amount_received, response.currency.clone(), )?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let new_router_data = types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed); new_router_data.map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error .decline_code .map(|decline_code| { format!("message - {}, decline_code - {}", message, decline_code) }) .unwrap_or(message) }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Stripe { fn get_headers( &self, req: &types::PaymentsSyncRouterData, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), types::PaymentsSyncType::get_content_type(self) .to_string() .into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); if let Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment( stripe_split_payment, )) = &req.request.split_payments { transformers::transform_headers_for_connect_platform( stripe_split_payment.charge_type.clone(), stripe_split_payment.transfer_account_id.clone(), &mut header, ); } Ok(header) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = req.request.connector_transaction_id.clone(); match id.get_connector_transaction_id() { Ok(x) if x.starts_with("set") => Ok(format!( "{}{}/{}?expand[0]=latest_attempt", // expand latest attempt to extract payment checks and three_d_secure data self.base_url(connectors), "v1/setup_intents", x, )), Ok(x) => Ok(format!( "{}{}/{}{}", self.base_url(connectors), "v1/payment_intents", x, "?expand[0]=latest_charge" //updated payment_id(if present) reside inside latest_charge field )), x => x.change_context(errors::ConnectorError::MissingConnectorTransactionID), } } fn build_request( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> where types::PaymentsResponseData: Clone, { let id = data.request.connector_transaction_id.clone(); match id.get_connector_transaction_id() { Ok(x) if x.starts_with("set") => { let response: stripe::SetupIntentResponse = res .response .parse_struct("SetupIntentSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } Ok(_) => { let response: stripe::PaymentIntentSyncResponse = res .response .parse_struct("PaymentIntentSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let response_integrity_object = connector_utils::get_sync_integrity_object( self.amount_converter, response.amount, response.currency.clone(), )?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let new_router_data = types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }); new_router_data.map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) } Err(err) => { Err(err).change_context(errors::ConnectorError::MissingConnectorTransactionID) } } } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error .decline_code .map(|decline_code| { format!("message - {}, decline_code - {}", message, decline_code) }) .unwrap_or(message) }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } #[async_trait::async_trait] impl services::ConnectorIntegration< api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, > for Stripe { fn get_headers( &self, req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), types::PaymentsAuthorizeType::get_content_type(self) .to_string() .into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); if let Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment( stripe_split_payment, )) = &req.request.split_payments { if stripe_split_payment.charge_type == api::enums::PaymentChargeType::Stripe(api::enums::StripeChargeType::Direct) { let mut customer_account_header = vec![( headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), stripe_split_payment .transfer_account_id .clone() .into_masked(), )]; header.append(&mut customer_account_header); } } Ok(header) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v1/payment_intents" )) } fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_req = stripe::PaymentIntentRequest::try_from((req, amount))?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let response_integrity_object = connector_utils::get_authorise_integrity_object( self.amount_converter, response.amount, response.currency.clone(), )?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let new_router_data = types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed); new_router_data.map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error .decline_code .map(|decline_code| { format!("message - {}, decline_code - {}", message, decline_code) }) .unwrap_or(message) }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl services::ConnectorIntegration< api::Void, types::PaymentsCancelData, types::PaymentsResponseData, > for Stripe { fn get_headers( &self, req: &types::PaymentsCancelRouterData, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), types::PaymentsVoidType::get_content_type(self) .to_string() .into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::PaymentsCancelRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let payment_id = &req.request.connector_transaction_id; Ok(format!( "{}v1/payment_intents/{}/cancel", self.base_url(connectors), payment_id )) } fn get_request_body( &self, req: &types::PaymentsCancelRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = stripe::CancelRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PaymentsCancelRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(types::PaymentsVoidType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &types::PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: stripe::PaymentIntentResponse = res .response .parse_struct("PaymentIntentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error .decline_code .map(|decline_code| { format!("message - {}, decline_code - {}", message, decline_code) }) .unwrap_or(message) }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } type Verify = dyn services::ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >; impl services::ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for Stripe { fn get_headers( &self, req: &types::RouterData< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), Verify::get_content_type(self).to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::RouterData< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v1/setup_intents" )) } fn get_request_body( &self, req: &types::RouterData< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = stripe::SetupIntentRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::RouterData< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&Verify::get_url(self, req, connectors)?) .attach_default_headers() .headers(Verify::get_headers(self, req, connectors)?) .set_body(Verify::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &types::RouterData< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >, errors::ConnectorError, > where api::SetupMandate: Clone, types::SetupMandateRequestData: Clone, types::PaymentsResponseData: Clone, { let response: stripe::SetupIntentResponse = res .response .parse_struct("SetupIntentResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error .decline_code .map(|decline_code| { format!("message - {}, decline_code - {}", message, decline_code) }) .unwrap_or(message) }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl api::Refund for Stripe {} impl api::RefundExecute for Stripe {} impl api::RefundSync for Stripe {} impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Stripe { fn get_headers( &self, req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), types::RefundExecuteType::get_content_type(self) .to_string() .into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); if let Some(SplitRefundsRequest::StripeSplitRefund(ref stripe_split_refund)) = req.request.split_refunds.as_ref() { match &stripe_split_refund.charge_type { api::enums::PaymentChargeType::Stripe(stripe_charge) => { if stripe_charge == &api::enums::StripeChargeType::Direct { let mut customer_account_header = vec![( headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), stripe_split_refund .transfer_account_id .clone() .into_masked(), )]; header.append(&mut customer_account_header); } } } } Ok(header) } fn get_content_type(&self) -> &'static str { "application/x-www-form-urlencoded" } fn get_url( &self, _req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "v1/refunds")) } fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let request_body = match req.request.split_refunds.as_ref() { Some(SplitRefundsRequest::StripeSplitRefund(_)) => RequestContent::FormUrlEncoded( Box::new(stripe::ChargeRefundRequest::try_from(req)?), ), _ => RequestContent::FormUrlEncoded(Box::new(stripe::RefundRequest::try_from(( req, refund_amount, ))?)), }; Ok(request_body) } fn build_request( &self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } #[instrument(skip_all)] fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: stripe::RefundResponse = res.response .parse_struct("Stripe RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let response_integrity_object = connector_utils::get_refund_integrity_object( self.amount_converter, response.amount, response.currency.clone(), )?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let new_router_data = types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }); new_router_data .map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error .decline_code .map(|decline_code| { format!("message - {}, decline_code - {}", message, decline_code) }) .unwrap_or(message) }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Stripe { fn get_headers( &self, req: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), types::RefundSyncType::get_content_type(self) .to_string() .into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); if let Some(SplitRefundsRequest::StripeSplitRefund(ref stripe_refund)) = req.request.split_refunds.as_ref() { transformers::transform_headers_for_connect_platform( stripe_refund.charge_type.clone(), stripe_refund.transfer_account_id.clone(), &mut header, ); } Ok(header) } fn get_content_type(&self) -> &'static str { "application/x-www-form-urlencoded" } fn get_url( &self, req: &types::RefundsRouterData<api::RSync>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = req.request.get_connector_refund_id()?; Ok(format!("{}v1/refunds/{}", self.base_url(connectors), id)) } fn build_request( &self, req: &types::RefundsRouterData<api::RSync>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } #[instrument(skip_all)] fn handle_response( &self, data: &types::RefundsRouterData<api::RSync>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, errors::ConnectorError, > { let response: stripe::RefundResponse = res.response .parse_struct("Stripe RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; let response_integrity_object = connector_utils::get_refund_integrity_object( self.amount_converter, response.amount, response.currency.clone(), )?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let new_router_data = types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }); new_router_data .map(|mut router_data| { router_data.request.integrity_object = Some(response_integrity_object); router_data }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error .decline_code .map(|decline_code| { format!("message - {}, decline_code - {}", message, decline_code) }) .unwrap_or(message) }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl api::UploadFile for Stripe {} #[async_trait::async_trait] impl api::FileUpload for Stripe { fn validate_file_upload( &self, purpose: api::FilePurpose, file_size: i32, file_type: mime::Mime, ) -> CustomResult<(), errors::ConnectorError> { match purpose { api::FilePurpose::DisputeEvidence => { let supported_file_types = ["image/jpeg", "image/png", "application/pdf"]; // 5 Megabytes (MB) if file_size > 5000000 { Err(errors::ConnectorError::FileValidationFailed { reason: "file_size exceeded the max file size of 5MB".to_owned(), })? } if !supported_file_types.contains(&file_type.to_string().as_str()) { Err(errors::ConnectorError::FileValidationFailed { reason: "file_type does not match JPEG, JPG, PNG, or PDF format".to_owned(), })? } } } Ok(()) } } impl services::ConnectorIntegration< api::Upload, types::UploadFileRequestData, types::UploadFileResponse, > for Stripe { fn get_headers( &self, req: &types::RouterData< api::Upload, types::UploadFileRequestData, types::UploadFileResponse, >, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.get_auth_header(&req.connector_auth_type) } fn get_content_type(&self) -> &'static str { "multipart/form-data" } fn get_url( &self, _req: &types::UploadFileRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", connectors.stripe.base_url_file_upload, "v1/files" )) } fn get_request_body( &self, req: &types::UploadFileRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = transformers::construct_file_upload_request(req.clone())?; Ok(RequestContent::FormData(connector_req)) } fn build_request( &self, req: &types::UploadFileRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::UploadFileType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::UploadFileType::get_headers(self, req, connectors)?) .set_body(types::UploadFileType::get_request_body( self, req, connectors, )?) .build(), )) } #[instrument(skip_all)] fn handle_response( &self, data: &types::UploadFileRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData<api::Upload, types::UploadFileRequestData, types::UploadFileResponse>, errors::ConnectorError, > { let response: stripe::FileUploadResponse = res .response .parse_struct("Stripe FileUploadResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::UploadFileRouterData { response: Ok(types::UploadFileResponse { provider_file_id: response.file_id, }), ..data.clone() }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error .decline_code .map(|decline_code| { format!("message - {}, decline_code - {}", message, decline_code) }) .unwrap_or(message) }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl api::RetrieveFile for Stripe {} impl services::ConnectorIntegration< api::Retrieve, types::RetrieveFileRequestData, types::RetrieveFileResponse, > for Stripe { fn get_headers( &self, req: &types::RouterData< api::Retrieve, types::RetrieveFileRequestData, types::RetrieveFileResponse, >, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.get_auth_header(&req.connector_auth_type) } fn get_url( &self, req: &types::RetrieveFileRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v1/files/{}/contents", connectors.stripe.base_url_file_upload, req.request.provider_file_id )) } fn build_request( &self, req: &types::RetrieveFileRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) .url(&types::RetrieveFileType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RetrieveFileType::get_headers(self, req, connectors)?) .build(), )) } #[instrument(skip_all)] fn handle_response( &self, data: &types::RetrieveFileRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult< types::RouterData< api::Retrieve, types::RetrieveFileRequestData, types::RetrieveFileResponse, >, errors::ConnectorError, > { let response = res.response; event_builder.map(|event| event.set_response_body(&serde_json::json!({"connector_response_type": "file", "status_code": res.status_code}))); router_env::logger::info!(connector_response_type=?"file"); Ok(types::RetrieveFileRouterData { response: Ok(types::RetrieveFileResponse { file_data: response.to_vec(), }), ..data.clone() }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error .decline_code .map(|decline_code| { format!("message - {}, decline_code - {}", message, decline_code) }) .unwrap_or(message) }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl api::SubmitEvidence for Stripe {} impl services::ConnectorIntegration< api::Evidence, types::SubmitEvidenceRequestData, types::SubmitEvidenceResponse, > for Stripe { fn get_headers( &self, req: &types::SubmitEvidenceRouterData, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), types::SubmitEvidenceType::get_content_type(self) .to_string() .into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } fn get_content_type(&self) -> &'static str { "application/x-www-form-urlencoded" } fn get_url( &self, req: &types::SubmitEvidenceRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}{}", self.base_url(connectors), "v1/disputes/", req.request.connector_dispute_id )) } fn get_request_body( &self, req: &types::SubmitEvidenceRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = stripe::Evidence::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::SubmitEvidenceRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::SubmitEvidenceType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::SubmitEvidenceType::get_headers( self, req, connectors, )?) .set_body(types::SubmitEvidenceType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } #[instrument(skip_all)] fn handle_response( &self, data: &types::SubmitEvidenceRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::SubmitEvidenceRouterData, errors::ConnectorError> { let response: stripe::DisputeObj = res .response .parse_struct("Stripe DisputeObj") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::SubmitEvidenceRouterData { response: Ok(types::SubmitEvidenceResponse { dispute_status: api_models::enums::DisputeStatus::DisputeChallenged, connector_status: Some(response.status), }), ..data.clone() }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: stripe::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response .error .code .clone() .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), message: response .error .code .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: response.error.message.map(|message| { response .error .decline_code .map(|decline_code| { format!("message - {}, decline_code - {}", message, decline_code) }) .unwrap_or(message) }), attempt_status: None, connector_transaction_id: response.error.payment_intent.map(|pi| pi.id), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } fn get_signature_elements_from_header( headers: &actix_web::http::header::HeaderMap, ) -> CustomResult<HashMap<String, Vec<u8>>, errors::ConnectorError> { let security_header = headers .get("Stripe-Signature") .map(|header_value| { header_value .to_str() .map(String::from) .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound) }) .ok_or(errors::ConnectorError::WebhookSignatureNotFound)??; let props = security_header.split(',').collect::<Vec<&str>>(); let mut security_header_kvs: HashMap<String, Vec<u8>> = HashMap::with_capacity(props.len()); for prop_str in &props { let (prop_key, prop_value) = prop_str .split_once('=') .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)?; security_header_kvs.insert(prop_key.to_string(), prop_value.bytes().collect()); } Ok(security_header_kvs) } #[async_trait::async_trait] impl api::IncomingWebhook for Stripe { fn get_webhook_source_verification_algorithm( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, request: &api::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let mut security_header_kvs = get_signature_elements_from_header(request.headers)?; let signature = security_header_kvs .remove("v1") .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?; hex::decode(signature).change_context(errors::ConnectorError::WebhookSignatureNotFound) } fn get_webhook_source_verification_message( &self, request: &api::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let mut security_header_kvs = get_signature_elements_from_header(request.headers)?; let timestamp = security_header_kvs .remove("t") .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?; Ok(format!( "{}.{}", String::from_utf8_lossy(&timestamp), String::from_utf8_lossy(request.body) ) .into_bytes()) } fn get_webhook_object_reference_id( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let details: stripe::WebhookEvent = request .body .parse_struct("WebhookEvent") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(match details.event_data.event_object.object { stripe::WebhookEventObjectType::PaymentIntent => { match details .event_data .event_object .metadata .and_then(|meta_data| meta_data.order_id) { // if order_id is present Some(order_id) => api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(order_id), ), // else used connector_transaction_id None => api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( details.event_data.event_object.id, ), ), } } stripe::WebhookEventObjectType::Charge => { match details .event_data .event_object .metadata .and_then(|meta_data| meta_data.order_id) { // if order_id is present Some(order_id) => api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(order_id), ), // else used connector_transaction_id None => api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( details .event_data .event_object .payment_intent .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, ), ), } } stripe::WebhookEventObjectType::Dispute => { api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( details .event_data .event_object .payment_intent .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, ), ) } stripe::WebhookEventObjectType::Source => { api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PreprocessingId( details.event_data.event_object.id, ), ) } stripe::WebhookEventObjectType::Refund => { match details .event_data .event_object .metadata .clone() .and_then(|meta_data| meta_data.order_id) { // if meta_data is present Some(order_id) => { // Issue: 2076 match details .event_data .event_object .metadata .and_then(|meta_data| meta_data.is_refund_id_as_reference) { // if the order_id is refund_id Some(_) => api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::RefundId(order_id), ), // if the order_id is payment_id // since payment_id was being passed before the deployment of this pr _ => api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::ConnectorRefundId( details.event_data.event_object.id, ), ), } } // else use connector_transaction_id None => api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::ConnectorRefundId( details.event_data.event_object.id, ), ), } } }) } fn get_webhook_event_type( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { let details: stripe::WebhookEventTypeBody = request .body .parse_struct("WebhookEventTypeBody") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(match details.event_type { stripe::WebhookEventType::PaymentIntentFailed => { api::IncomingWebhookEvent::PaymentIntentFailure } stripe::WebhookEventType::PaymentIntentSucceed => { api::IncomingWebhookEvent::PaymentIntentSuccess } stripe::WebhookEventType::PaymentIntentCanceled => { api::IncomingWebhookEvent::PaymentIntentCancelled } stripe::WebhookEventType::PaymentIntentAmountCapturableUpdated => { api::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess } stripe::WebhookEventType::ChargeSucceeded => { if let Some(stripe::WebhookPaymentMethodDetails { payment_method: stripe::WebhookPaymentMethodType::AchCreditTransfer | stripe::WebhookPaymentMethodType::MultibancoBankTransfers, }) = details.event_data.event_object.payment_method_details { api::IncomingWebhookEvent::PaymentIntentSuccess } else { api::IncomingWebhookEvent::EventNotSupported } } stripe::WebhookEventType::ChargeRefundUpdated => details .event_data .event_object .status .map(|status| match status { stripe::WebhookEventStatus::Succeeded => { api::IncomingWebhookEvent::RefundSuccess } stripe::WebhookEventStatus::Failed => api::IncomingWebhookEvent::RefundFailure, _ => api::IncomingWebhookEvent::EventNotSupported, }) .unwrap_or(api::IncomingWebhookEvent::EventNotSupported), stripe::WebhookEventType::SourceChargeable => { api::IncomingWebhookEvent::SourceChargeable } stripe::WebhookEventType::DisputeCreated => api::IncomingWebhookEvent::DisputeOpened, stripe::WebhookEventType::DisputeClosed => api::IncomingWebhookEvent::DisputeCancelled, stripe::WebhookEventType::DisputeUpdated => details .event_data .event_object .status .map(Into::into) .unwrap_or(api::IncomingWebhookEvent::EventNotSupported), stripe::WebhookEventType::PaymentIntentPartiallyFunded => { api::IncomingWebhookEvent::PaymentIntentPartiallyFunded } stripe::WebhookEventType::PaymentIntentRequiresAction => { api::IncomingWebhookEvent::PaymentActionRequired } stripe::WebhookEventType::ChargeDisputeFundsWithdrawn => { api::IncomingWebhookEvent::DisputeLost } stripe::WebhookEventType::ChargeDisputeFundsReinstated => { api::IncomingWebhookEvent::DisputeWon } stripe::WebhookEventType::Unknown | stripe::WebhookEventType::ChargeCaptured | stripe::WebhookEventType::ChargeExpired | stripe::WebhookEventType::ChargeFailed | stripe::WebhookEventType::ChargePending | stripe::WebhookEventType::ChargeUpdated | stripe::WebhookEventType::ChargeRefunded | stripe::WebhookEventType::PaymentIntentCreated | stripe::WebhookEventType::PaymentIntentProcessing | stripe::WebhookEventType::SourceTransactionCreated => { api::IncomingWebhookEvent::EventNotSupported } }) } fn get_webhook_resource_object( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let details: stripe::WebhookEvent = request .body .parse_struct("WebhookEvent") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(Box::new(details.event_data.event_object)) } fn get_dispute_details( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::disputes::DisputePayload, errors::ConnectorError> { let details: stripe::WebhookEvent = request .body .parse_struct("WebhookEvent") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(api::disputes::DisputePayload { amount: details .event_data .event_object .amount .get_required_value("amount") .change_context(errors::ConnectorError::MissingRequiredField { field_name: "amount", })? .to_string(), currency: details.event_data.event_object.currency, dispute_stage: api_models::enums::DisputeStage::Dispute, connector_dispute_id: details.event_data.event_object.id, connector_reason: details.event_data.event_object.reason, connector_reason_code: None, challenge_required_by: details .event_data .event_object .evidence_details .map(|payload| payload.due_by), connector_status: details .event_data .event_object .status .ok_or(errors::ConnectorError::WebhookResourceObjectNotFound)? .to_string(), created_at: Some(details.event_data.event_object.created), updated_at: None, }) } } impl services::ConnectorRedirectResponse for Stripe { fn get_flow_type( &self, _query_params: &str, _json_payload: Option<serde_json::Value>, action: services::PaymentAction, ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { match action { services::PaymentAction::PSync | services::PaymentAction::CompleteAuthorize | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => { Ok(payments::CallConnectorAction::Trigger) } } } } impl api::Payouts for Stripe {} #[cfg(feature = "payouts")] impl api::PayoutCancel for Stripe {} #[cfg(feature = "payouts")] impl api::PayoutCreate for Stripe {} #[cfg(feature = "payouts")] impl api::PayoutFulfill for Stripe {} #[cfg(feature = "payouts")] impl api::PayoutRecipient for Stripe {} #[cfg(feature = "payouts")] impl api::PayoutRecipientAccount for Stripe {} #[cfg(feature = "payouts")] impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::PayoutsResponseData> for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::PayoutsRouterData<api::PoCancel>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let transfer_id = req.request.get_transfer_id()?; Ok(format!( "{}v1/transfers/{}/reversals", connectors.stripe.base_url, transfer_id )) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoCancel>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, _connectors) } fn get_request_body( &self, req: &types::RouterData<api::PoCancel, types::PayoutsData, types::PayoutsResponseData>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = stripe::StripeConnectReversalRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoCancel>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutCancelType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutCancelType::get_headers(self, req, connectors)?) .set_body(types::PayoutCancelType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &types::PayoutsRouterData<api::PoCancel>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> { let response: stripe::StripeConnectReversalResponse = res .response .parse_struct("StripeConnectReversalResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::PayoutsResponseData> for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::PayoutsRouterData<api::PoCreate>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v1/transfers", connectors.stripe.base_url)) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoCreate>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoCreate>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = stripe::StripeConnectPayoutCreateRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoCreate>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutCreateType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutCreateType::get_headers(self, req, connectors)?) .set_body(types::PayoutCreateType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &types::PayoutsRouterData<api::PoCreate>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> { let response: stripe::StripeConnectPayoutCreateResponse = res .response .parse_struct("StripeConnectPayoutCreateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v1/payouts", connectors.stripe.base_url,)) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut headers = self.build_headers(req, connectors)?; let customer_account = req.get_connector_customer_id()?; let mut customer_account_header = vec![( headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(), customer_account.into_masked(), )]; headers.append(&mut customer_account_header); Ok(headers) } fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoFulfill>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = stripe::StripeConnectPayoutFulfillRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutFulfillType::get_headers( self, req, connectors, )?) .set_body(types::PayoutFulfillType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &types::PayoutsRouterData<api::PoFulfill>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { let response: stripe::StripeConnectPayoutFulfillResponse = res .response .parse_struct("StripeConnectPayoutFulfillResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] impl services::ConnectorIntegration<api::PoRecipient, types::PayoutsData, types::PayoutsResponseData> for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::PayoutsRouterData<api::PoRecipient>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v1/accounts", connectors.stripe.base_url)) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoRecipient>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoRecipient>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = stripe::StripeConnectRecipientCreateRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoRecipient>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutRecipientType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutRecipientType::get_headers( self, req, connectors, )?) .set_body(types::PayoutRecipientType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &types::PayoutsRouterData<api::PoRecipient>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoRecipient>, errors::ConnectorError> { let response: stripe::StripeConnectRecipientCreateResponse = res .response .parse_struct("StripeConnectRecipientCreateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] impl services::ConnectorIntegration< api::PoRecipientAccount, types::PayoutsData, types::PayoutsResponseData, > for Stripe { fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::PayoutsRouterData<api::PoRecipientAccount>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_customer_id = req.get_connector_customer_id()?; Ok(format!( "{}v1/accounts/{}/external_accounts", connectors.stripe.base_url, connector_customer_id )) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoRecipientAccount>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoRecipientAccount>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = stripe::StripeConnectRecipientAccountCreateRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoRecipientAccount>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutRecipientAccountType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PayoutRecipientAccountType::get_headers( self, req, connectors, )?) .set_body(types::PayoutRecipientAccountType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &types::PayoutsRouterData<api::PoRecipientAccount>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoRecipientAccount>, errors::ConnectorError> { let response: stripe::StripeConnectRecipientAccountCreateResponse = res .response .parse_struct("StripeConnectRecipientAccountCreateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorSpecifications for Stripe {}
20,376
1,492
hyperswitch
crates/router/src/connector/threedsecureio.rs
.rs
pub mod transformers; use std::fmt::Debug; use error_stack::{report, ResultExt}; use masking::ExposeInterface; use pm_auth::consts; use transformers as threedsecureio; use crate::{ configs::settings, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, RequestContent, Response, }, utils::{self, BytesExt}, }; #[derive(Debug, Clone)] pub struct Threedsecureio; impl api::Payment for Threedsecureio {} impl api::PaymentSession for Threedsecureio {} impl api::ConnectorAccessToken for Threedsecureio {} impl api::MandateSetup for Threedsecureio {} impl api::PaymentAuthorize for Threedsecureio {} impl api::PaymentSync for Threedsecureio {} impl api::PaymentCapture for Threedsecureio {} impl api::PaymentVoid for Threedsecureio {} impl api::Refund for Threedsecureio {} impl api::RefundExecute for Threedsecureio {} impl api::RefundSync for Threedsecureio {} impl api::PaymentToken for Threedsecureio {} impl ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Threedsecureio { } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Threedsecureio where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), "application/json; charset=utf-8".to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Threedsecureio { fn id(&self) -> &'static str { "threedsecureio" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.threedsecureio.base_url.as_ref() } fn get_auth_header( &self, auth_type: &types::ConnectorAuthType, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let auth = threedsecureio::ThreedsecureioAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::APIKEY.to_string(), auth.api_key.expose().into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response_result: Result< threedsecureio::ThreedsecureioErrorResponse, error_stack::Report<common_utils::errors::ParsingError>, > = res.response.parse_struct("ThreedsecureioErrorResponse"); match response_result { Ok(response) => { event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.error_code, message: response .error_description .clone() .unwrap_or(consts::NO_ERROR_MESSAGE.to_owned()), reason: response.error_description, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } Err(err) => { router_env::logger::error!(deserialization_error =? err); utils::handle_json_response_deserialization_failure(res, "threedsecureio") } } } } impl ConnectorValidation for Threedsecureio {} impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for Threedsecureio { } impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> for Threedsecureio { } impl ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for Threedsecureio { } impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Threedsecureio { } impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Threedsecureio { } impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for Threedsecureio { } impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Threedsecureio { } impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Threedsecureio { } impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Threedsecureio { } #[async_trait::async_trait] impl api::IncomingWebhook for Threedsecureio { fn get_webhook_object_reference_id( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } impl api::ConnectorPreAuthentication for Threedsecureio {} impl api::ConnectorPreAuthenticationVersionCall for Threedsecureio {} impl api::ExternalAuthentication for Threedsecureio {} impl api::ConnectorAuthentication for Threedsecureio {} impl api::ConnectorPostAuthentication for Threedsecureio {} impl ConnectorIntegration< api::Authentication, types::authentication::ConnectorAuthenticationRequestData, types::authentication::AuthenticationResponseData, > for Threedsecureio { fn get_headers( &self, req: &types::authentication::ConnectorAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::authentication::ConnectorAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/auth", self.base_url(connectors),)) } fn get_request_body( &self, req: &types::authentication::ConnectorAuthenticationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = threedsecureio::ThreedsecureioRouterData::try_from(( &self.get_currency_unit(), req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?, req.request .amount .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "amount", })?, req, ))?; let req_obj = threedsecureio::ThreedsecureioAuthenticationRequest::try_from(&connector_router_data); Ok(RequestContent::Json(Box::new(req_obj?))) } fn build_request( &self, req: &types::authentication::ConnectorAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url( &types::authentication::ConnectorAuthenticationType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorAuthenticationType::get_headers( self, req, connectors, )?, ) .set_body( types::authentication::ConnectorAuthenticationType::get_request_body( self, req, connectors, )?, ) .build(), )) } fn handle_response( &self, data: &types::authentication::ConnectorAuthenticationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< types::authentication::ConnectorAuthenticationRouterData, errors::ConnectorError, > { let response: threedsecureio::ThreedsecureioAuthenticationResponse = res .response .parse_struct("ThreedsecureioAuthenticationResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< api::PreAuthentication, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, > for Threedsecureio { fn get_headers( &self, req: &types::authentication::PreAuthNRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::authentication::PreAuthNRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/preauth", self.base_url(connectors),)) } fn get_request_body( &self, req: &types::authentication::PreAuthNRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = threedsecureio::ThreedsecureioRouterData::try_from((0, req))?; let req_obj = threedsecureio::ThreedsecureioPreAuthenticationRequest::try_from( &connector_router_data, )?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &types::authentication::PreAuthNRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url( &types::authentication::ConnectorPreAuthenticationType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorPreAuthenticationType::get_headers( self, req, connectors, )?, ) .set_body( types::authentication::ConnectorPreAuthenticationType::get_request_body( self, req, connectors, )?, ) .build(), )) } fn handle_response( &self, data: &types::authentication::PreAuthNRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::authentication::PreAuthNRouterData, errors::ConnectorError> { let response: threedsecureio::ThreedsecureioPreAuthenticationResponse = res .response .parse_struct("threedsecureio ThreedsecureioPreAuthenticationResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< api::PostAuthentication, types::authentication::ConnectorPostAuthenticationRequestData, types::authentication::AuthenticationResponseData, > for Threedsecureio { fn get_headers( &self, req: &types::authentication::ConnectorPostAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::authentication::ConnectorPostAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/postauth", self.base_url(connectors),)) } fn get_request_body( &self, req: &types::authentication::ConnectorPostAuthenticationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = threedsecureio::ThreedsecureioPostAuthenticationRequest { three_ds_server_trans_id: req.request.threeds_server_transaction_id.clone(), }; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &types::authentication::ConnectorPostAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url( &types::authentication::ConnectorPostAuthenticationType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorPostAuthenticationType::get_headers( self, req, connectors, )?, ) .set_body( types::authentication::ConnectorPostAuthenticationType::get_request_body( self, req, connectors, )?, ) .build(), )) } fn handle_response( &self, data: &types::authentication::ConnectorPostAuthenticationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< types::authentication::ConnectorPostAuthenticationRouterData, errors::ConnectorError, > { let response: threedsecureio::ThreedsecureioPostAuthenticationResponse = res .response .parse_struct("threedsecureio PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok( types::authentication::ConnectorPostAuthenticationRouterData { response: Ok( types::authentication::AuthenticationResponseData::PostAuthNResponse { trans_status: response.trans_status.into(), authentication_value: response.authentication_value, eci: response.eci, }, ), ..data.clone() }, ) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< api::PreAuthenticationVersionCall, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, > for Threedsecureio { } impl ConnectorSpecifications for Threedsecureio {}
3,782
1,493
hyperswitch
crates/router/src/connector/payone.rs
.rs
pub mod transformers; use base64::Engine; #[cfg(feature = "payouts")] use common_utils::request::RequestContent; #[cfg(feature = "payouts")] use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector}; use error_stack::{report, ResultExt}; use masking::{ExposeInterface, PeekInterface}; use ring::hmac; #[cfg(feature = "payouts")] use router_env::{instrument, tracing}; use self::transformers as payone; #[cfg(feature = "payouts")] use crate::connector::utils::convert_amount; #[cfg(feature = "payouts")] use crate::get_formatted_date_time; #[cfg(feature = "payouts")] use crate::services; use crate::{ configs::settings, connector::{ utils as connector_utils, utils::{ConnectorErrorType, ConnectorErrorTypeMapping}, }, consts, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{ request::{self, Mask}, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, Response, }, utils::BytesExt, }; #[derive(Clone)] pub struct Payone { #[cfg(feature = "payouts")] amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Payone { pub fn new() -> &'static Self { &Self { #[cfg(feature = "payouts")] amount_converter: &MinorUnitForConnector, } } pub fn generate_signature( &self, auth: payone::PayoneAuthType, http_method: String, canonicalized_path: String, content_type: String, date_header: String, ) -> CustomResult<String, errors::ConnectorError> { let payone::PayoneAuthType { api_key, api_secret, .. } = auth; let string_to_hash: String = format!( "{}\n{}\n{}\n{}\n", http_method, content_type.trim(), date_header.trim(), canonicalized_path.trim() ); let key = hmac::Key::new(hmac::HMAC_SHA256, api_secret.expose().as_bytes()); let hash_hmac = consts::BASE64_ENGINE.encode(hmac::sign(&key, string_to_hash.as_bytes())); let signature_header = format!("GCS v1HMAC:{}:{}", api_key.peek(), hash_hmac); Ok(signature_header) } } impl api::Payment for Payone {} impl api::PaymentSession for Payone {} impl api::ConnectorAccessToken for Payone {} impl api::MandateSetup for Payone {} impl api::PaymentAuthorize for Payone {} impl api::PaymentSync for Payone {} impl api::PaymentCapture for Payone {} impl api::PaymentVoid for Payone {} impl api::Refund for Payone {} impl api::RefundExecute for Payone {} impl api::RefundSync for Payone {} impl api::PaymentToken for Payone {} impl ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Payone { } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Payone where Self: ConnectorIntegration<Flow, Request, Response>, { #[cfg(feature = "payouts")] fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let auth = payone::PayoneAuthType::try_from(&req.connector_auth_type)?; let http_method = self.get_http_method().to_string(); let content_type = Self::get_content_type(self); let base_url = self.base_url(connectors); let url = Self::get_url(self, req, connectors)?; let date_header = get_formatted_date_time!( "[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT" )?; let path: String = url.replace(base_url, "/"); let authorization_header: String = self.generate_signature( auth, http_method, path, content_type.to_string(), date_header.clone(), )?; let headers = vec![ (headers::DATE.to_string(), date_header.to_string().into()), ( headers::AUTHORIZATION.to_string(), authorization_header.to_string().into(), ), ]; Ok(headers) } } impl ConnectorCommon for Payone { fn id(&self) -> &'static str { "payone" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.payone.base_url.as_ref() } fn get_auth_header( &self, auth_type: &types::ConnectorAuthType, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let auth = payone::PayoneAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.expose().into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: payone::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let errors_list = response.errors.clone().unwrap_or_default(); let option_error_code_message = connector_utils::get_error_code_error_message_based_on_priority( self.clone(), errors_list .into_iter() .map(|errors| errors.into()) .collect(), ); match response.errors { Some(errors) => Ok(ErrorResponse { status_code: res.status_code, code: option_error_code_message .clone() .map(|error_code_message| error_code_message.error_code) .unwrap_or(consts::NO_ERROR_CODE.to_string()), message: option_error_code_message .clone() .map(|error_code_message| error_code_message.error_code) .unwrap_or(consts::NO_ERROR_CODE.to_string()), reason: Some( errors .iter() .map(|error| format!("{} : {}", error.code, error.message)) .collect::<Vec<String>>() .join(", "), ), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }), None => Ok(ErrorResponse { status_code: res.status_code, code: consts::NO_ERROR_CODE.to_string(), message: consts::NO_ERROR_MESSAGE.to_string(), reason: None, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }), } } } impl ConnectorValidation for Payone {} impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for Payone { } impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> for Payone { } impl ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for Payone { } impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Payone { } impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Payone { } impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for Payone { } impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Payone { } impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Payone {} impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Payone {} impl api::Payouts for Payone {} #[cfg(feature = "payouts")] impl api::PayoutFulfill for Payone {} #[cfg(feature = "payouts")] impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> for Payone { fn get_url( &self, req: &types::PayoutsRouterData<api::PoFulfill>, _connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let auth = payone::PayoneAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(format!( "{}v2/{}/payouts", self.base_url(_connectors), auth.merchant_account.peek() )) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoFulfill>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.destination_currency, )?; let connector_router_data = payone::PayoneRouterData::from((amount, req)); let connector_req = payone::PayonePayoutFulfillRequest::try_from(connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutFulfillType::get_headers( self, req, connectors, )?) .set_body(types::PayoutFulfillType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } #[instrument(skip_all)] fn handle_response( &self, data: &types::PayoutsRouterData<api::PoFulfill>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { let response: payone::PayonePayoutFulfillResponse = res .response .parse_struct("PayonePayoutFulfillResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl api::IncomingWebhook for Payone { fn get_webhook_object_reference_id( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } impl ConnectorErrorTypeMapping for Payone { fn get_connector_error_type( &self, error_code: String, _error_message: String, ) -> ConnectorErrorType { match error_code.as_str() { "30001101" => ConnectorErrorType::BusinessError, "30001100" => ConnectorErrorType::BusinessError, "30001102" => ConnectorErrorType::BusinessError, "30001104" => ConnectorErrorType::BusinessError, "30001105" => ConnectorErrorType::BusinessError, "30001106" => ConnectorErrorType::TechnicalError, "30001120" => ConnectorErrorType::BusinessError, "30001130" => ConnectorErrorType::BusinessError, "30001140" => ConnectorErrorType::BusinessError, "30001141" => ConnectorErrorType::BusinessError, "30001142" => ConnectorErrorType::BusinessError, "30001143" => ConnectorErrorType::BusinessError, "30001158" => ConnectorErrorType::UserError, "30001180" => ConnectorErrorType::TechnicalError, "30031001" => ConnectorErrorType::UserError, "30041001" => ConnectorErrorType::UserError, "30051001" => ConnectorErrorType::BusinessError, "30141001" => ConnectorErrorType::UserError, "30431001" => ConnectorErrorType::UserError, "30511001" => ConnectorErrorType::UserError, "30581001" => ConnectorErrorType::UserError, "30591001" => ConnectorErrorType::BusinessError, "30621001" => ConnectorErrorType::BusinessError, "30921001" => ConnectorErrorType::TechnicalError, "40001134" => ConnectorErrorType::BusinessError, "40001135" => ConnectorErrorType::BusinessError, "50001081" => ConnectorErrorType::TechnicalError, "40001137" => ConnectorErrorType::TechnicalError, "40001138" => ConnectorErrorType::TechnicalError, "40001139" => ConnectorErrorType::UserError, "50001054" => ConnectorErrorType::TechnicalError, "50001087" => ConnectorErrorType::TechnicalError, _ => ConnectorErrorType::UnknownError, } } } impl ConnectorSpecifications for Payone {}
3,600
1,494
hyperswitch
crates/router/src/connector/signifyd.rs
.rs
pub mod transformers; use std::fmt::Debug; #[cfg(feature = "frm")] use base64::Engine; #[cfg(feature = "frm")] use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; #[cfg(feature = "frm")] use error_stack::ResultExt; #[cfg(feature = "frm")] use masking::{PeekInterface, Secret}; #[cfg(feature = "frm")] use ring::hmac; #[cfg(feature = "frm")] use transformers as signifyd; #[cfg(feature = "frm")] use super::utils as connector_utils; use crate::{ configs::settings, core::errors::{self, CustomResult}, headers, services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, }, }; #[cfg(feature = "frm")] use crate::{ consts, events::connector_api_logs::ConnectorEvent, types::{api::fraud_check as frm_api, fraud_check as frm_types, ErrorResponse, Response}, utils::BytesExt, }; #[derive(Debug, Clone)] pub struct Signifyd; impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Signifyd where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Signifyd { fn id(&self) -> &'static str { "signifyd" } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.signifyd.base_url.as_ref() } #[cfg(feature = "frm")] fn get_auth_header( &self, auth_type: &types::ConnectorAuthType, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let auth = signifyd::SignifydAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let auth_api_key = format!( "Basic {}", consts::BASE64_ENGINE.encode(auth.api_key.peek()) ); Ok(vec![( headers::AUTHORIZATION.to_string(), request::Mask::into_masked(auth_api_key), )]) } #[cfg(feature = "frm")] fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: signifyd::SignifydErrorResponse = res .response .parse_struct("SignifydErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: consts::NO_ERROR_CODE.to_string(), message: response.messages.join(" &"), reason: Some(response.errors.to_string()), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl api::Payment for Signifyd {} impl api::PaymentAuthorize for Signifyd {} impl api::PaymentSync for Signifyd {} impl api::PaymentVoid for Signifyd {} impl api::PaymentCapture for Signifyd {} impl api::MandateSetup for Signifyd {} impl api::ConnectorAccessToken for Signifyd {} impl api::PaymentToken for Signifyd {} impl api::Refund for Signifyd {} impl api::RefundExecute for Signifyd {} impl api::RefundSync for Signifyd {} impl ConnectorValidation for Signifyd {} impl ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Signifyd { } impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> for Signifyd { } impl ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for Signifyd { fn build_request( &self, _req: &types::RouterData< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >, _connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Signifyd".to_string()) .into(), ) } } impl api::PaymentSession for Signifyd {} impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for Signifyd { } impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for Signifyd { } impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Signifyd { } impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Signifyd { } impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Signifyd { } impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Signifyd { } impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Signifyd {} #[cfg(feature = "frm")] impl api::FraudCheck for Signifyd {} #[cfg(feature = "frm")] impl frm_api::FraudCheckSale for Signifyd {} #[cfg(feature = "frm")] impl frm_api::FraudCheckCheckout for Signifyd {} #[cfg(feature = "frm")] impl frm_api::FraudCheckTransaction for Signifyd {} #[cfg(feature = "frm")] impl frm_api::FraudCheckFulfillment for Signifyd {} #[cfg(feature = "frm")] impl frm_api::FraudCheckRecordReturn for Signifyd {} #[cfg(feature = "frm")] impl ConnectorIntegration< frm_api::Sale, frm_types::FraudCheckSaleData, frm_types::FraudCheckResponseData, > for Signifyd { fn get_headers( &self, req: &frm_types::FrmSaleRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &frm_types::FrmSaleRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/sales" )) } fn get_request_body( &self, req: &frm_types::FrmSaleRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = signifyd::SignifydPaymentsSaleRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &frm_types::FrmSaleRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&frm_types::FrmSaleType::get_url(self, req, connectors)?) .attach_default_headers() .headers(frm_types::FrmSaleType::get_headers(self, req, connectors)?) .set_body(frm_types::FrmSaleType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &frm_types::FrmSaleRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmSaleRouterData, errors::ConnectorError> { let response: signifyd::SignifydPaymentsResponse = res .response .parse_struct("SignifydPaymentsResponse Sale") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <frm_types::FrmSaleRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] impl ConnectorIntegration< frm_api::Checkout, frm_types::FraudCheckCheckoutData, frm_types::FraudCheckResponseData, > for Signifyd { fn get_headers( &self, req: &frm_types::FrmCheckoutRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &frm_types::FrmCheckoutRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/checkouts" )) } fn get_request_body( &self, req: &frm_types::FrmCheckoutRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = signifyd::SignifydPaymentsCheckoutRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &frm_types::FrmCheckoutRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&frm_types::FrmCheckoutType::get_url(self, req, connectors)?) .attach_default_headers() .headers(frm_types::FrmCheckoutType::get_headers( self, req, connectors, )?) .set_body(frm_types::FrmCheckoutType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &frm_types::FrmCheckoutRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmCheckoutRouterData, errors::ConnectorError> { let response: signifyd::SignifydPaymentsResponse = res .response .parse_struct("SignifydPaymentsResponse Checkout") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <frm_types::FrmCheckoutRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] impl ConnectorIntegration< frm_api::Transaction, frm_types::FraudCheckTransactionData, frm_types::FraudCheckResponseData, > for Signifyd { fn get_headers( &self, req: &frm_types::FrmTransactionRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &frm_types::FrmTransactionRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/transactions" )) } fn get_request_body( &self, req: &frm_types::FrmTransactionRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = signifyd::SignifydPaymentsTransactionRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &frm_types::FrmTransactionRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&frm_types::FrmTransactionType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(frm_types::FrmTransactionType::get_headers( self, req, connectors, )?) .set_body(frm_types::FrmTransactionType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &frm_types::FrmTransactionRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmTransactionRouterData, errors::ConnectorError> { let response: signifyd::SignifydPaymentsResponse = res .response .parse_struct("SignifydPaymentsResponse Transaction") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <frm_types::FrmTransactionRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] impl ConnectorIntegration< frm_api::Fulfillment, frm_types::FraudCheckFulfillmentData, frm_types::FraudCheckResponseData, > for Signifyd { fn get_headers( &self, req: &frm_types::FrmFulfillmentRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &frm_types::FrmFulfillmentRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/fulfillments" )) } fn get_request_body( &self, req: &frm_types::FrmFulfillmentRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = signifyd::FrmFulfillmentSignifydRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj.clone()))) } fn build_request( &self, req: &frm_types::FrmFulfillmentRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&frm_types::FrmFulfillmentType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(frm_types::FrmFulfillmentType::get_headers( self, req, connectors, )?) .set_body(frm_types::FrmFulfillmentType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &frm_types::FrmFulfillmentRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmFulfillmentRouterData, errors::ConnectorError> { let response: signifyd::FrmFulfillmentSignifydApiResponse = res .response .parse_struct("FrmFulfillmentSignifydApiResponse Sale") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); frm_types::FrmFulfillmentRouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] impl ConnectorIntegration< frm_api::RecordReturn, frm_types::FraudCheckRecordReturnData, frm_types::FraudCheckResponseData, > for Signifyd { fn get_headers( &self, req: &frm_types::FrmRecordReturnRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &frm_types::FrmRecordReturnRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "v3/orders/events/returns/records" )) } fn get_request_body( &self, req: &frm_types::FrmRecordReturnRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let req_obj = signifyd::SignifydPaymentsRecordReturnRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &frm_types::FrmRecordReturnRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&frm_types::FrmRecordReturnType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(frm_types::FrmRecordReturnType::get_headers( self, req, connectors, )?) .set_body(frm_types::FrmRecordReturnType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &frm_types::FrmRecordReturnRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<frm_types::FrmRecordReturnRouterData, errors::ConnectorError> { let response: signifyd::SignifydPaymentsRecordReturnResponse = res .response .parse_struct("SignifydPaymentsResponse Transaction") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); <frm_types::FrmRecordReturnRouterData>::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "frm")] #[async_trait::async_trait] impl api::IncomingWebhook for Signifyd { fn get_webhook_source_verification_algorithm( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, request: &api::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let header_value = connector_utils::get_header_key_value("x-signifyd-sec-hmac-sha256", request.headers)?; Ok(header_value.as_bytes().to_vec()) } fn get_webhook_source_verification_message( &self, request: &api::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { Ok(request.body.to_vec()) } async fn verify_webhook_source( &self, request: &api::IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_label, connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let message = self .get_webhook_source_verification_message( request, merchant_id, &connector_webhook_secrets, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &connector_webhook_secrets.secret); let signed_message = hmac::sign(&signing_key, &message); let payload_sign = consts::BASE64_ENGINE.encode(signed_message.as_ref()); Ok(payload_sign.as_bytes().eq(&signature)) } fn get_webhook_object_reference_id( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let resource: signifyd::SignifydWebhookBody = request .body .parse_struct("SignifydWebhookBody") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; Ok(api::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(resource.order_id), )) } fn get_webhook_event_type( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { let resource: signifyd::SignifydWebhookBody = request .body .parse_struct("SignifydWebhookBody") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; Ok(api::IncomingWebhookEvent::from(resource.review_disposition)) } fn get_webhook_resource_object( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let resource: signifyd::SignifydWebhookBody = request .body .parse_struct("SignifydWebhookBody") .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; Ok(Box::new(resource)) } } impl ConnectorSpecifications for Signifyd {}
5,820
1,495
hyperswitch
crates/router/src/connector/dummyconnector.rs
.rs
pub mod transformers; use std::fmt::Debug; use common_utils::{consts as common_consts, request::RequestContent}; use diesel_models::enums; use error_stack::{report, ResultExt}; use super::utils::RefundsRequestData; use crate::{ configs::settings, connector::utils as connector_utils, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, Response, }, utils::BytesExt, }; #[derive(Debug, Clone)] pub struct DummyConnector<const T: u8>; impl<const T: u8> api::Payment for DummyConnector<T> {} impl<const T: u8> api::PaymentSession for DummyConnector<T> {} impl<const T: u8> api::ConnectorAccessToken for DummyConnector<T> {} impl<const T: u8> api::MandateSetup for DummyConnector<T> {} impl<const T: u8> api::PaymentAuthorize for DummyConnector<T> {} impl<const T: u8> api::PaymentSync for DummyConnector<T> {} impl<const T: u8> api::PaymentCapture for DummyConnector<T> {} impl<const T: u8> api::PaymentVoid for DummyConnector<T> {} impl<const T: u8> api::Refund for DummyConnector<T> {} impl<const T: u8> api::RefundExecute for DummyConnector<T> {} impl<const T: u8> api::RefundSync for DummyConnector<T> {} impl<const T: u8> api::PaymentToken for DummyConnector<T> {} impl<const T: u8> ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for DummyConnector<T> { // Not Implemented (R) } impl<const T: u8, Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for DummyConnector<T> where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), types::PaymentsAuthorizeType::get_content_type(self) .to_string() .into(), ), ( common_consts::TENANT_HEADER.to_string(), req.tenant_id.get_string_repr().to_string().into(), ), ]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl<const T: u8> ConnectorCommon for DummyConnector<T> { fn id(&self) -> &'static str { Into::<transformers::DummyConnectors>::into(T).get_dummy_connector_id() } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.dummyconnector.base_url.as_ref() } fn get_auth_header( &self, auth_type: &types::ConnectorAuthType, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let auth = transformers::DummyConnectorAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: transformers::DummyConnectorErrorResponse = res .response .parse_struct("DummyConnectorErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.error.code, message: response.error.message, reason: response.error.reason, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl<const T: u8> ConnectorValidation for DummyConnector<T> { fn validate_connector_against_payment_request( &self, capture_method: Option<enums::CaptureMethod>, _payment_method: enums::PaymentMethod, _pmt: Option<enums::PaymentMethodType>, ) -> CustomResult<(), errors::ConnectorError> { let capture_method = capture_method.unwrap_or_default(); match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual | enums::CaptureMethod::SequentialAutomatic => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( connector_utils::construct_not_supported_error_report(capture_method, self.id()), ), } } } impl<const T: u8> ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for DummyConnector<T> { //TODO: implement sessions flow } impl<const T: u8> ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> for DummyConnector<T> { } impl<const T: u8> ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for DummyConnector<T> { fn build_request( &self, _req: &types::RouterData< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >, _connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented( "Setup Mandate flow for DummyConnector".to_string(), ) .into()) } } impl<const T: u8> ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for DummyConnector<T> { fn get_headers( &self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { match req.payment_method { enums::PaymentMethod::Card => Ok(format!("{}/payment", self.base_url(connectors))), enums::PaymentMethod::Wallet => Ok(format!("{}/payment", self.base_url(connectors))), enums::PaymentMethod::PayLater => Ok(format!("{}/payment", self.base_url(connectors))), _ => Err(error_stack::report!(errors::ConnectorError::NotSupported { message: format!("The payment method {} is not supported", req.payment_method), connector: Into::<transformers::DummyConnectors>::into(T).get_dummy_connector_id(), })), } } fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = transformers::DummyConnectorPaymentsRequest::<T>::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: transformers::PaymentsResponse = res .response .parse_struct("DummyConnector PaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl<const T: u8> ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for DummyConnector<T> { fn get_headers( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { match req .request .connector_transaction_id .get_connector_transaction_id() { Ok(transaction_id) => Ok(format!( "{}/payments/{}", self.base_url(connectors), transaction_id )), Err(_) => Err(error_stack::report!( errors::ConnectorError::MissingConnectorTransactionID )), } } fn build_request( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: transformers::PaymentsResponse = res .response .parse_struct("dummyconnector PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl<const T: u8> ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for DummyConnector<T> { fn get_headers( &self, req: &types::PaymentsCaptureRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, _req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } fn build_request( &self, req: &types::PaymentsCaptureRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: transformers::PaymentsResponse = res .response .parse_struct("transformers PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl<const T: u8> ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for DummyConnector<T> { } impl<const T: u8> ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for DummyConnector<T> { fn get_headers( &self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/{}/refund", self.base_url(connectors), req.request.connector_transaction_id )) } fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = transformers::DummyConnectorRefundRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: transformers::RefundResponse = res .response .parse_struct("transformers RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl<const T: u8> ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for DummyConnector<T> { fn get_headers( &self, req: &types::RefundSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::RefundSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let refund_id = req.request.get_connector_refund_id()?; Ok(format!( "{}/refunds/{}", self.base_url(connectors), refund_id )) } fn build_request( &self, req: &types::RefundSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &types::RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: transformers::RefundResponse = res .response .parse_struct("transformers RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl<const T: u8> api::IncomingWebhook for DummyConnector<T> { fn get_webhook_object_reference_id( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { Ok(api::IncomingWebhookEvent::EventNotSupported) } fn get_webhook_resource_object( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } impl<const T: u8> ConnectorSpecifications for DummyConnector<T> {}
4,786
1,496
hyperswitch
crates/router/src/connector/adyenplatform.rs
.rs
pub mod transformers; use api_models::{self, webhooks::IncomingWebhookEvent}; #[cfg(feature = "payouts")] use base64::Engine; #[cfg(feature = "payouts")] use common_utils::request::RequestContent; #[cfg(feature = "payouts")] use common_utils::types::MinorUnitForConnector; #[cfg(feature = "payouts")] use common_utils::types::{AmountConvertor, MinorUnit}; #[cfg(not(feature = "payouts"))] use error_stack::report; use error_stack::ResultExt; #[cfg(feature = "payouts")] use http::HeaderName; use hyperswitch_interfaces::webhooks::IncomingWebhookFlowError; use masking::Maskable; #[cfg(feature = "payouts")] use masking::Secret; #[cfg(feature = "payouts")] use ring::hmac; #[cfg(feature = "payouts")] use router_env::{instrument, tracing}; use self::transformers as adyenplatform; #[cfg(feature = "payouts")] use crate::connector::utils::convert_amount; use crate::{ configs::settings, core::errors::{self, CustomResult}, headers, services::{self, request::Mask, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon}, }, }; #[cfg(feature = "payouts")] use crate::{ consts, events::connector_api_logs::ConnectorEvent, types::transformers::ForeignFrom, utils::{crypto, ByteSliceExt, BytesExt}, }; #[derive(Clone)] pub struct Adyenplatform { #[cfg(feature = "payouts")] amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Adyenplatform { pub const fn new() -> &'static Self { &Self { #[cfg(feature = "payouts")] amount_converter: &MinorUnitForConnector, } } } impl ConnectorCommon for Adyenplatform { fn id(&self) -> &'static str { "adyenplatform" } fn get_auth_header( &self, auth_type: &types::ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let auth = adyenplatform::AdyenplatformAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.into_masked(), )]) } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.adyenplatform.base_url.as_ref() } #[cfg(feature = "payouts")] fn build_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: adyenplatform::AdyenTransferErrorResponse = res .response .parse_struct("AdyenTransferErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response.error_code, message: response.title, reason: response.detail, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl api::Payment for Adyenplatform {} impl api::PaymentAuthorize for Adyenplatform {} impl api::PaymentSync for Adyenplatform {} impl api::PaymentVoid for Adyenplatform {} impl api::PaymentCapture for Adyenplatform {} impl api::MandateSetup for Adyenplatform {} impl api::ConnectorAccessToken for Adyenplatform {} impl api::PaymentToken for Adyenplatform {} impl ConnectorValidation for Adyenplatform {} impl services::ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Adyenplatform { } impl services::ConnectorIntegration< api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken, > for Adyenplatform { } impl services::ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for Adyenplatform { } impl api::PaymentSession for Adyenplatform {} impl services::ConnectorIntegration< api::Session, types::PaymentsSessionData, types::PaymentsResponseData, > for Adyenplatform { } impl services::ConnectorIntegration< api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData, > for Adyenplatform { } impl services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Adyenplatform { } impl services::ConnectorIntegration< api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, > for Adyenplatform { } impl services::ConnectorIntegration< api::Void, types::PaymentsCancelData, types::PaymentsResponseData, > for Adyenplatform { } impl api::Payouts for Adyenplatform {} #[cfg(feature = "payouts")] impl api::PayoutFulfill for Adyenplatform {} #[cfg(feature = "payouts")] impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> for Adyenplatform { fn get_url( &self, _req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}btl/v4/transfers", connectors.adyenplatform.base_url, )) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoFulfill>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), types::PayoutFulfillType::get_content_type(self) .to_string() .into(), )]; let auth = adyenplatform::AdyenplatformAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let mut api_key = vec![( headers::AUTHORIZATION.to_string(), auth.api_key.into_masked(), )]; header.append(&mut api_key); Ok(header) } fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoFulfill>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.destination_currency, )?; let connector_router_data = adyenplatform::AdyenPlatformRouterData::try_from((amount, req))?; let connector_req = adyenplatform::AdyenTransferRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutFulfillType::get_headers( self, req, connectors, )?) .set_body(types::PayoutFulfillType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } #[instrument(skip_all)] fn handle_response( &self, data: &types::PayoutsRouterData<api::PoFulfill>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { let response: adyenplatform::AdyenTransferResponse = res .response .parse_struct("AdyenTransferResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::Refund for Adyenplatform {} impl api::RefundExecute for Adyenplatform {} impl api::RefundSync for Adyenplatform {} impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Adyenplatform { } impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Adyenplatform { } #[async_trait::async_trait] impl api::IncomingWebhook for Adyenplatform { #[cfg(feature = "payouts")] fn get_webhook_source_verification_algorithm( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } #[cfg(feature = "payouts")] fn get_webhook_source_verification_signature( &self, request: &api::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let base64_signature = request .headers .get(HeaderName::from_static("hmacsignature")) .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)?; Ok(base64_signature.as_bytes().to_vec()) } #[cfg(feature = "payouts")] fn get_webhook_source_verification_message( &self, request: &api::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { Ok(request.body.to_vec()) } #[cfg(feature = "payouts")] async fn verify_webhook_source( &self, request: &api::IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, errors::ConnectorError> { let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_label, connector_webhook_details, ) .await .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let message = self .get_webhook_source_verification_message( request, merchant_id, &connector_webhook_secrets, ) .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let raw_key = hex::decode(connector_webhook_secrets.secret) .change_context(errors::ConnectorError::WebhookVerificationSecretInvalid)?; let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &raw_key); let signed_messaged = hmac::sign(&signing_key, &message); let payload_sign = consts::BASE64_ENGINE.encode(signed_messaged.as_ref()); Ok(payload_sign.as_bytes().eq(&signature)) } fn get_webhook_object_reference_id( &self, #[cfg(feature = "payouts")] request: &api::IncomingWebhookRequestDetails<'_>, #[cfg(not(feature = "payouts"))] _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { #[cfg(feature = "payouts")] { let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request .body .parse_struct("AdyenplatformIncomingWebhook") .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; Ok(api_models::webhooks::ObjectReferenceId::PayoutId( api_models::webhooks::PayoutIdType::PayoutAttemptId(webhook_body.data.reference), )) } #[cfg(not(feature = "payouts"))] { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } fn get_webhook_api_response( &self, _request: &api::IncomingWebhookRequestDetails<'_>, error_kind: Option<IncomingWebhookFlowError>, ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError> { if error_kind.is_some() { Ok(services::api::ApplicationResponse::JsonWithHeaders(( serde_json::Value::Null, vec![( "x-http-code".to_string(), Maskable::Masked(Secret::new("404".to_string())), )], ))) } else { Ok(services::api::ApplicationResponse::StatusOk) } } fn get_webhook_event_type( &self, #[cfg(feature = "payouts")] request: &api::IncomingWebhookRequestDetails<'_>, #[cfg(not(feature = "payouts"))] _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { #[cfg(feature = "payouts")] { let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request .body .parse_struct("AdyenplatformIncomingWebhook") .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; Ok(IncomingWebhookEvent::foreign_from(( webhook_body.webhook_type, webhook_body.data.status, webhook_body.data.tracking, ))) } #[cfg(not(feature = "payouts"))] { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } fn get_webhook_resource_object( &self, #[cfg(feature = "payouts")] request: &api::IncomingWebhookRequestDetails<'_>, #[cfg(not(feature = "payouts"))] _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { #[cfg(feature = "payouts")] { let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request .body .parse_struct("AdyenplatformIncomingWebhook") .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; Ok(Box::new(webhook_body)) } #[cfg(not(feature = "payouts"))] { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } } impl ConnectorSpecifications for Adyenplatform {}
3,581
1,497
hyperswitch
crates/router/src/connector/utils.rs
.rs
use std::{ collections::{HashMap, HashSet}, str::FromStr, }; #[cfg(feature = "payouts")] use api_models::payouts::{self, PayoutVendorAccountDetails}; use api_models::{ enums::{CanadaStatesAbbreviation, UsStatesAbbreviation}, payments, }; use base64::Engine; use common_utils::{ date_time, errors::{ParsingError, ReportSwitchExt}, ext_traits::StringExt, id_type, pii::{self, Email, IpAddress}, types::{AmountConvertor, MinorUnit}, }; use diesel_models::{enums, types::OrderDetailsWithAmount}; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ mandates, network_tokenization::NetworkTokenNumber, payments::payment_attempt::PaymentAttempt, router_request_types::{ AuthoriseIntegrityObject, CaptureIntegrityObject, RefundIntegrityObject, SyncIntegrityObject, }, }; use masking::{Deserialize, ExposeInterface, Secret}; use once_cell::sync::Lazy; use regex::Regex; use serde::Serializer; use time::PrimitiveDateTime; #[cfg(feature = "frm")] use crate::types::fraud_check; use crate::{ consts, core::{ errors::{self, ApiErrorResponse, CustomResult}, payments::{types::AuthenticationData, PaymentData}, }, pii::PeekInterface, types::{ self, api, domain, storage::enums as storage_enums, transformers::{ForeignFrom, ForeignTryFrom}, ApplePayPredecryptData, BrowserInformation, PaymentsCancelData, ResponseId, }, utils::{OptionExt, ValueExt}, }; pub fn missing_field_err( message: &'static str, ) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> { Box::new(move || { errors::ConnectorError::MissingRequiredField { field_name: message, } .into() }) } type Error = error_stack::Report<errors::ConnectorError>; pub trait AccessTokenRequestInfo { fn get_request_id(&self) -> Result<Secret<String>, Error>; } impl AccessTokenRequestInfo for types::RefreshTokenRouterData { fn get_request_id(&self) -> Result<Secret<String>, Error> { self.request .id .clone() .ok_or_else(missing_field_err("request.id")) } } pub trait RouterData { fn get_billing(&self) -> Result<&hyperswitch_domain_models::address::Address, Error>; fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error>; fn get_billing_phone(&self) -> Result<&hyperswitch_domain_models::address::PhoneDetails, Error>; fn get_description(&self) -> Result<String, Error>; fn get_billing_address( &self, ) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error>; fn get_shipping_address( &self, ) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error>; fn get_shipping_address_with_phone_number( &self, ) -> Result<&hyperswitch_domain_models::address::Address, Error>; fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error>; fn get_session_token(&self) -> Result<String, Error>; fn get_billing_first_name(&self) -> Result<Secret<String>, Error>; fn get_billing_full_name(&self) -> Result<Secret<String>, Error>; fn get_billing_last_name(&self) -> Result<Secret<String>, Error>; fn get_billing_line1(&self) -> Result<Secret<String>, Error>; fn get_billing_city(&self) -> Result<String, Error>; fn get_billing_email(&self) -> Result<Email, Error>; fn get_billing_phone_number(&self) -> Result<Secret<String>, Error>; fn to_connector_meta<T>(&self) -> Result<T, Error> where T: serde::de::DeserializeOwned; fn is_three_ds(&self) -> bool; fn get_payment_method_token(&self) -> Result<types::PaymentMethodToken, Error>; fn get_customer_id(&self) -> Result<id_type::CustomerId, Error>; fn get_connector_customer_id(&self) -> Result<String, Error>; fn get_preprocessing_id(&self) -> Result<String, Error>; fn get_recurring_mandate_payment_data( &self, ) -> Result<types::RecurringMandatePaymentData, Error>; #[cfg(feature = "payouts")] fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error>; #[cfg(feature = "payouts")] fn get_quote_id(&self) -> Result<String, Error>; fn get_optional_billing(&self) -> Option<&hyperswitch_domain_models::address::Address>; fn get_optional_shipping(&self) -> Option<&hyperswitch_domain_models::address::Address>; fn get_optional_shipping_line1(&self) -> Option<Secret<String>>; fn get_optional_shipping_line2(&self) -> Option<Secret<String>>; fn get_optional_shipping_city(&self) -> Option<String>; fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2>; fn get_optional_shipping_zip(&self) -> Option<Secret<String>>; fn get_optional_shipping_state(&self) -> Option<Secret<String>>; fn get_optional_shipping_first_name(&self) -> Option<Secret<String>>; fn get_optional_shipping_last_name(&self) -> Option<Secret<String>>; fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>>; fn get_optional_shipping_email(&self) -> Option<Email>; fn get_optional_billing_full_name(&self) -> Option<Secret<String>>; fn get_optional_billing_line1(&self) -> Option<Secret<String>>; fn get_optional_billing_line2(&self) -> Option<Secret<String>>; fn get_optional_billing_city(&self) -> Option<String>; fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2>; fn get_optional_billing_zip(&self) -> Option<Secret<String>>; fn get_optional_billing_state(&self) -> Option<Secret<String>>; fn get_optional_billing_first_name(&self) -> Option<Secret<String>>; fn get_optional_billing_last_name(&self) -> Option<Secret<String>>; fn get_optional_billing_phone_number(&self) -> Option<Secret<String>>; fn get_optional_billing_email(&self) -> Option<Email>; } pub trait PaymentResponseRouterData { fn get_attempt_status_for_db_update<F>( &self, payment_data: &PaymentData<F>, ) -> enums::AttemptStatus where F: Clone; } impl<Flow, Request, Response> PaymentResponseRouterData for types::RouterData<Flow, Request, Response> where Request: types::Capturable, { fn get_attempt_status_for_db_update<F>( &self, payment_data: &PaymentData<F>, ) -> enums::AttemptStatus where F: Clone, { match self.status { enums::AttemptStatus::Voided => { if payment_data.payment_intent.amount_captured > Some(MinorUnit::new(0)) { enums::AttemptStatus::PartialCharged } else { self.status } } enums::AttemptStatus::Charged => { let captured_amount = types::Capturable::get_captured_amount(&self.request, payment_data); let total_capturable_amount = payment_data.payment_attempt.get_total_amount(); if Some(total_capturable_amount) == captured_amount.map(MinorUnit::new) { enums::AttemptStatus::Charged } else if captured_amount.is_some() { enums::AttemptStatus::PartialCharged } else { self.status } } _ => self.status, } } } pub const SELECTED_PAYMENT_METHOD: &str = "Selected payment method"; pub fn get_unimplemented_payment_method_error_message(connector: &str) -> String { format!("{} through {}", SELECTED_PAYMENT_METHOD, connector) } impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Response> { fn get_billing(&self) -> Result<&hyperswitch_domain_models::address::Address, Error> { self.address .get_payment_method_billing() .ok_or_else(missing_field_err("billing")) } fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error> { self.address .get_payment_method_billing() .and_then(|a| a.address.as_ref()) .and_then(|ad| ad.country) .ok_or_else(missing_field_err( "payment_method_data.billing.address.country", )) } fn get_billing_phone( &self, ) -> Result<&hyperswitch_domain_models::address::PhoneDetails, Error> { self.address .get_payment_method_billing() .and_then(|a| a.phone.as_ref()) .ok_or_else(missing_field_err("billing.phone")) } fn get_optional_billing(&self) -> Option<&hyperswitch_domain_models::address::Address> { self.address.get_payment_method_billing() } fn get_optional_shipping(&self) -> Option<&hyperswitch_domain_models::address::Address> { self.address.get_shipping() } fn get_optional_shipping_first_name(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.first_name) }) } fn get_optional_shipping_last_name(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.last_name) }) } fn get_optional_shipping_line1(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.line1) }) } fn get_optional_shipping_line2(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.line2) }) } fn get_optional_shipping_city(&self) -> Option<String> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.city) }) } fn get_optional_shipping_state(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.state) }) } fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.country) }) } fn get_optional_shipping_zip(&self) -> Option<Secret<String>> { self.address.get_shipping().and_then(|shipping_address| { shipping_address .clone() .address .and_then(|shipping_details| shipping_details.zip) }) } fn get_optional_shipping_email(&self) -> Option<Email> { self.address .get_shipping() .and_then(|shipping_address| shipping_address.clone().email) } fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>> { self.address .get_shipping() .and_then(|shipping_address| shipping_address.clone().phone) .and_then(|phone_details| phone_details.get_number_with_country_code().ok()) } fn get_description(&self) -> Result<String, Error> { self.description .clone() .ok_or_else(missing_field_err("description")) } fn get_billing_address( &self, ) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error> { self.address .get_payment_method_billing() .as_ref() .and_then(|a| a.address.as_ref()) .ok_or_else(missing_field_err("billing.address")) } fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error> { self.connector_meta_data .clone() .ok_or_else(missing_field_err("connector_meta_data")) } fn get_session_token(&self) -> Result<String, Error> { self.session_token .clone() .ok_or_else(missing_field_err("session_token")) } fn get_billing_first_name(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.first_name.clone()) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.first_name", )) } fn get_billing_full_name(&self) -> Result<Secret<String>, Error> { self.get_optional_billing() .and_then(|billing_details| billing_details.address.as_ref()) .and_then(|billing_address| billing_address.get_optional_full_name()) .ok_or_else(missing_field_err( "payment_method_data.billing.address.first_name", )) } fn get_billing_last_name(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.last_name.clone()) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.last_name", )) } fn get_billing_line1(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.line1.clone()) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.line1", )) } fn get_billing_city(&self) -> Result<String, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.city) }) .ok_or_else(missing_field_err( "payment_method_data.billing.address.city", )) } fn get_billing_email(&self) -> Result<Email, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| billing_address.email.clone()) .ok_or_else(missing_field_err("payment_method_data.billing.email")) } fn get_billing_phone_number(&self) -> Result<Secret<String>, Error> { self.address .get_payment_method_billing() .and_then(|billing_address| billing_address.clone().phone) .map(|phone_details| phone_details.get_number_with_country_code()) .transpose()? .ok_or_else(missing_field_err("payment_method_data.billing.phone")) } fn get_optional_billing_line1(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.line1) }) } fn get_optional_billing_line2(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.line2) }) } fn get_optional_billing_city(&self) -> Option<String> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.city) }) } fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.country) }) } fn get_optional_billing_zip(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.zip) }) } fn get_optional_billing_state(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.state) }) } fn get_optional_billing_first_name(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.first_name) }) } fn get_optional_billing_last_name(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .address .and_then(|billing_details| billing_details.last_name) }) } fn get_optional_billing_phone_number(&self) -> Option<Secret<String>> { self.address .get_payment_method_billing() .and_then(|billing_address| { billing_address .clone() .phone .and_then(|phone_data| phone_data.number) }) } fn get_optional_billing_email(&self) -> Option<Email> { self.address .get_payment_method_billing() .and_then(|billing_address| billing_address.clone().email) } fn to_connector_meta<T>(&self) -> Result<T, Error> where T: serde::de::DeserializeOwned, { self.get_connector_meta()? .parse_value(std::any::type_name::<T>()) .change_context(errors::ConnectorError::NoConnectorMetaData) } fn is_three_ds(&self) -> bool { matches!(self.auth_type, enums::AuthenticationType::ThreeDs) } fn get_shipping_address( &self, ) -> Result<&hyperswitch_domain_models::address::AddressDetails, Error> { self.address .get_shipping() .and_then(|a| a.address.as_ref()) .ok_or_else(missing_field_err("shipping.address")) } fn get_shipping_address_with_phone_number( &self, ) -> Result<&hyperswitch_domain_models::address::Address, Error> { self.address .get_shipping() .ok_or_else(missing_field_err("shipping")) } fn get_payment_method_token(&self) -> Result<types::PaymentMethodToken, Error> { self.payment_method_token .clone() .ok_or_else(missing_field_err("payment_method_token")) } fn get_customer_id(&self) -> Result<id_type::CustomerId, Error> { self.customer_id .to_owned() .ok_or_else(missing_field_err("customer_id")) } fn get_connector_customer_id(&self) -> Result<String, Error> { self.connector_customer .to_owned() .ok_or_else(missing_field_err("connector_customer_id")) } fn get_preprocessing_id(&self) -> Result<String, Error> { self.preprocessing_id .to_owned() .ok_or_else(missing_field_err("preprocessing_id")) } fn get_recurring_mandate_payment_data( &self, ) -> Result<types::RecurringMandatePaymentData, Error> { self.recurring_mandate_payment_data .to_owned() .ok_or_else(missing_field_err("recurring_mandate_payment_data")) } fn get_optional_billing_full_name(&self) -> Option<Secret<String>> { self.get_optional_billing() .and_then(|billing_details| billing_details.address.as_ref()) .and_then(|billing_address| billing_address.get_optional_full_name()) } #[cfg(feature = "payouts")] fn get_payout_method_data(&self) -> Result<api::PayoutMethodData, Error> { self.payout_method_data .to_owned() .ok_or_else(missing_field_err("payout_method_data")) } #[cfg(feature = "payouts")] fn get_quote_id(&self) -> Result<String, Error> { self.quote_id .to_owned() .ok_or_else(missing_field_err("quote_id")) } } pub trait AddressData { fn get_email(&self) -> Result<Email, Error>; fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error>; fn get_optional_country(&self) -> Option<enums::CountryAlpha2>; fn get_optional_full_name(&self) -> Option<Secret<String>>; } impl AddressData for hyperswitch_domain_models::address::Address { fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error> { self.phone .clone() .map(|phone_details| phone_details.get_number_with_country_code()) .transpose()? .ok_or_else(missing_field_err("phone")) } fn get_optional_country(&self) -> Option<enums::CountryAlpha2> { self.address .as_ref() .and_then(|billing_details| billing_details.country) } fn get_optional_full_name(&self) -> Option<Secret<String>> { self.address .as_ref() .and_then(|billing_address| billing_address.get_optional_full_name()) } } pub trait PaymentsPreProcessingData { fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>; fn get_email(&self) -> Result<Email, Error>; fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>; fn get_currency(&self) -> Result<enums::Currency, Error>; fn get_amount(&self) -> Result<i64, Error>; fn get_minor_amount(&self) -> Result<MinorUnit, Error>; fn is_auto_capture(&self) -> Result<bool, Error>; fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; fn get_webhook_url(&self) -> Result<String, Error>; fn get_router_return_url(&self) -> Result<String, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_complete_authorize_url(&self) -> Result<String, Error>; fn connector_mandate_id(&self) -> Option<String>; } impl PaymentsPreProcessingData for types::PaymentsPreProcessingData { fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> { self.payment_method_type .to_owned() .ok_or_else(missing_field_err("payment_method_type")) } fn get_currency(&self) -> Result<enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } fn get_amount(&self) -> Result<i64, Error> { self.amount.ok_or_else(missing_field_err("amount")) } // New minor amount function for amount framework fn get_minor_amount(&self) -> Result<MinorUnit, Error> { self.minor_amount.ok_or_else(missing_field_err("amount")) } fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | None | Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { self.order_details .clone() .ok_or_else(missing_field_err("order_details")) } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url .clone() .ok_or_else(missing_field_err("webhook_url")) } fn get_router_return_url(&self) -> Result<String, Error> { self.router_return_url .clone() .ok_or_else(missing_field_err("return_url")) } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_complete_authorize_url(&self) -> Result<String, Error> { self.complete_authorize_url .clone() .ok_or_else(missing_field_err("complete_authorize_url")) } fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> { self.redirect_response .as_ref() .and_then(|res| res.payload.to_owned()) .ok_or( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.payload", } .into(), ) } fn connector_mandate_id(&self) -> Option<String> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { connector_mandate_ids.get_connector_mandate_id() } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) } } pub trait PaymentsCaptureRequestData { fn is_multiple_capture(&self) -> bool; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_capture_method(&self) -> Option<enums::CaptureMethod>; } impl PaymentsCaptureRequestData for types::PaymentsCaptureData { fn is_multiple_capture(&self) -> bool { self.multiple_capture_data.is_some() } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_capture_method(&self) -> Option<enums::CaptureMethod> { self.capture_method.to_owned() } } pub trait SplitPaymentData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest>; } impl SplitPaymentData for types::PaymentsCaptureData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } impl SplitPaymentData for types::PaymentsAuthorizeData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { self.split_payments.clone() } } impl SplitPaymentData for types::PaymentsSyncData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { self.split_payments.clone() } } impl SplitPaymentData for PaymentsCancelData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } impl SplitPaymentData for types::SetupMandateRequestData { fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> { None } } pub trait RevokeMandateRequestData { fn get_connector_mandate_id(&self) -> Result<String, Error>; } impl RevokeMandateRequestData for types::MandateRevokeRequestData { fn get_connector_mandate_id(&self) -> Result<String, Error> { self.connector_mandate_id .clone() .ok_or_else(missing_field_err("connector_mandate_id")) } } pub trait PaymentsSetupMandateRequestData { fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_email(&self) -> Result<Email, Error>; fn is_card(&self) -> bool; } impl PaymentsSetupMandateRequestData for types::SetupMandateRequestData { fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn is_card(&self) -> bool { matches!(self.payment_method_data, domain::PaymentMethodData::Card(_)) } } pub trait PaymentsAuthorizeRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; fn get_email(&self) -> Result<Email, Error>; fn get_optional_email(&self) -> Option<Email>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; fn get_card(&self) -> Result<domain::Card, Error>; fn connector_mandate_id(&self) -> Option<String>; fn get_optional_network_transaction_id(&self) -> Option<String>; fn is_mandate_payment(&self) -> bool; fn is_cit_mandate_payment(&self) -> bool; fn is_customer_initiated_mandate_payment(&self) -> bool; fn get_webhook_url(&self) -> Result<String, Error>; fn get_router_return_url(&self) -> Result<String, Error>; fn is_wallet(&self) -> bool; fn is_card(&self) -> bool; fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>; fn get_connector_mandate_id(&self) -> Result<String, Error>; fn get_complete_authorize_url(&self) -> Result<String, Error>; fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>>; fn get_original_amount(&self) -> i64; fn get_surcharge_amount(&self) -> Option<i64>; fn get_tax_on_surcharge_amount(&self) -> Option<i64>; fn get_total_surcharge_amount(&self) -> Option<i64>; fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue>; fn get_authentication_data(&self) -> Result<AuthenticationData, Error>; fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>; } pub trait PaymentMethodTokenizationRequestData { fn get_browser_info(&self) -> Result<BrowserInformation, Error>; } impl PaymentMethodTokenizationRequestData for types::PaymentMethodTokenizationData { fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } } impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | None | Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_optional_email(&self) -> Option<Email> { self.email.clone() } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { self.order_details .clone() .ok_or_else(missing_field_err("order_details")) } fn get_card(&self) -> Result<domain::Card, Error> { match self.payment_method_data.clone() { domain::PaymentMethodData::Card(card) => Ok(card), _ => Err(missing_field_err("card")()), } } fn get_complete_authorize_url(&self) -> Result<String, Error> { self.complete_authorize_url .clone() .ok_or_else(missing_field_err("complete_authorize_url")) } fn connector_mandate_id(&self) -> Option<String> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { connector_mandate_ids.get_connector_mandate_id() } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) } fn get_optional_network_transaction_id(&self) -> Option<String> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => { Some(network_transaction_id.clone()) } Some(payments::MandateReferenceId::ConnectorMandateId(_)) | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) | None => None, }) } fn is_mandate_payment(&self) -> bool { ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession)) || self .mandate_id .as_ref() .and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref()) .is_some() } fn is_cit_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession) } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url .clone() .ok_or_else(missing_field_err("webhook_url")) } fn get_router_return_url(&self) -> Result<String, Error> { self.router_return_url .clone() .ok_or_else(missing_field_err("return_url")) } fn is_wallet(&self) -> bool { matches!( self.payment_method_data, domain::PaymentMethodData::Wallet(_) ) } fn is_card(&self) -> bool { matches!(self.payment_method_data, domain::PaymentMethodData::Card(_)) } fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> { self.payment_method_type .to_owned() .ok_or_else(missing_field_err("payment_method_type")) } fn get_connector_mandate_id(&self) -> Result<String, Error> { self.connector_mandate_id() .ok_or_else(missing_field_err("connector_mandate_id")) } fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>> { self.browser_info.clone().and_then(|browser_info| { browser_info .ip_address .map(|ip| Secret::new(ip.to_string())) }) } fn get_original_amount(&self) -> i64 { self.surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.original_amount.get_amount_as_i64()) .unwrap_or(self.amount) } fn get_surcharge_amount(&self) -> Option<i64> { self.surcharge_details .as_ref() .map(|surcharge_details| surcharge_details.surcharge_amount.get_amount_as_i64()) } fn get_tax_on_surcharge_amount(&self) -> Option<i64> { self.surcharge_details.as_ref().map(|surcharge_details| { surcharge_details .tax_on_surcharge_amount .get_amount_as_i64() }) } fn get_total_surcharge_amount(&self) -> Option<i64> { self.surcharge_details.as_ref().map(|surcharge_details| { surcharge_details .get_total_surcharge_amount() .get_amount_as_i64() }) } fn is_customer_initiated_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession) } fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue> { self.metadata.clone().and_then(|meta_data| match meta_data { serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) | serde_json::Value::String(_) | serde_json::Value::Array(_) => None, serde_json::Value::Object(_) => Some(meta_data.into()), }) } fn get_authentication_data(&self) -> Result<AuthenticationData, Error> { self.authentication_data .clone() .ok_or_else(missing_field_err("authentication_data")) } /// Attempts to retrieve the connector mandate reference ID as a `Result<String, Error>`. fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { connector_mandate_ids.get_connector_mandate_request_reference_id() } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) .ok_or_else(missing_field_err("connector_mandate_request_reference_id")) } } pub trait ConnectorCustomerData { fn get_email(&self) -> Result<Email, Error>; } impl ConnectorCustomerData for types::ConnectorCustomerData { fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } } pub trait BrowserInformationData { fn get_accept_header(&self) -> Result<String, Error>; fn get_language(&self) -> Result<String, Error>; fn get_screen_height(&self) -> Result<u32, Error>; fn get_screen_width(&self) -> Result<u32, Error>; fn get_color_depth(&self) -> Result<u8, Error>; fn get_user_agent(&self) -> Result<String, Error>; fn get_time_zone(&self) -> Result<i32, Error>; fn get_java_enabled(&self) -> Result<bool, Error>; fn get_java_script_enabled(&self) -> Result<bool, Error>; fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error>; } impl BrowserInformationData for BrowserInformation { fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error> { let ip_address = self .ip_address .ok_or_else(missing_field_err("browser_info.ip_address"))?; Ok(Secret::new(ip_address.to_string())) } fn get_accept_header(&self) -> Result<String, Error> { self.accept_header .clone() .ok_or_else(missing_field_err("browser_info.accept_header")) } fn get_language(&self) -> Result<String, Error> { self.language .clone() .ok_or_else(missing_field_err("browser_info.language")) } fn get_screen_height(&self) -> Result<u32, Error> { self.screen_height .ok_or_else(missing_field_err("browser_info.screen_height")) } fn get_screen_width(&self) -> Result<u32, Error> { self.screen_width .ok_or_else(missing_field_err("browser_info.screen_width")) } fn get_color_depth(&self) -> Result<u8, Error> { self.color_depth .ok_or_else(missing_field_err("browser_info.color_depth")) } fn get_user_agent(&self) -> Result<String, Error> { self.user_agent .clone() .ok_or_else(missing_field_err("browser_info.user_agent")) } fn get_time_zone(&self) -> Result<i32, Error> { self.time_zone .ok_or_else(missing_field_err("browser_info.time_zone")) } fn get_java_enabled(&self) -> Result<bool, Error> { self.java_enabled .ok_or_else(missing_field_err("browser_info.java_enabled")) } fn get_java_script_enabled(&self) -> Result<bool, Error> { self.java_script_enabled .ok_or_else(missing_field_err("browser_info.java_script_enabled")) } } pub trait PaymentsCompleteAuthorizeRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; fn get_email(&self) -> Result<Email, Error>; fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>; fn get_complete_authorize_url(&self) -> Result<String, Error>; fn is_mandate_payment(&self) -> bool; fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>; fn is_cit_mandate_payment(&self) -> bool; } impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | None | Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } fn get_email(&self) -> Result<Email, Error> { self.email.clone().ok_or_else(missing_field_err("email")) } fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> { self.redirect_response .as_ref() .and_then(|res| res.payload.to_owned()) .ok_or( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "request.redirect_response.payload", } .into(), ) } fn get_complete_authorize_url(&self) -> Result<String, Error> { self.complete_authorize_url .clone() .ok_or_else(missing_field_err("complete_authorize_url")) } fn is_mandate_payment(&self) -> bool { ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession)) || self .mandate_id .as_ref() .and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref()) .is_some() } fn is_cit_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession) } /// Attempts to retrieve the connector mandate reference ID as a `Result<String, Error>`. fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error> { self.mandate_id .as_ref() .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => { connector_mandate_ids.get_connector_mandate_request_reference_id() } Some(payments::MandateReferenceId::NetworkMandateId(_)) | None | Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None, }) .ok_or_else(missing_field_err("connector_mandate_request_reference_id")) } } pub trait PaymentsSyncRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError>; } impl PaymentsSyncRequestData for types::PaymentsSyncData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | None | Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError> { match self.connector_transaction_id.clone() { ResponseId::ConnectorTransactionId(txn_id) => Ok(txn_id), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "connector_transaction_id", }) .attach_printable("Expected connector transaction ID not found") .change_context(errors::ConnectorError::MissingConnectorTransactionID)?, } } } pub trait PaymentsPostSessionTokensRequestData { fn is_auto_capture(&self) -> Result<bool, Error>; } impl PaymentsPostSessionTokensRequestData for types::PaymentsPostSessionTokensData { fn is_auto_capture(&self) -> Result<bool, Error> { match self.capture_method { Some(enums::CaptureMethod::Automatic) | None | Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true), Some(enums::CaptureMethod::Manual) => Ok(false), Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } } #[cfg(feature = "payouts")] pub trait CustomerDetails { fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError>; fn get_customer_name( &self, ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>; fn get_customer_email(&self) -> Result<Email, errors::ConnectorError>; fn get_customer_phone( &self, ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>; fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError>; } #[cfg(feature = "payouts")] impl CustomerDetails for types::CustomerDetails { fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError> { self.customer_id .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_id", }) } fn get_customer_name( &self, ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> { self.name .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_name", }) } fn get_customer_email(&self) -> Result<Email, errors::ConnectorError> { self.email .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_email", }) } fn get_customer_phone( &self, ) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> { self.phone .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_phone", }) } fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError> { self.phone_country_code .clone() .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "customer_phone_country_code", }) } } pub trait PaymentsCancelRequestData { fn get_amount(&self) -> Result<i64, Error>; fn get_currency(&self) -> Result<enums::Currency, Error>; fn get_cancellation_reason(&self) -> Result<String, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; } impl PaymentsCancelRequestData for PaymentsCancelData { fn get_amount(&self) -> Result<i64, Error> { self.amount.ok_or_else(missing_field_err("amount")) } fn get_currency(&self) -> Result<enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } fn get_cancellation_reason(&self) -> Result<String, Error> { self.cancellation_reason .clone() .ok_or_else(missing_field_err("cancellation_reason")) } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } } pub trait RefundsRequestData { fn get_connector_refund_id(&self) -> Result<String, Error>; fn get_webhook_url(&self) -> Result<String, Error>; fn get_browser_info(&self) -> Result<BrowserInformation, Error>; fn get_connector_metadata(&self) -> Result<serde_json::Value, Error>; } impl RefundsRequestData for types::RefundsData { #[track_caller] fn get_connector_refund_id(&self) -> Result<String, Error> { self.connector_refund_id .clone() .get_required_value("connector_refund_id") .change_context(errors::ConnectorError::MissingConnectorTransactionID) } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url .clone() .ok_or_else(missing_field_err("webhook_url")) } fn get_browser_info(&self) -> Result<BrowserInformation, Error> { self.browser_info .clone() .ok_or_else(missing_field_err("browser_info")) } fn get_connector_metadata(&self) -> Result<serde_json::Value, Error> { self.connector_metadata .clone() .ok_or_else(missing_field_err("connector_metadata")) } } #[cfg(feature = "payouts")] pub trait PayoutsData { fn get_transfer_id(&self) -> Result<String, Error>; fn get_customer_details(&self) -> Result<types::CustomerDetails, Error>; fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error>; #[cfg(feature = "payouts")] fn get_payout_type(&self) -> Result<storage_enums::PayoutType, Error>; } #[cfg(feature = "payouts")] impl PayoutsData for types::PayoutsData { fn get_transfer_id(&self) -> Result<String, Error> { self.connector_payout_id .clone() .ok_or_else(missing_field_err("transfer_id")) } fn get_customer_details(&self) -> Result<types::CustomerDetails, Error> { self.customer_details .clone() .ok_or_else(missing_field_err("customer_details")) } fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error> { self.vendor_details .clone() .ok_or_else(missing_field_err("vendor_details")) } #[cfg(feature = "payouts")] fn get_payout_type(&self) -> Result<storage_enums::PayoutType, Error> { self.payout_type .to_owned() .ok_or_else(missing_field_err("payout_type")) } } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayWalletData { #[serde(rename = "type")] pub pm_type: String, pub description: String, pub info: GooglePayPaymentMethodInfo, pub tokenization_data: GpayTokenizationData, } #[derive(Clone, Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayPaymentMethodInfo { pub card_network: String, pub card_details: String, } #[derive(Clone, Debug, serde::Serialize)] pub struct GpayTokenizationData { #[serde(rename = "type")] pub token_type: String, pub token: Secret<String>, } impl From<domain::GooglePayWalletData> for GooglePayWalletData { fn from(data: domain::GooglePayWalletData) -> Self { Self { pm_type: data.pm_type, description: data.description, info: GooglePayPaymentMethodInfo { card_network: data.info.card_network, card_details: data.info.card_details, }, tokenization_data: GpayTokenizationData { token_type: data.tokenization_data.token_type, token: Secret::new(data.tokenization_data.token), }, } } } static CARD_REGEX: Lazy<HashMap<CardIssuer, Result<Regex, regex::Error>>> = Lazy::new(|| { let mut map = HashMap::new(); // Reference: https://gist.github.com/michaelkeevildown/9096cd3aac9029c4e6e05588448a8841 // [#379]: Determine card issuer from card BIN number map.insert(CardIssuer::Master, Regex::new(r"^5[1-5][0-9]{14}$")); map.insert(CardIssuer::AmericanExpress, Regex::new(r"^3[47][0-9]{13}$")); map.insert(CardIssuer::Visa, Regex::new(r"^4[0-9]{12}(?:[0-9]{3})?$")); map.insert(CardIssuer::Discover, Regex::new(r"^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$")); map.insert( CardIssuer::Maestro, Regex::new(r"^(5018|5020|5038|5893|6304|6759|6761|6762|6763)[0-9]{8,15}$"), ); map.insert( CardIssuer::DinersClub, Regex::new(r"^3(?:0[0-5]|[68][0-9])[0-9]{11}$"), ); map.insert( CardIssuer::JCB, Regex::new(r"^(3(?:088|096|112|158|337|5(?:2[89]|[3-8][0-9]))\d{12})$"), ); map.insert(CardIssuer::CarteBlanche, Regex::new(r"^389[0-9]{11}$")); map }); #[derive(Debug, Copy, Clone, strum::Display, Eq, Hash, PartialEq)] pub enum CardIssuer { AmericanExpress, Master, Maestro, Visa, Discover, DinersClub, JCB, CarteBlanche, } pub trait CardData { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>; fn get_card_issuer(&self) -> Result<CardIssuer, Error>; fn get_card_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError>; fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String>; fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String>; fn get_expiry_year_4_digit(&self) -> Secret<String>; fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError>; fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error>; fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error>; } #[cfg(feature = "payouts")] impl CardData for payouts::CardPayout { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.expiry_year.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(), )) } fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.card_number.peek()) } fn get_card_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?; Ok(Secret::new(format!( "{}{}{}", self.expiry_month.peek(), delimiter, year.peek() ))) } fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", year.peek(), delimiter, self.expiry_month.peek() )) } fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", self.expiry_month.peek(), delimiter, year.peek() )) } fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.expiry_year.peek().clone(); if year.len() == 2 { year = format!("20{}", year); } Secret::new(year) } fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.expiry_month.clone().expose(); Ok(Secret::new(format!("{year}{month}"))) } fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { self.expiry_month .peek() .clone() .parse::<i8>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { self.expiry_year .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } } impl CardData for hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.card_exp_year.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(), )) } fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.card_number.peek()) } fn get_card_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?; Ok(Secret::new(format!( "{}{}{}", self.card_exp_month.peek(), delimiter, year.peek() ))) } fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", year.peek(), delimiter, self.card_exp_month.peek() )) } fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", self.card_exp_month.peek(), delimiter, year.peek() )) } fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.card_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{}", year); } Secret::new(year) } fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.card_exp_month.clone().expose(); Ok(Secret::new(format!("{year}{month}"))) } fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { self.card_exp_month .peek() .clone() .parse::<i8>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { self.card_exp_year .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } } impl CardData for domain::Card { fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { let binding = self.card_exp_year.clone(); let year = binding.peek(); Ok(Secret::new( year.get(year.len() - 2..) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_string(), )) } fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.card_number.peek()) } fn get_card_expiry_month_year_2_digit_with_delimiter( &self, delimiter: String, ) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?; Ok(Secret::new(format!( "{}{}{}", self.card_exp_month.peek(), delimiter, year.peek() ))) } fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", year.peek(), delimiter, self.card_exp_month.peek() )) } fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { let year = self.get_expiry_year_4_digit(); Secret::new(format!( "{}{}{}", self.card_exp_month.peek(), delimiter, year.peek() )) } fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.card_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{}", year); } Secret::new(year) } fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { let year = self.get_card_expiry_year_2_digit()?.expose(); let month = self.card_exp_month.clone().expose(); Ok(Secret::new(format!("{year}{month}"))) } fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { self.card_exp_month .peek() .clone() .parse::<i8>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { self.card_exp_year .peek() .clone() .parse::<i32>() .change_context(errors::ConnectorError::ResponseDeserializationFailed) .map(Secret::new) } } #[track_caller] fn get_card_issuer(card_number: &str) -> Result<CardIssuer, Error> { for (k, v) in CARD_REGEX.iter() { let regex: Regex = v .clone() .change_context(errors::ConnectorError::RequestEncodingFailed)?; if regex.is_match(card_number) { return Ok(*k); } } Err(error_stack::Report::new( errors::ConnectorError::NotImplemented("Card Type".into()), )) } pub trait WalletData { fn get_wallet_token(&self) -> Result<Secret<String>, Error>; fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error> where T: serde::de::DeserializeOwned; fn get_encoded_wallet_token(&self) -> Result<String, Error>; } impl WalletData for domain::WalletData { fn get_wallet_token(&self) -> Result<Secret<String>, Error> { match self { Self::GooglePay(data) => Ok(Secret::new(data.tokenization_data.token.clone())), Self::ApplePay(data) => Ok(data.get_applepay_decoded_payment_data()?), Self::PaypalSdk(data) => Ok(Secret::new(data.token.clone())), _ => Err(errors::ConnectorError::InvalidWallet.into()), } } fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error> where T: serde::de::DeserializeOwned, { serde_json::from_str::<T>(self.get_wallet_token()?.peek()) .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name }) } fn get_encoded_wallet_token(&self) -> Result<String, Error> { match self { Self::GooglePay(_) => { let json_token: serde_json::Value = self.get_wallet_token_as_json("Google Pay".to_owned())?; let token_as_vec = serde_json::to_vec(&json_token).change_context( errors::ConnectorError::InvalidWalletToken { wallet_name: "Google Pay".to_string(), }, )?; let encoded_token = consts::BASE64_ENGINE.encode(token_as_vec); Ok(encoded_token) } _ => Err( errors::ConnectorError::NotImplemented("SELECTED PAYMENT METHOD".to_owned()).into(), ), } } } pub trait ApplePay { fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error>; } impl ApplePay for domain::ApplePayWalletData { fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error> { let token = Secret::new( String::from_utf8( consts::BASE64_ENGINE .decode(&self.payment_data) .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })?, ) .change_context(errors::ConnectorError::InvalidWalletToken { wallet_name: "Apple Pay".to_string(), })?, ); Ok(token) } } pub trait ApplePayDecrypt { fn get_expiry_month(&self) -> Result<Secret<String>, Error>; fn get_four_digit_expiry_year(&self) -> Result<Secret<String>, Error>; } impl ApplePayDecrypt for Box<ApplePayPredecryptData> { fn get_four_digit_expiry_year(&self) -> Result<Secret<String>, Error> { Ok(Secret::new(format!( "20{}", self.application_expiration_date .get(0..2) .ok_or(errors::ConnectorError::RequestEncodingFailed)? ))) } fn get_expiry_month(&self) -> Result<Secret<String>, Error> { Ok(Secret::new( self.application_expiration_date .get(2..4) .ok_or(errors::ConnectorError::RequestEncodingFailed)? .to_owned(), )) } } pub trait CryptoData { fn get_pay_currency(&self) -> Result<String, Error>; } impl CryptoData for domain::CryptoData { fn get_pay_currency(&self) -> Result<String, Error> { self.pay_currency .clone() .ok_or_else(missing_field_err("crypto_data.pay_currency")) } } pub trait PhoneDetailsData { fn get_number(&self) -> Result<Secret<String>, Error>; fn get_country_code(&self) -> Result<String, Error>; fn get_number_with_country_code(&self) -> Result<Secret<String>, Error>; fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error>; fn extract_country_code(&self) -> Result<String, Error>; } impl PhoneDetailsData for hyperswitch_domain_models::address::PhoneDetails { fn get_country_code(&self) -> Result<String, Error> { self.country_code .clone() .ok_or_else(missing_field_err("billing.phone.country_code")) } fn extract_country_code(&self) -> Result<String, Error> { self.get_country_code() .map(|cc| cc.trim_start_matches('+').to_string()) } fn get_number(&self) -> Result<Secret<String>, Error> { self.number .clone() .ok_or_else(missing_field_err("billing.phone.number")) } fn get_number_with_country_code(&self) -> Result<Secret<String>, Error> { let number = self.get_number()?; let country_code = self.get_country_code()?; Ok(Secret::new(format!("{}{}", country_code, number.peek()))) } fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error> { let number = self.get_number()?; let country_code = self.get_country_code()?; let number_without_plus = country_code.trim_start_matches('+'); Ok(Secret::new(format!( "{}#{}", number_without_plus, number.peek() ))) } } pub trait AddressDetailsData { fn get_first_name(&self) -> Result<&Secret<String>, Error>; fn get_last_name(&self) -> Result<&Secret<String>, Error>; fn get_full_name(&self) -> Result<Secret<String>, Error>; fn get_line1(&self) -> Result<&Secret<String>, Error>; fn get_city(&self) -> Result<&String, Error>; fn get_line2(&self) -> Result<&Secret<String>, Error>; fn get_state(&self) -> Result<&Secret<String>, Error>; fn get_zip(&self) -> Result<&Secret<String>, Error>; fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error>; fn get_combined_address_line(&self) -> Result<Secret<String>, Error>; fn get_optional_line2(&self) -> Option<Secret<String>>; fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2>; } impl AddressDetailsData for hyperswitch_domain_models::address::AddressDetails { fn get_first_name(&self) -> Result<&Secret<String>, Error> { self.first_name .as_ref() .ok_or_else(missing_field_err("address.first_name")) } fn get_last_name(&self) -> Result<&Secret<String>, Error> { self.last_name .as_ref() .ok_or_else(missing_field_err("address.last_name")) } fn get_full_name(&self) -> Result<Secret<String>, Error> { let first_name = self.get_first_name()?.peek().to_owned(); let last_name = self .get_last_name() .ok() .cloned() .unwrap_or(Secret::new("".to_string())); let last_name = last_name.peek(); let full_name = format!("{} {}", first_name, last_name).trim().to_string(); Ok(Secret::new(full_name)) } fn get_line1(&self) -> Result<&Secret<String>, Error> { self.line1 .as_ref() .ok_or_else(missing_field_err("address.line1")) } fn get_city(&self) -> Result<&String, Error> { self.city .as_ref() .ok_or_else(missing_field_err("address.city")) } fn get_state(&self) -> Result<&Secret<String>, Error> { self.state .as_ref() .ok_or_else(missing_field_err("address.state")) } fn get_line2(&self) -> Result<&Secret<String>, Error> { self.line2 .as_ref() .ok_or_else(missing_field_err("address.line2")) } fn get_zip(&self) -> Result<&Secret<String>, Error> { self.zip .as_ref() .ok_or_else(missing_field_err("address.zip")) } fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error> { self.country .as_ref() .ok_or_else(missing_field_err("address.country")) } fn get_combined_address_line(&self) -> Result<Secret<String>, Error> { Ok(Secret::new(format!( "{},{}", self.get_line1()?.peek(), self.get_line2()?.peek() ))) } fn get_optional_line2(&self) -> Option<Secret<String>> { self.line2.clone() } fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2> { self.country } } pub trait MandateData { fn get_end_date(&self, format: date_time::DateFormat) -> Result<String, Error>; fn get_metadata(&self) -> Result<pii::SecretSerdeValue, Error>; } impl MandateData for payments::MandateAmountData { fn get_end_date(&self, format: date_time::DateFormat) -> Result<String, Error> { let date = self.end_date.ok_or_else(missing_field_err( "mandate_data.mandate_type.{multi_use|single_use}.end_date", ))?; date_time::format_date(date, format) .change_context(errors::ConnectorError::DateFormattingFailed) } fn get_metadata(&self) -> Result<pii::SecretSerdeValue, Error> { self.metadata.clone().ok_or_else(missing_field_err( "mandate_data.mandate_type.{multi_use|single_use}.metadata", )) } } pub trait RecurringMandateData { fn get_original_payment_amount(&self) -> Result<i64, Error>; fn get_original_payment_currency(&self) -> Result<enums::Currency, Error>; } impl RecurringMandateData for types::RecurringMandatePaymentData { fn get_original_payment_amount(&self) -> Result<i64, Error> { self.original_payment_authorized_amount .ok_or_else(missing_field_err("original_payment_authorized_amount")) } fn get_original_payment_currency(&self) -> Result<enums::Currency, Error> { self.original_payment_authorized_currency .ok_or_else(missing_field_err("original_payment_authorized_currency")) } } pub trait MandateReferenceData { fn get_connector_mandate_id(&self) -> Result<String, Error>; } impl MandateReferenceData for payments::ConnectorMandateReferenceId { fn get_connector_mandate_id(&self) -> Result<String, Error> { self.get_connector_mandate_id() .ok_or_else(missing_field_err("mandate_id")) } } pub fn get_header_key_value<'a>( key: &str, headers: &'a actix_web::http::header::HeaderMap, ) -> CustomResult<&'a str, errors::ConnectorError> { get_header_field(headers.get(key)) } pub fn get_http_header<'a>( key: &str, headers: &'a http::HeaderMap, ) -> CustomResult<&'a str, errors::ConnectorError> { get_header_field(headers.get(key)) } fn get_header_field( field: Option<&http::HeaderValue>, ) -> CustomResult<&str, errors::ConnectorError> { field .map(|header_value| { header_value .to_str() .change_context(errors::ConnectorError::WebhookSignatureNotFound) }) .ok_or(report!( errors::ConnectorError::WebhookSourceVerificationFailed ))? } pub fn to_boolean(string: String) -> bool { let str = string.as_str(); match str { "true" => true, "false" => false, "yes" => true, "no" => false, _ => false, } } pub fn get_connector_meta( connector_meta: Option<serde_json::Value>, ) -> Result<serde_json::Value, Error> { connector_meta.ok_or_else(missing_field_err("connector_meta_data")) } pub fn to_connector_meta<T>(connector_meta: Option<serde_json::Value>) -> Result<T, Error> where T: serde::de::DeserializeOwned, { let json = connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?; json.parse_value(std::any::type_name::<T>()).switch() } pub fn to_connector_meta_from_secret<T>( connector_meta: Option<Secret<serde_json::Value>>, ) -> Result<T, Error> where T: serde::de::DeserializeOwned, { let connector_meta_secret = connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?; let json = connector_meta_secret.expose(); json.parse_value(std::any::type_name::<T>()).switch() } pub fn base64_decode(data: String) -> Result<Vec<u8>, Error> { consts::BASE64_ENGINE .decode(data) .change_context(errors::ConnectorError::ResponseDeserializationFailed) } pub fn to_currency_base_unit_from_optional_amount( amount: Option<i64>, currency: enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { match amount { Some(a) => to_currency_base_unit(a, currency), _ => Err(errors::ConnectorError::MissingRequiredField { field_name: "amount", } .into()), } } pub fn get_amount_as_string( currency_unit: &api::CurrencyUnit, amount: i64, currency: enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { let amount = match currency_unit { api::CurrencyUnit::Minor => amount.to_string(), api::CurrencyUnit::Base => to_currency_base_unit(amount, currency)?, }; Ok(amount) } pub fn get_amount_as_f64( currency_unit: &api::CurrencyUnit, amount: i64, currency: enums::Currency, ) -> Result<f64, error_stack::Report<errors::ConnectorError>> { let amount = match currency_unit { api::CurrencyUnit::Base => to_currency_base_unit_asf64(amount, currency)?, api::CurrencyUnit::Minor => u32::try_from(amount) .change_context(errors::ConnectorError::ParsingFailed)? .into(), }; Ok(amount) } pub fn to_currency_base_unit( amount: i64, currency: enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { currency .to_currency_base_unit(amount) .change_context(errors::ConnectorError::ParsingFailed) } pub fn to_currency_lower_unit( amount: String, currency: enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { currency .to_currency_lower_unit(amount) .change_context(errors::ConnectorError::ResponseHandlingFailed) } pub fn construct_not_implemented_error_report( capture_method: enums::CaptureMethod, connector_name: &str, ) -> error_stack::Report<errors::ConnectorError> { errors::ConnectorError::NotImplemented(format!("{} for {}", capture_method, connector_name)) .into() } pub fn construct_not_supported_error_report( capture_method: enums::CaptureMethod, connector_name: &'static str, ) -> error_stack::Report<errors::ConnectorError> { errors::ConnectorError::NotSupported { message: capture_method.to_string(), connector: connector_name, } .into() } pub fn to_currency_base_unit_with_zero_decimal_check( amount: i64, currency: enums::Currency, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { currency .to_currency_base_unit_with_zero_decimal_check(amount) .change_context(errors::ConnectorError::RequestEncodingFailed) } pub fn to_currency_base_unit_asf64( amount: i64, currency: enums::Currency, ) -> Result<f64, error_stack::Report<errors::ConnectorError>> { currency .to_currency_base_unit_asf64(amount) .change_context(errors::ConnectorError::ParsingFailed) } pub fn str_to_f32<S>(value: &str, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let float_value = value.parse::<f64>().map_err(|_| { serde::ser::Error::custom("Invalid string, cannot be converted to float value") })?; serializer.serialize_f64(float_value) } pub fn collect_values_by_removing_signature( value: &serde_json::Value, signature: &String, ) -> Vec<String> { match value { serde_json::Value::Null => vec!["null".to_owned()], serde_json::Value::Bool(b) => vec![b.to_string()], serde_json::Value::Number(n) => match n.as_f64() { Some(f) => vec![format!("{f:.2}")], None => vec![n.to_string()], }, serde_json::Value::String(s) => { if signature == s { vec![] } else { vec![s.clone()] } } serde_json::Value::Array(arr) => arr .iter() .flat_map(|v| collect_values_by_removing_signature(v, signature)) .collect(), serde_json::Value::Object(obj) => obj .values() .flat_map(|v| collect_values_by_removing_signature(v, signature)) .collect(), } } pub fn collect_and_sort_values_by_removing_signature( value: &serde_json::Value, signature: &String, ) -> Vec<String> { let mut values = collect_values_by_removing_signature(value, signature); values.sort(); values } #[inline] pub fn get_webhook_merchant_secret_key(connector_label: &str, merchant_id: &str) -> String { format!("whsec_verification_{connector_label}_{merchant_id}") } impl ForeignTryFrom<String> for UsStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "UsStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => { let binding = value.as_str().to_lowercase(); let state = binding.as_str(); match state { "alabama" => Ok(Self::AL), "alaska" => Ok(Self::AK), "american samoa" => Ok(Self::AS), "arizona" => Ok(Self::AZ), "arkansas" => Ok(Self::AR), "california" => Ok(Self::CA), "colorado" => Ok(Self::CO), "connecticut" => Ok(Self::CT), "delaware" => Ok(Self::DE), "district of columbia" | "columbia" => Ok(Self::DC), "federated states of micronesia" | "micronesia" => Ok(Self::FM), "florida" => Ok(Self::FL), "georgia" => Ok(Self::GA), "guam" => Ok(Self::GU), "hawaii" => Ok(Self::HI), "idaho" => Ok(Self::ID), "illinois" => Ok(Self::IL), "indiana" => Ok(Self::IN), "iowa" => Ok(Self::IA), "kansas" => Ok(Self::KS), "kentucky" => Ok(Self::KY), "louisiana" => Ok(Self::LA), "maine" => Ok(Self::ME), "marshall islands" => Ok(Self::MH), "maryland" => Ok(Self::MD), "massachusetts" => Ok(Self::MA), "michigan" => Ok(Self::MI), "minnesota" => Ok(Self::MN), "mississippi" => Ok(Self::MS), "missouri" => Ok(Self::MO), "montana" => Ok(Self::MT), "nebraska" => Ok(Self::NE), "nevada" => Ok(Self::NV), "new hampshire" => Ok(Self::NH), "new jersey" => Ok(Self::NJ), "new mexico" => Ok(Self::NM), "new york" => Ok(Self::NY), "north carolina" => Ok(Self::NC), "north dakota" => Ok(Self::ND), "northern mariana islands" => Ok(Self::MP), "ohio" => Ok(Self::OH), "oklahoma" => Ok(Self::OK), "oregon" => Ok(Self::OR), "palau" => Ok(Self::PW), "pennsylvania" => Ok(Self::PA), "puerto rico" => Ok(Self::PR), "rhode island" => Ok(Self::RI), "south carolina" => Ok(Self::SC), "south dakota" => Ok(Self::SD), "tennessee" => Ok(Self::TN), "texas" => Ok(Self::TX), "utah" => Ok(Self::UT), "vermont" => Ok(Self::VT), "virgin islands" => Ok(Self::VI), "virginia" => Ok(Self::VA), "washington" => Ok(Self::WA), "west virginia" => Ok(Self::WV), "wisconsin" => Ok(Self::WI), "wyoming" => Ok(Self::WY), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } } } impl ForeignTryFrom<String> for CanadaStatesAbbreviation { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "CanadaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => { let binding = value.as_str().to_lowercase(); let state = binding.as_str(); match state { "alberta" => Ok(Self::AB), "british columbia" => Ok(Self::BC), "manitoba" => Ok(Self::MB), "new brunswick" => Ok(Self::NB), "newfoundland and labrador" | "newfoundland & labrador" => Ok(Self::NL), "northwest territories" => Ok(Self::NT), "nova scotia" => Ok(Self::NS), "nunavut" => Ok(Self::NU), "ontario" => Ok(Self::ON), "prince edward island" => Ok(Self::PE), "quebec" => Ok(Self::QC), "saskatchewan" => Ok(Self::SK), "yukon" => Ok(Self::YT), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } } } pub trait ConnectorErrorTypeMapping { fn get_connector_error_type( &self, _error_code: String, _error_message: String, ) -> ConnectorErrorType { ConnectorErrorType::UnknownError } } #[derive(Clone, Debug, PartialEq, Eq)] pub struct ErrorCodeAndMessage { pub error_code: String, pub error_message: String, } #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] //Priority of connector_error_type pub enum ConnectorErrorType { UserError = 2, BusinessError = 3, TechnicalError = 4, UnknownError = 1, } //Gets the list of error_code_and_message, sorts based on the priority of error_type and gives most prior error // This could be used in connectors where we get list of error_messages and have to choose one error_message pub fn get_error_code_error_message_based_on_priority( connector: impl ConnectorErrorTypeMapping, error_list: Vec<ErrorCodeAndMessage>, ) -> Option<ErrorCodeAndMessage> { let error_type_list = error_list .iter() .map(|error| { connector .get_connector_error_type(error.error_code.clone(), error.error_message.clone()) }) .collect::<Vec<ConnectorErrorType>>(); let mut error_zip_list = error_list .iter() .zip(error_type_list.iter()) .collect::<Vec<(&ErrorCodeAndMessage, &ConnectorErrorType)>>(); error_zip_list.sort_by_key(|&(_, error_type)| error_type); error_zip_list .first() .map(|&(error_code_message, _)| error_code_message) .cloned() } pub trait MultipleCaptureSyncResponse { fn get_connector_capture_id(&self) -> String; fn get_capture_attempt_status(&self) -> enums::AttemptStatus; fn is_capture_response(&self) -> bool; fn get_connector_reference_id(&self) -> Option<String> { None } fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>>; } pub fn construct_captures_response_hashmap<T>( capture_sync_response_list: Vec<T>, ) -> CustomResult<HashMap<String, types::CaptureSyncResponse>, errors::ConnectorError> where T: MultipleCaptureSyncResponse, { let mut hashmap = HashMap::new(); for capture_sync_response in capture_sync_response_list { let connector_capture_id = capture_sync_response.get_connector_capture_id(); if capture_sync_response.is_capture_response() { hashmap.insert( connector_capture_id.clone(), types::CaptureSyncResponse::Success { resource_id: ResponseId::ConnectorTransactionId(connector_capture_id), status: capture_sync_response.get_capture_attempt_status(), connector_response_reference_id: capture_sync_response .get_connector_reference_id(), amount: capture_sync_response .get_amount_captured() .change_context(errors::ConnectorError::AmountConversionFailed) .attach_printable( "failed to convert back captured response amount to minor unit", )?, }, ); } } Ok(hashmap) } pub fn is_manual_capture(capture_method: Option<enums::CaptureMethod>) -> bool { capture_method == Some(enums::CaptureMethod::Manual) || capture_method == Some(enums::CaptureMethod::ManualMultiple) } pub fn generate_random_bytes(length: usize) -> Vec<u8> { // returns random bytes of length n let mut rng = rand::thread_rng(); (0..length).map(|_| rand::Rng::gen(&mut rng)).collect() } pub fn validate_currency( request_currency: types::storage::enums::Currency, merchant_config_currency: Option<types::storage::enums::Currency>, ) -> Result<(), errors::ConnectorError> { let merchant_config_currency = merchant_config_currency.ok_or(errors::ConnectorError::NoConnectorMetaData)?; if request_currency != merchant_config_currency { Err(errors::ConnectorError::NotSupported { message: format!( "currency {} is not supported for this merchant account", request_currency ), connector: "Braintree", })? } Ok(()) } pub fn get_timestamp_in_milliseconds(datetime: &PrimitiveDateTime) -> i64 { let utc_datetime = datetime.assume_utc(); utc_datetime.unix_timestamp() * 1000 } #[cfg(feature = "frm")] pub trait FraudCheckSaleRequest { fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; } #[cfg(feature = "frm")] impl FraudCheckSaleRequest for fraud_check::FraudCheckSaleData { fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { self.order_details .clone() .ok_or_else(missing_field_err("order_details")) } } #[cfg(feature = "frm")] pub trait FraudCheckCheckoutRequest { fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>; } #[cfg(feature = "frm")] impl FraudCheckCheckoutRequest for fraud_check::FraudCheckCheckoutData { fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> { self.order_details .clone() .ok_or_else(missing_field_err("order_details")) } } #[cfg(feature = "frm")] pub trait FraudCheckTransactionRequest { fn get_currency(&self) -> Result<storage_enums::Currency, Error>; } #[cfg(feature = "frm")] impl FraudCheckTransactionRequest for fraud_check::FraudCheckTransactionData { fn get_currency(&self) -> Result<storage_enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } } #[cfg(feature = "frm")] pub trait FraudCheckRecordReturnRequest { fn get_currency(&self) -> Result<storage_enums::Currency, Error>; } #[cfg(feature = "frm")] impl FraudCheckRecordReturnRequest for fraud_check::FraudCheckRecordReturnData { fn get_currency(&self) -> Result<storage_enums::Currency, Error> { self.currency.ok_or_else(missing_field_err("currency")) } } #[cfg(feature = "v1")] pub trait PaymentsAttemptData { fn get_browser_info(&self) -> Result<BrowserInformation, error_stack::Report<ApiErrorResponse>>; } #[cfg(feature = "v1")] impl PaymentsAttemptData for PaymentAttempt { fn get_browser_info( &self, ) -> Result<BrowserInformation, error_stack::Report<ApiErrorResponse>> { self.browser_info .clone() .ok_or(ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })? .parse_value::<BrowserInformation>("BrowserInformation") .change_context(ApiErrorResponse::InvalidDataValue { field_name: "browser_info", }) } } #[cfg(feature = "frm")] pub trait FrmTransactionRouterDataRequest { fn is_payment_successful(&self) -> Option<bool>; } #[cfg(feature = "frm")] impl FrmTransactionRouterDataRequest for fraud_check::FrmTransactionRouterData { fn is_payment_successful(&self) -> Option<bool> { match self.status { storage_enums::AttemptStatus::AuthenticationFailed | storage_enums::AttemptStatus::RouterDeclined | storage_enums::AttemptStatus::AuthorizationFailed | storage_enums::AttemptStatus::Voided | storage_enums::AttemptStatus::CaptureFailed | storage_enums::AttemptStatus::Failure | storage_enums::AttemptStatus::AutoRefunded => Some(false), storage_enums::AttemptStatus::AuthenticationSuccessful | storage_enums::AttemptStatus::PartialChargedAndChargeable | storage_enums::AttemptStatus::Authorized | storage_enums::AttemptStatus::Charged => Some(true), storage_enums::AttemptStatus::Started | storage_enums::AttemptStatus::AuthenticationPending | storage_enums::AttemptStatus::Authorizing | storage_enums::AttemptStatus::CodInitiated | storage_enums::AttemptStatus::VoidInitiated | storage_enums::AttemptStatus::CaptureInitiated | storage_enums::AttemptStatus::VoidFailed | storage_enums::AttemptStatus::PartialCharged | storage_enums::AttemptStatus::Unresolved | storage_enums::AttemptStatus::Pending | storage_enums::AttemptStatus::PaymentMethodAwaited | storage_enums::AttemptStatus::ConfirmationAwaited | storage_enums::AttemptStatus::DeviceDataCollectionPending => None, } } } pub fn is_payment_failure(status: enums::AttemptStatus) -> bool { match status { common_enums::AttemptStatus::AuthenticationFailed | common_enums::AttemptStatus::AuthorizationFailed | common_enums::AttemptStatus::CaptureFailed | common_enums::AttemptStatus::VoidFailed | common_enums::AttemptStatus::Failure => true, common_enums::AttemptStatus::Started | common_enums::AttemptStatus::RouterDeclined | common_enums::AttemptStatus::AuthenticationPending | common_enums::AttemptStatus::AuthenticationSuccessful | common_enums::AttemptStatus::Authorized | common_enums::AttemptStatus::Charged | common_enums::AttemptStatus::Authorizing | common_enums::AttemptStatus::CodInitiated | common_enums::AttemptStatus::Voided | common_enums::AttemptStatus::VoidInitiated | common_enums::AttemptStatus::CaptureInitiated | common_enums::AttemptStatus::AutoRefunded | common_enums::AttemptStatus::PartialCharged | common_enums::AttemptStatus::PartialChargedAndChargeable | common_enums::AttemptStatus::Unresolved | common_enums::AttemptStatus::Pending | common_enums::AttemptStatus::PaymentMethodAwaited | common_enums::AttemptStatus::ConfirmationAwaited | common_enums::AttemptStatus::DeviceDataCollectionPending => false, } } pub fn is_refund_failure(status: enums::RefundStatus) -> bool { match status { common_enums::RefundStatus::Failure | common_enums::RefundStatus::TransactionFailure => { true } common_enums::RefundStatus::ManualReview | common_enums::RefundStatus::Pending | common_enums::RefundStatus::Success => false, } } impl ForeignFrom<( Option<String>, Option<String>, Option<String>, u16, Option<enums::AttemptStatus>, Option<String>, )> for types::ErrorResponse { fn foreign_from( (code, message, reason, http_code, attempt_status, connector_transaction_id): ( Option<String>, Option<String>, Option<String>, u16, Option<enums::AttemptStatus>, Option<String>, ), ) -> Self { Self { code: code.unwrap_or(consts::NO_ERROR_CODE.to_string()), message: message .clone() .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason, status_code: http_code, attempt_status, connector_transaction_id, network_advice_code: None, network_decline_code: None, network_error_message: None, } } } pub fn get_card_details( payment_method_data: domain::PaymentMethodData, connector_name: &'static str, ) -> Result<domain::payments::Card, errors::ConnectorError> { match payment_method_data { domain::PaymentMethodData::Card(details) => Ok(details), _ => Err(errors::ConnectorError::NotSupported { message: SELECTED_PAYMENT_METHOD.to_string(), connector: connector_name, })?, } } #[cfg(test)] mod error_code_error_message_tests { #![allow(clippy::unwrap_used)] use super::*; struct TestConnector; impl ConnectorErrorTypeMapping for TestConnector { fn get_connector_error_type( &self, error_code: String, error_message: String, ) -> ConnectorErrorType { match (error_code.as_str(), error_message.as_str()) { ("01", "INVALID_MERCHANT") => ConnectorErrorType::BusinessError, ("03", "INVALID_CVV") => ConnectorErrorType::UserError, ("04", "04") => ConnectorErrorType::TechnicalError, _ => ConnectorErrorType::UnknownError, } } } #[test] fn test_get_error_code_error_message_based_on_priority() { let error_code_message_list_unknown = vec![ ErrorCodeAndMessage { error_code: "01".to_string(), error_message: "INVALID_MERCHANT".to_string(), }, ErrorCodeAndMessage { error_code: "05".to_string(), error_message: "05".to_string(), }, ErrorCodeAndMessage { error_code: "03".to_string(), error_message: "INVALID_CVV".to_string(), }, ErrorCodeAndMessage { error_code: "04".to_string(), error_message: "04".to_string(), }, ]; let error_code_message_list_user = vec![ ErrorCodeAndMessage { error_code: "01".to_string(), error_message: "INVALID_MERCHANT".to_string(), }, ErrorCodeAndMessage { error_code: "03".to_string(), error_message: "INVALID_CVV".to_string(), }, ]; let error_code_error_message_unknown = get_error_code_error_message_based_on_priority( TestConnector, error_code_message_list_unknown, ); let error_code_error_message_user = get_error_code_error_message_based_on_priority( TestConnector, error_code_message_list_user, ); let error_code_error_message_none = get_error_code_error_message_based_on_priority(TestConnector, vec![]); assert_eq!( error_code_error_message_unknown, Some(ErrorCodeAndMessage { error_code: "05".to_string(), error_message: "05".to_string(), }) ); assert_eq!( error_code_error_message_user, Some(ErrorCodeAndMessage { error_code: "03".to_string(), error_message: "INVALID_CVV".to_string(), }) ); assert_eq!(error_code_error_message_none, None); } } pub fn is_mandate_supported( selected_pmd: domain::payments::PaymentMethodData, payment_method_type: Option<types::storage::enums::PaymentMethodType>, mandate_implemented_pmds: HashSet<PaymentMethodDataType>, connector: &'static str, ) -> Result<(), Error> { if mandate_implemented_pmds.contains(&PaymentMethodDataType::from(selected_pmd.clone())) { Ok(()) } else { match payment_method_type { Some(pm_type) => Err(errors::ConnectorError::NotSupported { message: format!("{} mandate payment", pm_type), connector, } .into()), None => Err(errors::ConnectorError::NotSupported { message: " mandate payment".to_string(), connector, } .into()), } } } #[derive(Debug, strum::Display, Eq, PartialEq, Hash)] pub enum PaymentMethodDataType { Card, Knet, Benefit, MomoAtm, CardRedirect, AliPayQr, AliPayRedirect, AliPayHkRedirect, AmazonPayRedirect, MomoRedirect, KakaoPayRedirect, GoPayRedirect, GcashRedirect, ApplePay, ApplePayRedirect, ApplePayThirdPartySdk, DanaRedirect, DuitNow, GooglePay, GooglePayRedirect, GooglePayThirdPartySdk, MbWayRedirect, MobilePayRedirect, PaypalRedirect, PaypalSdk, Paze, SamsungPay, TwintRedirect, VippsRedirect, TouchNGoRedirect, WeChatPayRedirect, WeChatPayQr, CashappQr, SwishQr, KlarnaRedirect, KlarnaSdk, AffirmRedirect, AfterpayClearpayRedirect, PayBrightRedirect, WalleyRedirect, AlmaRedirect, AtomeRedirect, BancontactCard, Bizum, Blik, Eft, Eps, Giropay, Ideal, Interac, LocalBankRedirect, OnlineBankingCzechRepublic, OnlineBankingFinland, OnlineBankingPoland, OnlineBankingSlovakia, OpenBankingUk, Przelewy24, Sofort, Trustly, OnlineBankingFpx, OnlineBankingThailand, AchBankDebit, SepaBankDebit, BecsBankDebit, BacsBankDebit, AchBankTransfer, SepaBankTransfer, BacsBankTransfer, MultibancoBankTransfer, PermataBankTransfer, BcaBankTransfer, BniVaBankTransfer, BriVaBankTransfer, CimbVaBankTransfer, DanamonVaBankTransfer, MandiriVaBankTransfer, Pix, Pse, Crypto, MandatePayment, Reward, Upi, Boleto, Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart, Indomaret, Oxxo, SevenEleven, Lawson, MiniStop, FamilyMart, Seicomart, PayEasy, Givex, PaySafeCar, CardToken, LocalBankTransfer, Mifinity, Fps, PromptPay, VietQr, OpenBanking, NetworkToken, DirectCarrierBilling, InstantBankTransfer, } impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { fn from(pm_data: domain::payments::PaymentMethodData) -> Self { match pm_data { domain::payments::PaymentMethodData::Card(_) => Self::Card, domain::payments::PaymentMethodData::NetworkToken(_) => Self::NetworkToken, domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Self::Card, domain::payments::PaymentMethodData::CardRedirect(card_redirect_data) => { match card_redirect_data { domain::CardRedirectData::Knet {} => Self::Knet, domain::payments::CardRedirectData::Benefit {} => Self::Benefit, domain::payments::CardRedirectData::MomoAtm {} => Self::MomoAtm, domain::payments::CardRedirectData::CardRedirect {} => Self::CardRedirect, } } domain::payments::PaymentMethodData::Wallet(wallet_data) => match wallet_data { domain::payments::WalletData::AliPayQr(_) => Self::AliPayQr, domain::payments::WalletData::AliPayRedirect(_) => Self::AliPayRedirect, domain::payments::WalletData::AliPayHkRedirect(_) => Self::AliPayHkRedirect, domain::payments::WalletData::AmazonPayRedirect(_) => Self::AmazonPayRedirect, domain::payments::WalletData::MomoRedirect(_) => Self::MomoRedirect, domain::payments::WalletData::KakaoPayRedirect(_) => Self::KakaoPayRedirect, domain::payments::WalletData::GoPayRedirect(_) => Self::GoPayRedirect, domain::payments::WalletData::GcashRedirect(_) => Self::GcashRedirect, domain::payments::WalletData::ApplePay(_) => Self::ApplePay, domain::payments::WalletData::ApplePayRedirect(_) => Self::ApplePayRedirect, domain::payments::WalletData::ApplePayThirdPartySdk(_) => { Self::ApplePayThirdPartySdk } domain::payments::WalletData::DanaRedirect {} => Self::DanaRedirect, domain::payments::WalletData::GooglePay(_) => Self::GooglePay, domain::payments::WalletData::GooglePayRedirect(_) => Self::GooglePayRedirect, domain::payments::WalletData::GooglePayThirdPartySdk(_) => { Self::GooglePayThirdPartySdk } domain::payments::WalletData::MbWayRedirect(_) => Self::MbWayRedirect, domain::payments::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect, domain::payments::WalletData::PaypalRedirect(_) => Self::PaypalRedirect, domain::payments::WalletData::PaypalSdk(_) => Self::PaypalSdk, domain::payments::WalletData::Paze(_) => Self::Paze, domain::payments::WalletData::SamsungPay(_) => Self::SamsungPay, domain::payments::WalletData::TwintRedirect {} => Self::TwintRedirect, domain::payments::WalletData::VippsRedirect {} => Self::VippsRedirect, domain::payments::WalletData::TouchNGoRedirect(_) => Self::TouchNGoRedirect, domain::payments::WalletData::WeChatPayRedirect(_) => Self::WeChatPayRedirect, domain::payments::WalletData::WeChatPayQr(_) => Self::WeChatPayQr, domain::payments::WalletData::CashappQr(_) => Self::CashappQr, domain::payments::WalletData::SwishQr(_) => Self::SwishQr, domain::payments::WalletData::Mifinity(_) => Self::Mifinity, }, domain::payments::PaymentMethodData::PayLater(pay_later_data) => match pay_later_data { domain::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect, domain::payments::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk, domain::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect, domain::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { Self::AfterpayClearpayRedirect } domain::payments::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect, domain::payments::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect, domain::payments::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect, domain::payments::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect, }, domain::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => { match bank_redirect_data { domain::payments::BankRedirectData::BancontactCard { .. } => { Self::BancontactCard } domain::payments::BankRedirectData::Bizum {} => Self::Bizum, domain::payments::BankRedirectData::Blik { .. } => Self::Blik, domain::payments::BankRedirectData::Eft { .. } => Self::Eft, domain::payments::BankRedirectData::Eps { .. } => Self::Eps, domain::payments::BankRedirectData::Giropay { .. } => Self::Giropay, domain::payments::BankRedirectData::Ideal { .. } => Self::Ideal, domain::payments::BankRedirectData::Interac { .. } => Self::Interac, domain::payments::BankRedirectData::OnlineBankingCzechRepublic { .. } => { Self::OnlineBankingCzechRepublic } domain::payments::BankRedirectData::OnlineBankingFinland { .. } => { Self::OnlineBankingFinland } domain::payments::BankRedirectData::OnlineBankingPoland { .. } => { Self::OnlineBankingPoland } domain::payments::BankRedirectData::OnlineBankingSlovakia { .. } => { Self::OnlineBankingSlovakia } domain::payments::BankRedirectData::OpenBankingUk { .. } => Self::OpenBankingUk, domain::payments::BankRedirectData::Przelewy24 { .. } => Self::Przelewy24, domain::payments::BankRedirectData::Sofort { .. } => Self::Sofort, domain::payments::BankRedirectData::Trustly { .. } => Self::Trustly, domain::payments::BankRedirectData::OnlineBankingFpx { .. } => { Self::OnlineBankingFpx } domain::payments::BankRedirectData::OnlineBankingThailand { .. } => { Self::OnlineBankingThailand } domain::payments::BankRedirectData::LocalBankRedirect { } => { Self::LocalBankRedirect } } } domain::payments::PaymentMethodData::BankDebit(bank_debit_data) => { match bank_debit_data { domain::payments::BankDebitData::AchBankDebit { .. } => Self::AchBankDebit, domain::payments::BankDebitData::SepaBankDebit { .. } => Self::SepaBankDebit, domain::payments::BankDebitData::BecsBankDebit { .. } => Self::BecsBankDebit, domain::payments::BankDebitData::BacsBankDebit { .. } => Self::BacsBankDebit, } } domain::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => { match *bank_transfer_data { domain::payments::BankTransferData::AchBankTransfer { .. } => { Self::AchBankTransfer } domain::payments::BankTransferData::SepaBankTransfer { .. } => { Self::SepaBankTransfer } domain::payments::BankTransferData::BacsBankTransfer { .. } => { Self::BacsBankTransfer } domain::payments::BankTransferData::MultibancoBankTransfer { .. } => { Self::MultibancoBankTransfer } domain::payments::BankTransferData::PermataBankTransfer { .. } => { Self::PermataBankTransfer } domain::payments::BankTransferData::BcaBankTransfer { .. } => { Self::BcaBankTransfer } domain::payments::BankTransferData::BniVaBankTransfer { .. } => { Self::BniVaBankTransfer } domain::payments::BankTransferData::BriVaBankTransfer { .. } => { Self::BriVaBankTransfer } domain::payments::BankTransferData::CimbVaBankTransfer { .. } => { Self::CimbVaBankTransfer } domain::payments::BankTransferData::DanamonVaBankTransfer { .. } => { Self::DanamonVaBankTransfer } domain::payments::BankTransferData::MandiriVaBankTransfer { .. } => { Self::MandiriVaBankTransfer } domain::payments::BankTransferData::Pix { .. } => Self::Pix, domain::payments::BankTransferData::Pse {} => Self::Pse, domain::payments::BankTransferData::LocalBankTransfer { .. } => { Self::LocalBankTransfer } domain::payments::BankTransferData::InstantBankTransfer {} => { Self::InstantBankTransfer } } } domain::payments::PaymentMethodData::Crypto(_) => Self::Crypto, domain::payments::PaymentMethodData::MandatePayment => Self::MandatePayment, domain::payments::PaymentMethodData::Reward => Self::Reward, domain::payments::PaymentMethodData::Upi(_) => Self::Upi, domain::payments::PaymentMethodData::Voucher(voucher_data) => match voucher_data { domain::payments::VoucherData::Boleto(_) => Self::Boleto, domain::payments::VoucherData::Efecty => Self::Efecty, domain::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo, domain::payments::VoucherData::RedCompra => Self::RedCompra, domain::payments::VoucherData::RedPagos => Self::RedPagos, domain::payments::VoucherData::Alfamart(_) => Self::Alfamart, domain::payments::VoucherData::Indomaret(_) => Self::Indomaret, domain::payments::VoucherData::Oxxo => Self::Oxxo, domain::payments::VoucherData::SevenEleven(_) => Self::SevenEleven, domain::payments::VoucherData::Lawson(_) => Self::Lawson, domain::payments::VoucherData::MiniStop(_) => Self::MiniStop, domain::payments::VoucherData::FamilyMart(_) => Self::FamilyMart, domain::payments::VoucherData::Seicomart(_) => Self::Seicomart, domain::payments::VoucherData::PayEasy(_) => Self::PayEasy, }, domain::PaymentMethodData::RealTimePayment(real_time_payment_data) => match *real_time_payment_data{ hyperswitch_domain_models::payment_method_data::RealTimePaymentData::DuitNow { } => Self::DuitNow, hyperswitch_domain_models::payment_method_data::RealTimePaymentData::Fps { } => Self::Fps, hyperswitch_domain_models::payment_method_data::RealTimePaymentData::PromptPay { } => Self::PromptPay, hyperswitch_domain_models::payment_method_data::RealTimePaymentData::VietQr { } => Self::VietQr, }, domain::payments::PaymentMethodData::GiftCard(gift_card_data) => { match *gift_card_data { domain::payments::GiftCardData::Givex(_) => Self::Givex, domain::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCar, } } domain::payments::PaymentMethodData::CardToken(_) => Self::CardToken, domain::payments::PaymentMethodData::OpenBanking(data) => match data { hyperswitch_domain_models::payment_method_data::OpenBankingData::OpenBankingPIS { } => Self::OpenBanking }, domain::payments::PaymentMethodData::MobilePayment(mobile_payment_data) => match mobile_payment_data { hyperswitch_domain_models::payment_method_data::MobilePaymentData::DirectCarrierBilling { .. } => Self::DirectCarrierBilling, }, } } } pub fn get_mandate_details( setup_mandate_details: Option<&mandates::MandateData>, ) -> Result<Option<&mandates::MandateAmountData>, error_stack::Report<errors::ConnectorError>> { setup_mandate_details .map(|mandate_data| match &mandate_data.mandate_type { Some(mandates::MandateDataType::SingleUse(mandate)) | Some(mandates::MandateDataType::MultiUse(Some(mandate))) => Ok(mandate), Some(mandates::MandateDataType::MultiUse(None)) => { Err(errors::ConnectorError::MissingRequiredField { field_name: "setup_future_usage.mandate_data.mandate_type.multi_use.amount", } .into()) } None => Err(errors::ConnectorError::MissingRequiredField { field_name: "setup_future_usage.mandate_data.mandate_type", } .into()), }) .transpose() } pub fn convert_amount<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: MinorUnit, currency: enums::Currency, ) -> Result<T, error_stack::Report<errors::ConnectorError>> { amount_convertor .convert(amount, currency) .change_context(errors::ConnectorError::AmountConversionFailed) } pub fn convert_back_amount_to_minor_units<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: T, currency: enums::Currency, ) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> { amount_convertor .convert_back(amount, currency) .change_context(errors::ConnectorError::AmountConversionFailed) } pub fn get_authorise_integrity_object<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: T, currency: String, ) -> Result<AuthoriseIntegrityObject, error_stack::Report<errors::ConnectorError>> { let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let amount_in_minor_unit = convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; Ok(AuthoriseIntegrityObject { amount: amount_in_minor_unit, currency: currency_enum, }) } pub fn get_sync_integrity_object<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: T, currency: String, ) -> Result<SyncIntegrityObject, error_stack::Report<errors::ConnectorError>> { let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let amount_in_minor_unit = convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?; Ok(SyncIntegrityObject { amount: Some(amount_in_minor_unit), currency: Some(currency_enum), }) } pub fn get_capture_integrity_object<T>( amount_convertor: &dyn AmountConvertor<Output = T>, capture_amount: Option<T>, currency: String, ) -> Result<CaptureIntegrityObject, error_stack::Report<errors::ConnectorError>> { let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let capture_amount_in_minor_unit = capture_amount .map(|amount| convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)) .transpose()?; Ok(CaptureIntegrityObject { capture_amount: capture_amount_in_minor_unit, currency: currency_enum, }) } pub fn get_refund_integrity_object<T>( amount_convertor: &dyn AmountConvertor<Output = T>, refund_amount: T, currency: String, ) -> Result<RefundIntegrityObject, error_stack::Report<errors::ConnectorError>> { let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str()) .change_context(errors::ConnectorError::ParsingFailed)?; let refund_amount_in_minor_unit = convert_back_amount_to_minor_units(amount_convertor, refund_amount, currency_enum)?; Ok(RefundIntegrityObject { currency: currency_enum, refund_amount: refund_amount_in_minor_unit, }) } pub trait NetworkTokenData { fn get_card_issuer(&self) -> Result<CardIssuer, Error>; fn get_expiry_year_4_digit(&self) -> Secret<String>; fn get_network_token(&self) -> NetworkTokenNumber; fn get_network_token_expiry_month(&self) -> Secret<String>; fn get_network_token_expiry_year(&self) -> Secret<String>; fn get_cryptogram(&self) -> Option<Secret<String>>; } impl NetworkTokenData for domain::NetworkTokenData { #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.token_number.peek()) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] fn get_card_issuer(&self) -> Result<CardIssuer, Error> { get_card_issuer(self.network_token.peek()) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.token_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{}", year); } Secret::new(year) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] fn get_expiry_year_4_digit(&self) -> Secret<String> { let mut year = self.network_token_exp_year.peek().clone(); if year.len() == 2 { year = format!("20{}", year); } Secret::new(year) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] fn get_network_token(&self) -> NetworkTokenNumber { self.token_number.clone() } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] fn get_network_token(&self) -> NetworkTokenNumber { self.network_token.clone() } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] fn get_network_token_expiry_month(&self) -> Secret<String> { self.token_exp_month.clone() } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] fn get_network_token_expiry_month(&self) -> Secret<String> { self.network_token_exp_month.clone() } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] fn get_network_token_expiry_year(&self) -> Secret<String> { self.token_exp_year.clone() } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] fn get_network_token_expiry_year(&self) -> Secret<String> { self.network_token_exp_year.clone() } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] fn get_cryptogram(&self) -> Option<Secret<String>> { self.token_cryptogram.clone() } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] fn get_cryptogram(&self) -> Option<Secret<String>> { self.cryptogram.clone() } } pub fn convert_uppercase<'de, D, T>(v: D) -> Result<T, D::Error> where D: serde::Deserializer<'de>, T: FromStr, <T as FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error, { use serde::de::Error; let output = <&str>::deserialize(v)?; output.to_uppercase().parse::<T>().map_err(D::Error::custom) }
28,063
1,498
hyperswitch
crates/router/src/connector/ebanx.rs
.rs
pub mod transformers; #[cfg(feature = "payouts")] use common_utils::request::RequestContent; #[cfg(feature = "payouts")] use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}; use error_stack::{report, ResultExt}; #[cfg(feature = "payouts")] use router_env::{instrument, tracing}; use transformers as ebanx; #[cfg(feature = "payouts")] use crate::connector::utils::convert_amount; use crate::{ configs::settings, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, services::{ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, }, utils::BytesExt, }; #[cfg(feature = "payouts")] use crate::{ headers, services::{self, request}, }; #[derive(Clone)] pub struct Ebanx { #[cfg(feature = "payouts")] amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), } impl Ebanx { pub fn new() -> &'static Self { &Self { #[cfg(feature = "payouts")] amount_converter: &FloatMajorUnitForConnector, } } } impl api::Payment for Ebanx {} impl api::PaymentSession for Ebanx {} impl api::ConnectorAccessToken for Ebanx {} impl api::MandateSetup for Ebanx {} impl api::PaymentAuthorize for Ebanx {} impl api::PaymentSync for Ebanx {} impl api::PaymentCapture for Ebanx {} impl api::PaymentVoid for Ebanx {} impl api::Refund for Ebanx {} impl api::RefundExecute for Ebanx {} impl api::RefundSync for Ebanx {} impl api::PaymentToken for Ebanx {} impl api::Payouts for Ebanx {} #[cfg(feature = "payouts")] impl api::PayoutCancel for Ebanx {} #[cfg(feature = "payouts")] impl api::PayoutCreate for Ebanx {} #[cfg(feature = "payouts")] impl api::PayoutEligibility for Ebanx {} #[cfg(feature = "payouts")] impl api::PayoutQuote for Ebanx {} #[cfg(feature = "payouts")] impl api::PayoutRecipient for Ebanx {} #[cfg(feature = "payouts")] impl api::PayoutFulfill for Ebanx {} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Ebanx where Self: ConnectorIntegration<Flow, Request, Response>, { #[cfg(feature = "payouts")] fn build_headers( &self, _req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let header = vec![( headers::CONTENT_TYPE.to_string(), self.common_get_content_type().to_string().into(), )]; Ok(header) } } impl ConnectorCommon for Ebanx { fn id(&self) -> &'static str { "ebanx" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.ebanx.base_url.as_ref() } fn build_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: ebanx::EbanxErrorResponse = res.response .parse_struct("EbanxErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::ErrorResponse { status_code: res.status_code, code: response.status_code, message: response.code, reason: response.message, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } #[cfg(feature = "payouts")] impl ConnectorIntegration<api::PoCreate, types::PayoutsData, types::PayoutsResponseData> for Ebanx { fn get_url( &self, _req: &types::PayoutsRouterData<api::PoCreate>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}ws/payout/create", connectors.ebanx.base_url)) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoCreate>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoCreate>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.source_currency, )?; let connector_router_data = ebanx::EbanxRouterData::from((amount, req)); let connector_req = ebanx::EbanxPayoutCreateRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoCreate>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutCreateType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutCreateType::get_headers(self, req, connectors)?) .set_body(types::PayoutCreateType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &types::PayoutsRouterData<api::PoCreate>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> { let response: ebanx::EbanxPayoutResponse = res .response .parse_struct("EbanxPayoutResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> for Ebanx { fn get_url( &self, _req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}ws/payout/commit", connectors.ebanx.base_url,)) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoFulfill>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.source_currency, )?; let connector_router_data = ebanx::EbanxRouterData::from((amount, req)); let connector_req = ebanx::EbanxPayoutFulfillRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutFulfillType::get_headers( self, req, connectors, )?) .set_body(types::PayoutFulfillType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } #[instrument(skip_all)] fn handle_response( &self, data: &types::PayoutsRouterData<api::PoFulfill>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { let response: ebanx::EbanxFulfillResponse = res .response .parse_struct("EbanxFulfillResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] impl ConnectorIntegration<api::PoCancel, types::PayoutsData, types::PayoutsResponseData> for Ebanx { fn get_url( &self, _req: &types::PayoutsRouterData<api::PoCancel>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}ws/payout/cancel", connectors.ebanx.base_url,)) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoCancel>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, _connectors) } fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoCancel>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = ebanx::EbanxPayoutCancelRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoCancel>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Put) .url(&types::PayoutCancelType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutCancelType::get_headers(self, req, connectors)?) .set_body(types::PayoutCancelType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } #[instrument(skip_all)] fn handle_response( &self, data: &types::PayoutsRouterData<api::PoCancel>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> { let response: ebanx::EbanxCancelResponse = res .response .parse_struct("EbanxCancelResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] impl ConnectorIntegration<api::PoQuote, types::PayoutsData, types::PayoutsResponseData> for Ebanx {} #[cfg(feature = "payouts")] impl ConnectorIntegration<api::PoRecipient, types::PayoutsData, types::PayoutsResponseData> for Ebanx { } #[cfg(feature = "payouts")] impl ConnectorIntegration<api::PoEligibility, types::PayoutsData, types::PayoutsResponseData> for Ebanx { } impl ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Ebanx { // Not Implemented (R) } impl ConnectorValidation for Ebanx { //TODO: implement functions when support enabled } impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for Ebanx { //TODO: implement sessions flow } impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> for Ebanx { } impl ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for Ebanx { } impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Ebanx { } impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Ebanx { } impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for Ebanx { } impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Ebanx { } impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Ebanx {} impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Ebanx {} impl api::IncomingWebhook for Ebanx { fn get_webhook_object_reference_id( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } impl ConnectorSpecifications for Ebanx {}
3,721
1,499
hyperswitch
crates/router/src/connector/gpayments.rs
.rs
pub mod gpayments_types; pub mod transformers; use common_utils::{ request::RequestContent, types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use transformers as gpayments; use crate::{ configs::settings, connector::{gpayments::gpayments_types::GpaymentsConnectorMetaData, utils::to_connector_meta}, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services, services::{request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, Response, }, utils::BytesExt, }; #[derive(Clone)] pub struct Gpayments { _amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Gpayments { pub fn new() -> &'static Self { &Self { _amount_converter: &MinorUnitForConnector, } } } impl api::Payment for Gpayments {} impl api::PaymentSession for Gpayments {} impl api::ConnectorAccessToken for Gpayments {} impl api::MandateSetup for Gpayments {} impl api::PaymentAuthorize for Gpayments {} impl api::PaymentSync for Gpayments {} impl api::PaymentCapture for Gpayments {} impl api::PaymentVoid for Gpayments {} impl api::Refund for Gpayments {} impl api::RefundExecute for Gpayments {} impl api::RefundSync for Gpayments {} impl api::PaymentToken for Gpayments {} impl ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Gpayments { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Gpayments where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, _req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; Ok(header) } } impl ConnectorCommon for Gpayments { fn id(&self) -> &'static str { "gpayments" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor // TODO! Check connector documentation, on which unit they are processing the currency. // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.gpayments.base_url.as_ref() } fn get_auth_header( &self, _auth_type: &types::ConnectorAuthType, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { Ok(vec![]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: gpayments_types::TDS2ApiError = res .response .parse_struct("gpayments_types TDS2ApiError") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.error_code, message: response.error_description, reason: response.error_detail, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl ConnectorValidation for Gpayments { //TODO: implement functions when support enabled } impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for Gpayments { } impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> for Gpayments { } impl ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for Gpayments { } impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Gpayments { } impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Gpayments { } impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for Gpayments { } impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Gpayments { } impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Gpayments { } impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Gpayments { } #[async_trait::async_trait] impl api::IncomingWebhook for Gpayments { fn get_webhook_object_reference_id( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } impl api::ExternalAuthentication for Gpayments {} impl api::ConnectorAuthentication for Gpayments {} impl api::ConnectorPreAuthentication for Gpayments {} impl api::ConnectorPreAuthenticationVersionCall for Gpayments {} impl api::ConnectorPostAuthentication for Gpayments {} fn build_endpoint( base_url: &str, connector_metadata: &Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<String, errors::ConnectorError> { let metadata = gpayments::GpaymentsMetaData::try_from(connector_metadata)?; let endpoint_prefix = metadata.endpoint_prefix; Ok(base_url.replace("{{merchant_endpoint_prefix}}", &endpoint_prefix)) } impl ConnectorIntegration< api::Authentication, types::authentication::ConnectorAuthenticationRequestData, types::authentication::AuthenticationResponseData, > for Gpayments { fn get_headers( &self, req: &types::authentication::ConnectorAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::authentication::ConnectorAuthenticationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_metadata: GpaymentsConnectorMetaData = to_connector_meta( req.request .pre_authentication_data .connector_metadata .clone(), )?; Ok(connector_metadata.authentication_url) } fn get_request_body( &self, req: &types::authentication::ConnectorAuthenticationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req)); let req_obj = gpayments_types::GpaymentsAuthenticationRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &types::authentication::ConnectorAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?; Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url( &types::authentication::ConnectorAuthenticationType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorAuthenticationType::get_headers( self, req, connectors, )?, ) .set_body( types::authentication::ConnectorAuthenticationType::get_request_body( self, req, connectors, )?, ) .add_certificate(Some(gpayments_auth_type.certificate)) .add_certificate_key(Some(gpayments_auth_type.private_key)) .build(), )) } fn handle_response( &self, data: &types::authentication::ConnectorAuthenticationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< types::authentication::ConnectorAuthenticationRouterData, errors::ConnectorError, > { let response: gpayments_types::GpaymentsAuthenticationSuccessResponse = res .response .parse_struct("gpayments GpaymentsAuthenticationResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< api::PostAuthentication, types::authentication::ConnectorPostAuthenticationRequestData, types::authentication::AuthenticationResponseData, > for Gpayments { fn get_headers( &self, req: &types::authentication::ConnectorPostAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::authentication::ConnectorPostAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; Ok(format!( "{}/api/v2/auth/brw/result?threeDSServerTransID={}", base_url, req.request.threeds_server_transaction_id, )) } fn build_request( &self, req: &types::authentication::ConnectorPostAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?; Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) .url( &types::authentication::ConnectorPostAuthenticationType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorPostAuthenticationType::get_headers( self, req, connectors, )?, ) .add_certificate(Some(gpayments_auth_type.certificate)) .add_certificate_key(Some(gpayments_auth_type.private_key)) .build(), )) } fn handle_response( &self, data: &types::authentication::ConnectorPostAuthenticationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< types::authentication::ConnectorPostAuthenticationRouterData, errors::ConnectorError, > { let response: gpayments_types::GpaymentsPostAuthenticationResponse = res .response .parse_struct("gpayments PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok( types::authentication::ConnectorPostAuthenticationRouterData { response: Ok( types::authentication::AuthenticationResponseData::PostAuthNResponse { trans_status: response.trans_status.into(), authentication_value: response.authentication_value, eci: response.eci, }, ), ..data.clone() }, ) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< api::PreAuthentication, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, > for Gpayments { fn get_headers( &self, req: &types::authentication::PreAuthNRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::authentication::PreAuthNRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; Ok(format!("{}/api/v2/auth/brw/init?mode=custom", base_url,)) } fn get_request_body( &self, req: &types::authentication::PreAuthNRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req)); let req_obj = gpayments_types::GpaymentsPreAuthenticationRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &types::authentication::PreAuthNRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?; Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url( &types::authentication::ConnectorPreAuthenticationType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorPreAuthenticationType::get_headers( self, req, connectors, )?, ) .set_body( types::authentication::ConnectorPreAuthenticationType::get_request_body( self, req, connectors, )?, ) .add_certificate(Some(gpayments_auth_type.certificate)) .add_certificate_key(Some(gpayments_auth_type.private_key)) .build(), )) } fn handle_response( &self, data: &types::authentication::PreAuthNRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::authentication::PreAuthNRouterData, errors::ConnectorError> { let response: gpayments_types::GpaymentsPreAuthenticationResponse = res .response .parse_struct("gpayments GpaymentsPreAuthenticationResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< api::PreAuthenticationVersionCall, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, > for Gpayments { fn get_headers( &self, req: &types::authentication::PreAuthNVersionCallRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::authentication::PreAuthNVersionCallRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; Ok(format!("{}/api/v2/auth/enrol", base_url,)) } fn get_request_body( &self, req: &types::authentication::PreAuthNVersionCallRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = gpayments::GpaymentsRouterData::from((MinorUnit::zero(), req)); let req_obj = gpayments_types::GpaymentsPreAuthVersionCallRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &types::authentication::PreAuthNVersionCallRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let gpayments_auth_type = gpayments::GpaymentsAuthType::try_from(&req.connector_auth_type)?; Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url( &types::authentication::ConnectorPreAuthenticationVersionCallType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorPreAuthenticationVersionCallType::get_headers( self, req, connectors, )?, ) .set_body( types::authentication::ConnectorPreAuthenticationVersionCallType::get_request_body( self, req, connectors, )?, ) .add_certificate(Some(gpayments_auth_type.certificate)) .add_certificate_key(Some(gpayments_auth_type.private_key)) .build(), )) } fn handle_response( &self, data: &types::authentication::PreAuthNVersionCallRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::authentication::PreAuthNVersionCallRouterData, errors::ConnectorError> { let response: gpayments_types::GpaymentsPreAuthVersionCallResponse = res .response .parse_struct("gpayments GpaymentsPreAuthVersionCallResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorSpecifications for Gpayments {}
4,540
1,500
hyperswitch
crates/router/src/connector/nmi.rs
.rs
pub mod transformers; use common_utils::{ crypto, ext_traits::ByteSliceExt, request::RequestContent, types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; use diesel_models::enums; use error_stack::{report, ResultExt}; use regex::Regex; use transformers as nmi; use super::utils as connector_utils; use crate::{ configs::settings, core::{ errors::{self, CustomResult}, payments, }, events::connector_api_logs::ConnectorEvent, services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, transformers::ForeignFrom, ErrorResponse, }, }; #[derive(Clone)] pub struct Nmi { amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), } impl Nmi { pub const fn new() -> &'static Self { &Self { amount_converter: &FloatMajorUnitForConnector, } } } impl api::Payment for Nmi {} impl api::PaymentSession for Nmi {} impl api::ConnectorAccessToken for Nmi {} impl api::MandateSetup for Nmi {} impl api::PaymentAuthorize for Nmi {} impl api::PaymentSync for Nmi {} impl api::PaymentCapture for Nmi {} impl api::PaymentVoid for Nmi {} impl api::Refund for Nmi {} impl api::RefundExecute for Nmi {} impl api::RefundSync for Nmi {} impl api::PaymentToken for Nmi {} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nmi where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, _req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { Ok(vec![( "Content-Type".to_string(), "application/x-www-form-urlencoded".to_string().into(), )]) } } impl ConnectorCommon for Nmi { fn id(&self) -> &'static str { "nmi" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.nmi.base_url.as_ref() } fn build_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: nmi::StandardResponse = res .response .parse_struct("StandardResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { message: response.responsetext.to_owned(), status_code: res.status_code, reason: Some(response.responsetext), code: response.response_code, attempt_status: None, connector_transaction_id: Some(response.transactionid), network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl ConnectorValidation for Nmi { fn validate_connector_against_payment_request( &self, capture_method: Option<enums::CaptureMethod>, _payment_method: enums::PaymentMethod, _pmt: Option<enums::PaymentMethodType>, ) -> CustomResult<(), errors::ConnectorError> { let capture_method = capture_method.unwrap_or_default(); match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual | enums::CaptureMethod::SequentialAutomatic => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( connector_utils::construct_not_supported_error_report(capture_method, self.id()), ), } } fn validate_psync_reference_id( &self, _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, _is_three_ds: bool, _status: enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<(), errors::ConnectorError> { // in case we dont have transaction id, we can make psync using attempt id Ok(()) } } impl ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Nmi { } impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for Nmi { } impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> for Nmi { } impl ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for Nmi { fn get_headers( &self, req: &types::SetupMandateRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, _req: &types::SetupMandateRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, req: &types::SetupMandateRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nmi::NmiPaymentsRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, _req: &types::SetupMandateRouterData, _connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("Setup Mandate flow for Nmi".to_string()).into()) // Ok(Some( // services::RequestBuilder::new() // .method(services::Method::Post) // .url(&types::SetupMandateType::get_url(self, req, connectors)?) // .headers(types::SetupMandateType::get_headers(self, req, connectors)?) // .set_body(types::SetupMandateType::get_request_body( // self, req, connectors, // )?) // .build(), // )) } fn handle_response( &self, data: &types::SetupMandateRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::PaymentsPreProcessing for Nmi {} impl ConnectorIntegration< api::PreProcessing, types::PaymentsPreProcessingData, types::PaymentsResponseData, > for Nmi { fn get_headers( &self, req: &types::PaymentsPreProcessingRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::PaymentsPreProcessingRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, req: &types::PaymentsPreProcessingRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nmi::NmiVaultRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PaymentsPreProcessingRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let req = Some( services::RequestBuilder::new() .method(services::Method::Post) .attach_default_headers() .headers(types::PaymentsPreProcessingType::get_headers( self, req, connectors, )?) .url(&types::PaymentsPreProcessingType::get_url( self, req, connectors, )?) .set_body(types::PaymentsPreProcessingType::get_request_body( self, req, connectors, )?) .build(), ); Ok(req) } fn handle_response( &self, data: &types::PaymentsPreProcessingRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: nmi::NmiVaultResponse = serde_urlencoded::from_bytes(&res.response) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Nmi { fn get_headers( &self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, _req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = nmi::NmiRouterData::from((amount, req)); let connector_req = nmi::NmiPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::PaymentsCompleteAuthorize for Nmi {} impl ConnectorIntegration< api::CompleteAuthorize, types::CompleteAuthorizeData, types::PaymentsResponseData, > for Nmi { fn get_headers( &self, req: &types::PaymentsCompleteAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::PaymentsCompleteAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, req: &types::PaymentsCompleteAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = nmi::NmiRouterData::from((amount, req)); let connector_req = nmi::NmiCompleteRequest::try_from(&connector_router_data)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PaymentsCompleteAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsCompleteAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsCompleteAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsCompleteAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: nmi::NmiCompleteResponse = serde_urlencoded::from_bytes(&res.response) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Nmi { fn get_headers( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, _req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/query.php", self.base_url(connectors))) } fn get_request_body( &self, req: &types::PaymentsSyncRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nmi::NmiSyncRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .set_body(types::PaymentsSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response = nmi::SyncResponse::try_from(res.response.to_vec())?; event_builder.map(|i| i.set_response_body(&response)); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for Nmi { fn get_headers( &self, req: &types::PaymentsCaptureRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, _req: &types::PaymentsCaptureRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, )?; let connector_router_data = nmi::NmiRouterData::from((amount, req)); let connector_req = nmi::NmiCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PaymentsCaptureRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Nmi { fn get_headers( &self, req: &types::PaymentsCancelRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, _req: &types::PaymentsCancelRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, req: &types::PaymentsCancelRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nmi::NmiCancelRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::PaymentsCancelRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(types::PaymentsVoidType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Nmi { fn get_headers( &self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, _req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/transact.php", self.base_url(connectors))) } fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = nmi::NmiRouterData::from((refund_amount, req)); let connector_req = nmi::NmiRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: nmi::StandardResponse = serde_urlencoded::from_bytes(&res.response) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Nmi { fn get_headers( &self, req: &types::RefundsRouterData<api::RSync>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, _req: &types::RefundsRouterData<api::RSync>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}api/query.php", self.base_url(connectors))) } fn get_request_body( &self, req: &types::RefundsRouterData<api::RSync>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nmi::NmiSyncRequest::try_from(req)?; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &types::RefundsRouterData<api::RSync>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .set_body(types::RefundSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::RefundsRouterData<api::RSync>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::RefundsRouterData<api::RSync>, errors::ConnectorError> { let response = nmi::NmiRefundSyncResponse::try_from(res.response.to_vec())?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl api::IncomingWebhook for Nmi { fn get_webhook_source_verification_algorithm( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, request: &api::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let sig_header = connector_utils::get_header_key_value("webhook-signature", request.headers)?; let regex_pattern = r"t=(.*),s=(.*)"; if let Some(captures) = Regex::new(regex_pattern) .change_context(errors::ConnectorError::WebhookSignatureNotFound)? .captures(sig_header) { let signature = captures .get(1) .ok_or(errors::ConnectorError::WebhookSignatureNotFound)? .as_str(); return Ok(signature.as_bytes().to_vec()); } Err(report!(errors::ConnectorError::WebhookSignatureNotFound)) } fn get_webhook_source_verification_message( &self, request: &api::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let sig_header = connector_utils::get_header_key_value("webhook-signature", request.headers)?; let regex_pattern = r"t=(.*),s=(.*)"; if let Some(captures) = Regex::new(regex_pattern) .change_context(errors::ConnectorError::WebhookSignatureNotFound)? .captures(sig_header) { let nonce = captures .get(0) .ok_or(errors::ConnectorError::WebhookSignatureNotFound)? .as_str(); let message = format!("{}.{}", nonce, String::from_utf8_lossy(request.body)); return Ok(message.into_bytes()); } Err(report!(errors::ConnectorError::WebhookSignatureNotFound)) } fn get_webhook_object_reference_id( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let reference_body: nmi::NmiWebhookObjectReference = request .body .parse_struct("nmi NmiWebhookObjectReference") .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; let object_reference_id = match reference_body.event_body.action.action_type { nmi::NmiActionType::Sale => api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId( reference_body.event_body.order_id, ), ), nmi::NmiActionType::Auth => api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId( reference_body.event_body.order_id, ), ), nmi::NmiActionType::Capture => api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId( reference_body.event_body.order_id, ), ), nmi::NmiActionType::Void => api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId( reference_body.event_body.order_id, ), ), nmi::NmiActionType::Refund => api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::RefundId(reference_body.event_body.order_id), ), _ => Err(errors::ConnectorError::WebhooksNotImplemented)?, }; Ok(object_reference_id) } fn get_webhook_event_type( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { let event_type_body: nmi::NmiWebhookEventBody = request .body .parse_struct("nmi NmiWebhookEventType") .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; Ok(api::IncomingWebhookEvent::foreign_from( event_type_body.event_type, )) } fn get_webhook_resource_object( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let webhook_body: nmi::NmiWebhookBody = request .body .parse_struct("nmi NmiWebhookBody") .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; match webhook_body.event_body.action.action_type { nmi::NmiActionType::Sale | nmi::NmiActionType::Auth | nmi::NmiActionType::Capture | nmi::NmiActionType::Void | nmi::NmiActionType::Credit => { Ok(Box::new(nmi::SyncResponse::try_from(&webhook_body)?)) } nmi::NmiActionType::Refund => Ok(Box::new(webhook_body)), } } } impl services::ConnectorRedirectResponse for Nmi { fn get_flow_type( &self, _query_params: &str, json_payload: Option<serde_json::Value>, action: services::PaymentAction, ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> { match action { services::PaymentAction::CompleteAuthorize => { let payload_data = json_payload.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "connector_metadata", })?; let redirect_res: nmi::NmiRedirectResponse = serde_json::from_value(payload_data) .change_context( errors::ConnectorError::MissingConnectorRedirectionPayload { field_name: "redirect_res", }, )?; match redirect_res { transformers::NmiRedirectResponse::NmiRedirectResponseData(_) => { Ok(payments::CallConnectorAction::Trigger) } transformers::NmiRedirectResponse::NmiErrorResponseData(error_res) => { Ok(payments::CallConnectorAction::StatusUpdate { status: enums::AttemptStatus::Failure, error_code: Some(error_res.code), error_message: Some(error_res.message), }) } } } services::PaymentAction::PSync | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => { Ok(payments::CallConnectorAction::Trigger) } } } } impl ConnectorSpecifications for Nmi {}
8,223
1,501
hyperswitch
crates/router/src/connector/wellsfargopayout.rs
.rs
pub mod transformers; use common_utils::types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}; use error_stack::{report, ResultExt}; use masking::ExposeInterface; use self::transformers as wellsfargopayout; use super::utils as connector_utils; use crate::{ configs::settings, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, RequestContent, Response, }, utils::BytesExt, }; #[derive(Clone)] pub struct Wellsfargopayout { amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), } impl Wellsfargopayout { pub fn new() -> &'static Self { &Self { amount_converter: &StringMinorUnitForConnector, } } } impl api::Payment for Wellsfargopayout {} impl api::PaymentSession for Wellsfargopayout {} impl api::ConnectorAccessToken for Wellsfargopayout {} impl api::MandateSetup for Wellsfargopayout {} impl api::PaymentAuthorize for Wellsfargopayout {} impl api::PaymentSync for Wellsfargopayout {} impl api::PaymentCapture for Wellsfargopayout {} impl api::PaymentVoid for Wellsfargopayout {} impl api::Refund for Wellsfargopayout {} impl api::RefundExecute for Wellsfargopayout {} impl api::RefundSync for Wellsfargopayout {} impl api::PaymentToken for Wellsfargopayout {} impl ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Wellsfargopayout { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Wellsfargopayout where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Wellsfargopayout { fn id(&self) -> &'static str { "wellsfargopayout" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor // todo!() // TODO! Check connector documentation, on which unit they are processing the currency. // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.wellsfargopayout.base_url.as_ref() } fn get_auth_header( &self, auth_type: &types::ConnectorAuthType, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let auth = wellsfargopayout::WellsfargopayoutAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.expose().into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: wellsfargopayout::WellsfargopayoutErrorResponse = res .response .parse_struct("WellsfargopayoutErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.code, message: response.message, reason: response.reason, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl ConnectorValidation for Wellsfargopayout { //TODO: implement functions when support enabled } impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for Wellsfargopayout { //TODO: implement sessions flow } impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> for Wellsfargopayout { } impl ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for Wellsfargopayout { } impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = wellsfargopayout::WellsfargopayoutRouterData::from((amount, req)); let connector_req = wellsfargopayout::WellsfargopayoutPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res .response .parse_struct("Wellsfargopayout PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::PaymentsSyncRouterData, _connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, req: &types::PaymentsSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &types::PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res .response .parse_struct("wellsfargopayout PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &types::PaymentsCaptureRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, _req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } fn build_request( &self, req: &types::PaymentsCaptureRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res .response .parse_struct("Wellsfargopayout PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Wellsfargopayout { } impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = wellsfargopayout::WellsfargopayoutRouterData::from((refund_amount, req)); let connector_req = wellsfargopayout::WellsfargopayoutRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::RefundsRouterData<api::Execute>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &types::RefundsRouterData<api::Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { let response: wellsfargopayout::RefundResponse = res .response .parse_struct("wellsfargopayout RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &types::RefundSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &types::RefundSyncRouterData, _connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, req: &types::RefundSyncRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( services::RequestBuilder::new() .method(services::Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .set_body(types::RefundSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &types::RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { let response: wellsfargopayout::RefundResponse = res .response .parse_struct("wellsfargopayout RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl api::IncomingWebhook for Wellsfargopayout { fn get_webhook_object_reference_id( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } impl ConnectorSpecifications for Wellsfargopayout {}
4,556
1,502
hyperswitch
crates/router/src/connector/netcetera.rs
.rs
pub mod netcetera_types; pub mod transformers; use std::fmt::Debug; use common_utils::{ext_traits::ByteSliceExt, request::RequestContent}; use error_stack::ResultExt; use hyperswitch_interfaces::authentication::ExternalAuthenticationPayload; use transformers as netcetera; use crate::{ configs::settings, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation}, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, ErrorResponse, Response, }, utils::BytesExt, }; #[derive(Debug, Clone)] pub struct Netcetera; impl api::Payment for Netcetera {} impl api::PaymentSession for Netcetera {} impl api::ConnectorAccessToken for Netcetera {} impl api::MandateSetup for Netcetera {} impl api::PaymentAuthorize for Netcetera {} impl api::PaymentSync for Netcetera {} impl api::PaymentCapture for Netcetera {} impl api::PaymentVoid for Netcetera {} impl api::Refund for Netcetera {} impl api::RefundExecute for Netcetera {} impl api::RefundSync for Netcetera {} impl api::PaymentToken for Netcetera {} impl ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Netcetera { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Netcetera where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Netcetera { fn id(&self) -> &'static str { "netcetera" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.netcetera.base_url.as_ref() } fn get_auth_header( &self, _auth_type: &types::ConnectorAuthType, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { Ok(vec![]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: netcetera::NetceteraErrorResponse = res .response .parse_struct("NetceteraErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.error_details.error_code, message: response.error_details.error_description, reason: response.error_details.error_detail, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } impl ConnectorValidation for Netcetera {} impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> for Netcetera { } impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> for Netcetera { } impl ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for Netcetera { } impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Netcetera { } impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Netcetera { } impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> for Netcetera { } impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Netcetera { } impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Netcetera { } impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Netcetera { } #[async_trait::async_trait] impl api::IncomingWebhook for Netcetera { fn get_webhook_object_reference_id( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { let webhook_body: netcetera::ResultsResponseData = request .body .parse_struct("netcetera ResultsResponseData") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(api::webhooks::ObjectReferenceId::ExternalAuthenticationID( api::webhooks::AuthenticationIdType::ConnectorAuthenticationId( webhook_body.three_ds_server_trans_id, ), )) } fn get_webhook_event_type( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { Ok(api::IncomingWebhookEvent::ExternalAuthenticationARes) } fn get_webhook_resource_object( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let webhook_body_value: netcetera::ResultsResponseData = request .body .parse_struct("netcetera ResultsResponseDatae") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(Box::new(webhook_body_value)) } fn get_external_authentication_details( &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ExternalAuthenticationPayload, errors::ConnectorError> { let webhook_body: netcetera::ResultsResponseData = request .body .parse_struct("netcetera ResultsResponseData") .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(ExternalAuthenticationPayload { trans_status: webhook_body .trans_status .unwrap_or(common_enums::TransactionStatus::InformationOnly), authentication_value: webhook_body.authentication_value, eci: webhook_body.eci, }) } } fn build_endpoint( base_url: &str, connector_metadata: &Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<String, errors::ConnectorError> { let metadata = netcetera::NetceteraMetaData::try_from(connector_metadata)?; let endpoint_prefix = metadata.endpoint_prefix; Ok(base_url.replace("{{merchant_endpoint_prefix}}", &endpoint_prefix)) } impl api::ConnectorPreAuthentication for Netcetera {} impl api::ConnectorPreAuthenticationVersionCall for Netcetera {} impl api::ExternalAuthentication for Netcetera {} impl api::ConnectorAuthentication for Netcetera {} impl api::ConnectorPostAuthentication for Netcetera {} impl ConnectorIntegration< api::PreAuthentication, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, > for Netcetera { fn get_headers( &self, req: &types::authentication::PreAuthNRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::authentication::PreAuthNRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; Ok(format!("{}/3ds/versioning", base_url,)) } fn get_request_body( &self, req: &types::authentication::PreAuthNRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = netcetera::NetceteraRouterData::try_from((0, req))?; let req_obj = netcetera::NetceteraPreAuthenticationRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &types::authentication::PreAuthNRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let netcetera_auth_type = netcetera::NetceteraAuthType::try_from(&req.connector_auth_type)?; Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url( &types::authentication::ConnectorPreAuthenticationType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorPreAuthenticationType::get_headers( self, req, connectors, )?, ) .set_body( types::authentication::ConnectorPreAuthenticationType::get_request_body( self, req, connectors, )?, ) .add_certificate(Some(netcetera_auth_type.certificate)) .add_certificate_key(Some(netcetera_auth_type.private_key)) .build(), )) } fn handle_response( &self, data: &types::authentication::PreAuthNRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::authentication::PreAuthNRouterData, errors::ConnectorError> { let response: netcetera::NetceteraPreAuthenticationResponse = res .response .parse_struct("netcetera NetceteraPreAuthenticationResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< api::Authentication, types::authentication::ConnectorAuthenticationRequestData, types::authentication::AuthenticationResponseData, > for Netcetera { fn get_headers( &self, req: &types::authentication::ConnectorAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &types::authentication::ConnectorAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?; Ok(format!("{}/3ds/authentication", base_url,)) } fn get_request_body( &self, req: &types::authentication::ConnectorAuthenticationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = netcetera::NetceteraRouterData::try_from(( &self.get_currency_unit(), req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "currency", })?, req.request .amount .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "amount", })?, req, ))?; let req_obj = netcetera::NetceteraAuthenticationRequest::try_from(&connector_router_data); Ok(RequestContent::Json(Box::new(req_obj?))) } fn build_request( &self, req: &types::authentication::ConnectorAuthenticationRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let netcetera_auth_type = netcetera::NetceteraAuthType::try_from(&req.connector_auth_type)?; Ok(Some( services::RequestBuilder::new() .method(services::Method::Post) .url( &types::authentication::ConnectorAuthenticationType::get_url( self, req, connectors, )?, ) .attach_default_headers() .headers( types::authentication::ConnectorAuthenticationType::get_headers( self, req, connectors, )?, ) .set_body( types::authentication::ConnectorAuthenticationType::get_request_body( self, req, connectors, )?, ) .add_certificate(Some(netcetera_auth_type.certificate)) .add_certificate_key(Some(netcetera_auth_type.private_key)) .build(), )) } fn handle_response( &self, data: &types::authentication::ConnectorAuthenticationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< types::authentication::ConnectorAuthenticationRouterData, errors::ConnectorError, > { let response: netcetera::NetceteraAuthenticationResponse = res .response .parse_struct("NetceteraAuthenticationResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< api::PostAuthentication, types::authentication::ConnectorPostAuthenticationRequestData, types::authentication::AuthenticationResponseData, > for Netcetera { } impl ConnectorIntegration< api::PreAuthenticationVersionCall, types::authentication::PreAuthNRequestData, types::authentication::AuthenticationResponseData, > for Netcetera { } impl ConnectorSpecifications for Netcetera {}
3,471
1,503
hyperswitch
crates/router/src/connector/wise.rs
.rs
pub mod transformers; #[cfg(feature = "payouts")] use common_utils::request::RequestContent; use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector}; use error_stack::{report, ResultExt}; #[cfg(feature = "payouts")] use masking::PeekInterface; #[cfg(feature = "payouts")] use router_env::{instrument, tracing}; use self::transformers as wise; use super::utils::convert_amount; use crate::{ configs::settings, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, services::{ self, request::{self, Mask}, ConnectorSpecifications, ConnectorValidation, }, types::{ self, api::{self, ConnectorCommon, ConnectorCommonExt}, }, utils::BytesExt, }; #[derive(Clone)] pub struct Wise { amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Wise { pub fn new() -> &'static Self { &Self { amount_converter: &MinorUnitForConnector, } } } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Wise where Self: services::ConnectorIntegration<Flow, Request, Response>, { #[cfg(feature = "payouts")] fn build_headers( &self, req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), types::PayoutQuoteType::get_content_type(self) .to_string() .into(), )]; let auth = wise::WiseAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let mut api_key = vec![( headers::AUTHORIZATION.to_string(), auth.api_key.into_masked(), )]; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Wise { fn id(&self) -> &'static str { "wise" } fn get_auth_header( &self, auth_type: &types::ConnectorAuthType, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let auth = wise::WiseAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.into_masked(), )]) } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { connectors.wise.base_url.as_ref() } fn build_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: wise::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); let default_status = response.status.unwrap_or_default().to_string(); match response.errors { Some(errs) => { if let Some(e) = errs.first() { Ok(types::ErrorResponse { status_code: res.status_code, code: e.code.clone(), message: e.message.clone(), reason: None, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } else { Ok(types::ErrorResponse { status_code: res.status_code, code: default_status, message: response.message.unwrap_or_default(), reason: None, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } None => Ok(types::ErrorResponse { status_code: res.status_code, code: default_status, message: response.message.unwrap_or_default(), reason: None, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }), } } } impl api::Payment for Wise {} impl api::PaymentAuthorize for Wise {} impl api::PaymentSync for Wise {} impl api::PaymentVoid for Wise {} impl api::PaymentCapture for Wise {} impl api::MandateSetup for Wise {} impl api::ConnectorAccessToken for Wise {} impl api::PaymentToken for Wise {} impl ConnectorValidation for Wise {} impl services::ConnectorIntegration< api::PaymentMethodToken, types::PaymentMethodTokenizationData, types::PaymentsResponseData, > for Wise { } impl services::ConnectorIntegration< api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken, > for Wise { } impl services::ConnectorIntegration< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, > for Wise { fn build_request( &self, _req: &types::RouterData< api::SetupMandate, types::SetupMandateRequestData, types::PaymentsResponseData, >, _connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Wise".to_string()) .into(), ) } } impl api::PaymentSession for Wise {} impl services::ConnectorIntegration< api::Session, types::PaymentsSessionData, types::PaymentsResponseData, > for Wise { } impl services::ConnectorIntegration< api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData, > for Wise { } impl services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> for Wise { } impl services::ConnectorIntegration< api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, > for Wise { } impl services::ConnectorIntegration< api::Void, types::PaymentsCancelData, types::PaymentsResponseData, > for Wise { } impl api::Payouts for Wise {} #[cfg(feature = "payouts")] impl api::PayoutCancel for Wise {} #[cfg(feature = "payouts")] impl api::PayoutCreate for Wise {} #[cfg(feature = "payouts")] impl api::PayoutEligibility for Wise {} #[cfg(feature = "payouts")] impl api::PayoutQuote for Wise {} #[cfg(feature = "payouts")] impl api::PayoutRecipient for Wise {} #[cfg(feature = "payouts")] impl api::PayoutFulfill for Wise {} #[cfg(feature = "payouts")] impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::PayoutsResponseData> for Wise { fn get_url( &self, req: &types::PayoutsRouterData<api::PoCancel>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let transfer_id = req.request.connector_payout_id.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "transfer_id", }, )?; Ok(format!( "{}v1/transfers/{}/cancel", connectors.wise.base_url, transfer_id )) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoCancel>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, _connectors) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoCancel>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Put) .url(&types::PayoutCancelType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutCancelType::get_headers(self, req, connectors)?) .build(); Ok(Some(request)) } #[instrument(skip_all)] fn handle_response( &self, data: &types::PayoutsRouterData<api::PoCancel>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoCancel>, errors::ConnectorError> { let response: wise::WisePayoutResponse = res .response .parse_struct("WisePayoutResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { let response: wise::ErrorResponse = res .response .parse_struct("ErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); let def_res = response.status.unwrap_or_default().to_string(); let errors = response.errors.unwrap_or_default(); let (code, message) = if let Some(e) = errors.first() { (e.code.clone(), e.message.clone()) } else { (def_res, response.message.unwrap_or_default()) }; Ok(types::ErrorResponse { status_code: res.status_code, code, message, reason: None, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } #[cfg(feature = "payouts")] impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::PayoutsResponseData> for Wise { fn get_url( &self, req: &types::PayoutsRouterData<api::PoQuote>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let auth = wise::WiseAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(format!( "{}v3/profiles/{}/quotes", connectors.wise.base_url, auth.profile_id.peek() )) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoQuote>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoQuote>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.source_currency, )?; let connector_router_data = wise::WiseRouterData::from((amount, req)); let connector_req = wise::WisePayoutQuoteRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoQuote>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutQuoteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutQuoteType::get_headers(self, req, connectors)?) .set_body(types::PayoutQuoteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } #[instrument(skip_all)] fn handle_response( &self, data: &types::PayoutsRouterData<api::PoQuote>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoQuote>, errors::ConnectorError> { let response: wise::WisePayoutQuoteResponse = res .response .parse_struct("WisePayoutQuoteResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] impl services::ConnectorIntegration<api::PoRecipient, types::PayoutsData, types::PayoutsResponseData> for Wise { fn get_url( &self, _req: &types::PayoutsRouterData<api::PoRecipient>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v1/accounts", connectors.wise.base_url)) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoRecipient>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoRecipient>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.source_currency, )?; let connector_router_data = wise::WiseRouterData::from((amount, req)); let connector_req = wise::WiseRecipientCreateRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoRecipient>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutRecipientType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutRecipientType::get_headers( self, req, connectors, )?) .set_body(types::PayoutRecipientType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } #[instrument(skip_all)] fn handle_response( &self, data: &types::PayoutsRouterData<api::PoRecipient>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoRecipient>, errors::ConnectorError> { let response: wise::WiseRecipientCreateResponse = res .response .parse_struct("WiseRecipientCreateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] #[cfg(feature = "payouts")] impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::PayoutsResponseData> for Wise { fn get_url( &self, _req: &types::PayoutsRouterData<api::PoCreate>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/v1/transfers", connectors.wise.base_url)) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoCreate>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoCreate>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = wise::WisePayoutCreateRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoCreate>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutCreateType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutCreateType::get_headers(self, req, connectors)?) .set_body(types::PayoutCreateType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } #[instrument(skip_all)] fn handle_response( &self, data: &types::PayoutsRouterData<api::PoCreate>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoCreate>, errors::ConnectorError> { let response: wise::WisePayoutResponse = res .response .parse_struct("WisePayoutResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[cfg(feature = "payouts")] impl services::ConnectorIntegration< api::PoEligibility, types::PayoutsData, types::PayoutsResponseData, > for Wise { fn build_request( &self, _req: &types::PayoutsRouterData<api::PoEligibility>, _connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { // Eligibility check for cards is not implemented Err( errors::ConnectorError::NotImplemented("Payout Eligibility for Wise".to_string()) .into(), ) } } #[cfg(feature = "payouts")] impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResponseData> for Wise { fn get_url( &self, req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { let auth = wise::WiseAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let transfer_id = req.request.connector_payout_id.to_owned().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "transfer_id", }, )?; Ok(format!( "{}v3/profiles/{}/transfers/{}/payments", connectors.wise.base_url, auth.profile_id.peek(), transfer_id )) } fn get_headers( &self, req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_request_body( &self, req: &types::PayoutsRouterData<api::PoFulfill>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = wise::WisePayoutFulfillRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &types::PayoutsRouterData<api::PoFulfill>, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { let request = services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PayoutFulfillType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PayoutFulfillType::get_headers( self, req, connectors, )?) .set_body(types::PayoutFulfillType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } #[instrument(skip_all)] fn handle_response( &self, data: &types::PayoutsRouterData<api::PoFulfill>, event_builder: Option<&mut ConnectorEvent>, res: types::Response, ) -> CustomResult<types::PayoutsRouterData<api::PoFulfill>, errors::ConnectorError> { let response: wise::WiseFulfillResponse = res .response .parse_struct("WiseFulfillResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: types::Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::Refund for Wise {} impl api::RefundExecute for Wise {} impl api::RefundSync for Wise {} impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Wise { } impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Wise { } #[async_trait::async_trait] impl api::IncomingWebhook for Wise { fn get_webhook_object_reference_id( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } impl ConnectorSpecifications for Wise {}
5,658
1,504