text
stringlengths
81
477k
file_path
stringlengths
22
92
module
stringlengths
13
87
token_count
int64
24
94.8k
has_source_code
bool
1 class
// File: crates/api_models/src/authentication.rs // Module: api_models::src::authentication use common_enums::{enums, AuthenticationConnectors}; #[cfg(feature = "v1")] use common_utils::errors::{self, CustomResult}; use common_utils::{ events::{ApiEventMetric, ApiEventsType}, id_type, }; #[cfg(feature = "v1")] use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::payments::{Address, BrowserInformation, PaymentMethodData}; use crate::payments::{CustomerDetails, DeviceChannel, SdkInformation, ThreeDsCompletionIndicator}; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AuthenticationCreateRequest { /// The unique identifier for this authentication. #[schema(value_type = Option<String>, example = "auth_mbabizu24mvu3mela5njyhpit4")] pub authentication_id: Option<id_type::AuthenticationId>, /// The business profile that is associated with this authentication #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Customer details. #[schema(value_type = Option<CustomerDetails>)] pub customer: Option<CustomerDetails>, /// The amount for the transaction, required. #[schema(value_type = MinorUnit, example = 1000)] pub amount: common_utils::types::MinorUnit, /// The connector to be used for authentication, if known. #[schema(value_type = Option<AuthenticationConnectors>, example = "netcetera")] pub authentication_connector: Option<AuthenticationConnectors>, /// The currency for the transaction, required. #[schema(value_type = Currency)] pub currency: common_enums::Currency, /// The URL to which the user should be redirected after authentication. #[schema(value_type = Option<String>, example = "https://example.com/redirect")] pub return_url: Option<String>, /// Force 3DS challenge. #[serde(default)] pub force_3ds_challenge: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, /// Profile Acquirer ID get from profile acquirer configuration #[schema(value_type = Option<String>)] pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>, /// Acquirer details information #[schema(value_type = Option<AcquirerDetails>)] pub acquirer_details: Option<AcquirerDetails>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AcquirerDetails { /// The bin of the card. #[schema(value_type = Option<String>, example = "123456")] pub acquirer_bin: Option<String>, /// The merchant id of the card. #[schema(value_type = Option<String>, example = "merchant_abc")] pub acquirer_merchant_id: Option<String>, /// The country code of the card. #[schema(value_type = Option<String>, example = "US/34456")] pub merchant_country_code: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AuthenticationResponse { /// The unique identifier for this authentication. #[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")] pub authentication_id: id_type::AuthenticationId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(value_type = String, example = "merchant_abc")] pub merchant_id: id_type::MerchantId, /// The current status of the authentication (e.g., Started). #[schema(value_type = AuthenticationStatus)] pub status: common_enums::AuthenticationStatus, /// The client secret for this authentication, to be used for client-side operations. #[schema(value_type = Option<String>, example = "auth_mbabizu24mvu3mela5njyhpit4_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<masking::Secret<String>>, /// The amount for the transaction. #[schema(value_type = MinorUnit, example = 1000)] pub amount: common_utils::types::MinorUnit, /// The currency for the transaction. #[schema(value_type = Currency)] pub currency: enums::Currency, /// The connector to be used for authentication, if known. #[schema(value_type = Option<AuthenticationConnectors>, example = "netcetera")] pub authentication_connector: Option<AuthenticationConnectors>, /// Whether 3DS challenge was forced. pub force_3ds_challenge: Option<bool>, /// The URL to which the user should be redirected after authentication, if provided. pub return_url: Option<String>, #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created_at: Option<PrimitiveDateTime>, #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, /// Acquirer details information #[schema(value_type = Option<AcquirerDetails>)] pub acquirer_details: Option<AcquirerDetails>, /// Profile Acquirer ID get from profile acquirer configuration #[schema(value_type = Option<String>)] pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>, } impl ApiEventMetric for AuthenticationCreateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { self.authentication_id .as_ref() .map(|id| ApiEventsType::Authentication { authentication_id: id.clone(), }) } } impl ApiEventMetric for AuthenticationResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } } #[cfg(feature = "v1")] #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct AuthenticationEligibilityRequest { /// Payment method-specific data such as card details, wallet info, etc. /// This holds the raw information required to process the payment method. #[schema(value_type = PaymentMethodData)] pub payment_method_data: PaymentMethodData, /// Enum representing the type of payment method being used /// (e.g., Card, Wallet, UPI, BankTransfer, etc.). #[schema(value_type = PaymentMethod)] pub payment_method: common_enums::PaymentMethod, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "debit")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Optional secret value used to identify and authorize the client making the request. /// This can help ensure that the payment session is secure and valid. #[schema(value_type = Option<String>)] pub client_secret: Option<masking::Secret<String>>, /// Optional identifier for the business profile associated with the payment. /// This determines which configurations, rules, and branding are applied to the transaction. #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Optional billing address of the customer. /// This can be used for fraud detection, authentication, or compliance purposes. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// Optional shipping address of the customer. /// This can be useful for logistics, verification, or additional risk checks. #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// Optional information about the customer's browser (user-agent, language, etc.). /// This is typically used to support 3DS authentication flows and improve risk assessment. #[schema(value_type = Option<BrowserInformation>)] pub browser_information: Option<BrowserInformation>, /// Optional email address of the customer. /// Used for customer identification, communication, and possibly for 3DS or fraud checks. #[schema(value_type = Option<String>)] pub email: Option<common_utils::pii::Email>, } #[cfg(feature = "v1")] impl AuthenticationEligibilityRequest { pub fn get_next_action_api( &self, base_url: String, authentication_id: String, ) -> CustomResult<NextAction, errors::ParsingError> { let url = format!("{base_url}/authentication/{authentication_id}/authenticate"); Ok(NextAction { url: url::Url::parse(&url).change_context(errors::ParsingError::UrlParsingError)?, http_method: common_utils::request::Method::Post, }) } pub fn get_billing_address(&self) -> Option<Address> { self.billing.clone() } pub fn get_shipping_address(&self) -> Option<Address> { self.shipping.clone() } pub fn get_browser_information(&self) -> Option<BrowserInformation> { self.browser_information.clone() } } #[cfg(feature = "v1")] #[derive(Debug, Serialize, ToSchema)] pub struct AuthenticationEligibilityResponse { /// The unique identifier for this authentication. #[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")] pub authentication_id: id_type::AuthenticationId, /// The URL to which the user should be redirected after authentication. #[schema(value_type = NextAction)] pub next_action: NextAction, /// The current status of the authentication (e.g., Started). #[schema(value_type = AuthenticationStatus)] pub status: common_enums::AuthenticationStatus, /// The 3DS data for this authentication. #[schema(value_type = Option<EligibilityResponseParams>)] pub eligibility_response_params: Option<EligibilityResponseParams>, /// The metadata for this authentication. #[schema(value_type = serde_json::Value)] pub connector_metadata: Option<serde_json::Value>, /// The unique identifier for this authentication. #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The error message for this authentication. #[schema(value_type = Option<String>)] pub error_message: Option<String>, /// The error code for this authentication. #[schema(value_type = Option<String>)] pub error_code: Option<String>, /// The connector used for this authentication. #[schema(value_type = Option<AuthenticationConnectors>)] pub authentication_connector: Option<AuthenticationConnectors>, /// Billing address #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// Shipping address #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// Browser information #[schema(value_type = Option<BrowserInformation>)] pub browser_information: Option<BrowserInformation>, /// Email #[schema(value_type = Option<String>)] pub email: common_utils::crypto::OptionalEncryptableEmail, /// Acquirer details information. #[schema(value_type = Option<AcquirerDetails>)] pub acquirer_details: Option<AcquirerDetails>, } #[derive(Debug, Serialize, ToSchema)] pub enum EligibilityResponseParams { ThreeDsData(ThreeDsData), } #[derive(Debug, Serialize, ToSchema)] pub struct ThreeDsData { /// The unique identifier for this authentication from the 3DS server. #[schema(value_type = String)] pub three_ds_server_transaction_id: Option<String>, /// The maximum supported 3DS version. #[schema(value_type = String)] pub maximum_supported_3ds_version: Option<common_utils::types::SemanticVersion>, /// The unique identifier for this authentication from the connector. #[schema(value_type = String)] pub connector_authentication_id: Option<String>, /// The data required to perform the 3DS method. #[schema(value_type = String)] pub three_ds_method_data: Option<String>, /// The URL to which the user should be redirected after authentication. #[schema(value_type = String, example = "https://example.com/redirect")] pub three_ds_method_url: Option<url::Url>, /// The version of the message. #[schema(value_type = String)] pub message_version: Option<common_utils::types::SemanticVersion>, /// The unique identifier for this authentication. #[schema(value_type = String)] pub directory_server_id: Option<String>, } #[derive(Debug, Serialize, ToSchema)] pub struct NextAction { /// The URL for authenticatating the user. #[schema(value_type = String)] pub url: url::Url, /// The HTTP method to use for the request. #[schema(value_type = Method)] pub http_method: common_utils::request::Method, } #[cfg(feature = "v1")] impl ApiEventMetric for AuthenticationEligibilityRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v1")] impl ApiEventMetric for AuthenticationEligibilityResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AuthenticationAuthenticateRequest { /// Authentication ID for the authentication #[serde(skip_deserializing)] pub authentication_id: id_type::AuthenticationId, /// Client secret for the authentication #[schema(value_type = String)] pub client_secret: Option<masking::Secret<String>>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } impl ApiEventMetric for AuthenticationAuthenticateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AuthenticationAuthenticateResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = Option<TransactionStatus>)] pub transaction_status: Option<common_enums::TransactionStatus>, /// Access Server URL to be used for challenge submission pub acs_url: Option<url::Url>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_ds_server_transaction_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, /// The error message for this authentication. #[schema(value_type = String)] pub error_message: Option<String>, /// The error code for this authentication. #[schema(value_type = String)] pub error_code: Option<String>, /// The authentication value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern. #[schema(value_type = String)] pub authentication_value: Option<masking::Secret<String>>, /// The current status of the authentication (e.g., Started). #[schema(value_type = AuthenticationStatus)] pub status: common_enums::AuthenticationStatus, /// The connector to be used for authentication, if known. #[schema(value_type = Option<AuthenticationConnectors>, example = "netcetera")] pub authentication_connector: Option<AuthenticationConnectors>, /// The unique identifier for this authentication. #[schema(value_type = AuthenticationId, example = "auth_mbabizu24mvu3mela5njyhpit4")] pub authentication_id: id_type::AuthenticationId, /// The ECI value for this authentication. #[schema(value_type = String)] pub eci: Option<String>, /// Acquirer details information. #[schema(value_type = Option<AcquirerDetails>)] pub acquirer_details: Option<AcquirerDetails>, } impl ApiEventMetric for AuthenticationAuthenticateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, ToSchema)] pub struct AuthenticationSyncResponse { // Core Authentication Fields (from AuthenticationResponse) /// The unique identifier for this authentication. #[schema(value_type = String, example = "auth_mbabizu24mvu3mela5njyhpit4")] pub authentication_id: id_type::AuthenticationId, /// This is an identifier for the merchant account. #[schema(value_type = String, example = "merchant_abc")] pub merchant_id: id_type::MerchantId, /// The current status of the authentication. #[schema(value_type = AuthenticationStatus)] pub status: common_enums::AuthenticationStatus, /// The client secret for this authentication. #[schema(value_type = Option<String>)] pub client_secret: Option<masking::Secret<String>>, /// The amount for the transaction. #[schema(value_type = MinorUnit, example = 1000)] pub amount: common_utils::types::MinorUnit, /// The currency for the transaction. #[schema(value_type = Currency)] pub currency: enums::Currency, /// The connector used for authentication. #[schema(value_type = Option<AuthenticationConnectors>)] pub authentication_connector: Option<AuthenticationConnectors>, /// Whether 3DS challenge was forced. pub force_3ds_challenge: Option<bool>, /// The URL to which the user should be redirected after authentication. pub return_url: Option<String>, #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// The business profile that is associated with this authentication. #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// SCA exemption type for this authentication. #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, /// Acquirer details information. #[schema(value_type = Option<AcquirerDetails>)] pub acquirer_details: Option<AcquirerDetails>, /// The unique identifier from the 3DS server. #[schema(value_type = Option<String>)] pub threeds_server_transaction_id: Option<String>, /// The maximum supported 3DS version. #[schema(value_type = Option<String>)] pub maximum_supported_3ds_version: Option<common_utils::types::SemanticVersion>, /// The unique identifier from the connector. #[schema(value_type = Option<String>)] pub connector_authentication_id: Option<String>, /// The data required to perform the 3DS method. #[schema(value_type = Option<String>)] pub three_ds_method_data: Option<String>, /// The URL for the 3DS method. #[schema(value_type = Option<String>)] pub three_ds_method_url: Option<String>, /// The version of the message. #[schema(value_type = Option<String>)] pub message_version: Option<common_utils::types::SemanticVersion>, /// The metadata for this authentication. #[schema(value_type = Option<serde_json::Value>)] pub connector_metadata: Option<serde_json::Value>, /// The unique identifier for the directory server. #[schema(value_type = Option<String>)] pub directory_server_id: Option<String>, /// Billing address. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// Shipping address. #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// Browser information. #[schema(value_type = Option<BrowserInformation>)] pub browser_information: Option<BrowserInformation>, /// Email. #[schema(value_type = Option<String>)] pub email: common_utils::crypto::OptionalEncryptableEmail, /// Indicates the transaction status. #[serde(rename = "trans_status")] #[schema(value_type = Option<TransactionStatus>)] pub transaction_status: Option<common_enums::TransactionStatus>, /// Access Server URL for challenge submission. pub acs_url: Option<String>, /// Challenge request to be sent to acs_url. pub challenge_request: Option<String>, /// Unique identifier assigned by EMVCo. pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS. pub acs_trans_id: Option<String>, /// JWS object created by the ACS for the ARes message. pub acs_signed_content: Option<String>, /// Three DS Requestor URL. pub three_ds_requestor_url: Option<String>, /// Merchant app URL for OOB authentication. pub three_ds_requestor_app_url: Option<String>, /// The authentication value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern. #[schema(value_type = Option<String>)] pub authentication_value: Option<masking::Secret<String>>, /// ECI value for this authentication, only available in case of server to server request. Unavailable in case of client request due to security concern. pub eci: Option<String>, // Common Error Fields (present in multiple responses) /// Error message if any. #[schema(value_type = Option<String>)] pub error_message: Option<String>, /// Error code if any. #[schema(value_type = Option<String>)] pub error_code: Option<String>, /// Profile Acquirer ID #[schema(value_type = Option<String>)] pub profile_acquirer_id: Option<id_type::ProfileAcquirerId>, } #[cfg(feature = "v1")] impl ApiEventMetric for AuthenticationSyncResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AuthenticationSyncRequest { /// The client secret for this authentication. #[schema(value_type = String)] pub client_secret: Option<masking::Secret<String>>, /// Authentication ID for the authentication #[serde(skip_deserializing)] pub authentication_id: id_type::AuthenticationId, } impl ApiEventMetric for AuthenticationSyncRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct AuthenticationSyncPostUpdateRequest { /// Authentication ID for the authentication #[serde(skip_deserializing)] pub authentication_id: id_type::AuthenticationId, } impl ApiEventMetric for AuthenticationSyncPostUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Authentication { authentication_id: self.authentication_id.clone(), }) } }
crates/api_models/src/authentication.rs
api_models::src::authentication
5,394
true
// File: crates/api_models/src/routing.rs // Module: api_models::src::routing use std::fmt::Debug; use common_types::three_ds_decision_rule_engine::{ThreeDSDecision, ThreeDSDecisionRule}; use common_utils::{ errors::{ParsingError, ValidationError}, ext_traits::ValueExt, pii, }; use euclid::frontend::ast::Program; pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ ast, dir::{DirKeyKind, EuclidDirFilter}, }, }; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::{ enums::{RoutableConnectors, TransactionType}, open_router, }; // Define constants for default values const DEFAULT_LATENCY_THRESHOLD: f64 = 90.0; const DEFAULT_BUCKET_SIZE: i32 = 200; const DEFAULT_HEDGING_PERCENT: f64 = 5.0; const DEFAULT_ELIMINATION_THRESHOLD: f64 = 0.35; const DEFAULT_PAYMENT_METHOD: &str = "CARD"; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum ConnectorSelection { Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), } impl ConnectorSelection { pub fn get_connector_list(&self) -> Vec<RoutableConnectorChoice> { match self { Self::Priority(list) => list.clone(), Self::VolumeSplit(splits) => { splits.iter().map(|split| split.connector.clone()).collect() } } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingConfigRequest { pub name: String, pub description: String, pub algorithm: StaticRoutingAlgorithm, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingConfigRequest { pub name: Option<String>, pub description: Option<String>, pub algorithm: Option<StaticRoutingAlgorithm>, #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, pub transaction_type: Option<TransactionType>, } #[derive(Debug, serde::Serialize, ToSchema)] pub struct ProfileDefaultRoutingConfig { #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, pub connectors: Vec<RoutableConnectorChoice>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveQuery { pub limit: Option<u16>, pub offset: Option<u8>, pub transaction_type: Option<TransactionType>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingActivatePayload { pub transaction_type: Option<TransactionType>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveLinkQuery { pub profile_id: Option<common_utils::id_type::ProfileId>, pub transaction_type: Option<TransactionType>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveLinkQueryWrapper { pub routing_query: RoutingRetrieveQuery, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] /// Response of the retrieved routing configs for a merchant account pub struct RoutingRetrieveResponse { pub algorithm: Option<MerchantRoutingAlgorithm>, } #[derive(Debug, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum LinkedRoutingConfigRetrieveResponse { MerchantAccountBased(Box<RoutingRetrieveResponse>), ProfileBased(Vec<RoutingDictionaryRecord>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] /// Routing Algorithm specific to merchants pub struct MerchantRoutingAlgorithm { #[schema(value_type = String)] pub id: common_utils::id_type::RoutingId, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, pub name: String, pub description: String, pub algorithm: RoutingAlgorithmWrapper, pub created_at: i64, pub modified_at: i64, pub algorithm_for: TransactionType, } impl EuclidDirFilter for ConnectorSelection { const ALLOWED: &'static [DirKeyKind] = &[ DirKeyKind::PaymentMethod, DirKeyKind::CardBin, DirKeyKind::CardType, DirKeyKind::CardNetwork, DirKeyKind::PayLaterType, DirKeyKind::WalletType, DirKeyKind::UpiType, DirKeyKind::BankRedirectType, DirKeyKind::BankDebitType, DirKeyKind::CryptoType, DirKeyKind::MetaData, DirKeyKind::PaymentAmount, DirKeyKind::PaymentCurrency, DirKeyKind::AuthenticationType, DirKeyKind::MandateAcceptanceType, DirKeyKind::MandateType, DirKeyKind::PaymentType, DirKeyKind::SetupFutureUsage, DirKeyKind::CaptureMethod, DirKeyKind::BillingCountry, DirKeyKind::BusinessCountry, DirKeyKind::BusinessLabel, DirKeyKind::MetaData, DirKeyKind::RewardType, DirKeyKind::VoucherType, DirKeyKind::CardRedirectType, DirKeyKind::BankTransferType, DirKeyKind::RealTimePaymentType, ]; } impl EuclidAnalysable for ConnectorSelection { fn get_dir_value_for_analysis( &self, rule_name: String, ) -> Vec<(euclid::frontend::dir::DirValue, euclid::types::Metadata)> { self.get_connector_list() .into_iter() .map(|connector_choice| { let connector_name = connector_choice.connector.to_string(); let mca_id = connector_choice.merchant_connector_id.clone(); ( euclid::frontend::dir::DirValue::Connector(Box::new(connector_choice.into())), std::collections::HashMap::from_iter([( "CONNECTOR_SELECTION".to_string(), serde_json::json!({ "rule_name": rule_name, "connector_name": connector_name, "mca_id": mca_id, }), )]), ) }) .collect() } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)] pub struct ConnectorVolumeSplit { pub connector: RoutableConnectorChoice, pub split: u8, } /// Routable Connector chosen for a payment #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(from = "RoutableChoiceSerde", into = "RoutableChoiceSerde")] pub struct RoutableConnectorChoice { #[serde(skip)] pub choice_kind: RoutableChoiceKind, pub connector: RoutableConnectors, #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, PartialEq)] pub enum RoutableChoiceKind { OnlyConnector, FullStruct, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(untagged)] pub enum RoutableChoiceSerde { OnlyConnector(Box<RoutableConnectors>), FullStruct { connector: RoutableConnectors, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, }, } impl std::fmt::Display for RoutableConnectorChoice { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let base = self.connector.to_string(); if let Some(mca_id) = &self.merchant_connector_id { return write!(f, "{}:{}", base, mca_id.get_string_repr()); } write!(f, "{base}") } } impl From<RoutableConnectorChoice> for ast::ConnectorChoice { fn from(value: RoutableConnectorChoice) -> Self { Self { connector: value.connector, } } } impl PartialEq for RoutableConnectorChoice { fn eq(&self, other: &Self) -> bool { self.connector.eq(&other.connector) && self.merchant_connector_id.eq(&other.merchant_connector_id) } } impl Eq for RoutableConnectorChoice {} impl From<RoutableChoiceSerde> for RoutableConnectorChoice { fn from(value: RoutableChoiceSerde) -> Self { match value { RoutableChoiceSerde::OnlyConnector(connector) => Self { choice_kind: RoutableChoiceKind::OnlyConnector, connector: *connector, merchant_connector_id: None, }, RoutableChoiceSerde::FullStruct { connector, merchant_connector_id, } => Self { choice_kind: RoutableChoiceKind::FullStruct, connector, merchant_connector_id, }, } } } impl From<RoutableConnectorChoice> for RoutableChoiceSerde { fn from(value: RoutableConnectorChoice) -> Self { match value.choice_kind { RoutableChoiceKind::OnlyConnector => Self::OnlyConnector(Box::new(value.connector)), RoutableChoiceKind::FullStruct => Self::FullStruct { connector: value.connector, merchant_connector_id: value.merchant_connector_id, }, } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct RoutableConnectorChoiceWithStatus { pub routable_connector_choice: RoutableConnectorChoice, pub status: bool, } impl RoutableConnectorChoiceWithStatus { pub fn new(routable_connector_choice: RoutableConnectorChoice, status: bool) -> Self { Self { routable_connector_choice, status, } } } #[derive( Debug, Copy, Clone, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingAlgorithmKind { Single, Priority, VolumeSplit, Advanced, Dynamic, ThreeDsDecisionRule, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingPayloadWrapper { pub updated_config: Vec<RoutableConnectorChoice>, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum RoutingAlgorithmWrapper { Static(StaticRoutingAlgorithm), Dynamic(DynamicRoutingAlgorithm), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(untagged)] pub enum DynamicRoutingAlgorithm { EliminationBasedAlgorithm(EliminationRoutingConfig), SuccessBasedAlgorithm(SuccessBasedRoutingConfig), ContractBasedAlgorithm(ContractBasedRoutingConfig), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde( tag = "type", content = "data", rename_all = "snake_case", try_from = "RoutingAlgorithmSerde" )] pub enum StaticRoutingAlgorithm { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), #[schema(value_type=ProgramConnectorSelection)] Advanced(Program<ConnectorSelection>), #[schema(value_type=ProgramThreeDsDecisionRule)] ThreeDsDecisionRule(Program<ThreeDSDecisionRule>), } #[derive(Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct ProgramThreeDsDecisionRule { pub default_selection: ThreeDSDecisionRule, #[schema(value_type = RuleThreeDsDecisionRule)] pub rules: Vec<ast::Rule<ThreeDSDecisionRule>>, #[schema(value_type = HashMap<String, serde_json::Value>)] pub metadata: std::collections::HashMap<String, serde_json::Value>, } #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct RuleThreeDsDecisionRule { pub name: String, pub connector_selection: ThreeDSDecision, #[schema(value_type = Vec<IfStatement>)] pub statements: Vec<ast::IfStatement>, } impl StaticRoutingAlgorithm { pub fn should_validate_connectors_in_routing_config(&self) -> bool { match self { Self::Single(_) | Self::Priority(_) | Self::VolumeSplit(_) | Self::Advanced(_) => true, Self::ThreeDsDecisionRule(_) => false, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum RoutingAlgorithmSerde { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), Advanced(Program<ConnectorSelection>), ThreeDsDecisionRule(Program<ThreeDSDecisionRule>), } impl TryFrom<RoutingAlgorithmSerde> for StaticRoutingAlgorithm { type Error = error_stack::Report<ParsingError>; fn try_from(value: RoutingAlgorithmSerde) -> Result<Self, Self::Error> { match &value { RoutingAlgorithmSerde::Priority(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Priority Algorithm", ))? } RoutingAlgorithmSerde::VolumeSplit(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Volume split Algorithm", ))? } _ => {} }; Ok(match value { RoutingAlgorithmSerde::Single(i) => Self::Single(i), RoutingAlgorithmSerde::Priority(i) => Self::Priority(i), RoutingAlgorithmSerde::VolumeSplit(i) => Self::VolumeSplit(i), RoutingAlgorithmSerde::Advanced(i) => Self::Advanced(i), RoutingAlgorithmSerde::ThreeDsDecisionRule(i) => Self::ThreeDsDecisionRule(i), }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)] #[serde( tag = "type", content = "data", rename_all = "snake_case", try_from = "StraightThroughAlgorithmSerde", into = "StraightThroughAlgorithmSerde" )] pub enum StraightThroughAlgorithm { #[schema(title = "Single")] Single(Box<RoutableConnectorChoice>), #[schema(title = "Priority")] Priority(Vec<RoutableConnectorChoice>), #[schema(title = "VolumeSplit")] VolumeSplit(Vec<ConnectorVolumeSplit>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum StraightThroughAlgorithmInner { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum StraightThroughAlgorithmSerde { Direct(StraightThroughAlgorithmInner), Nested { algorithm: StraightThroughAlgorithmInner, }, } impl TryFrom<StraightThroughAlgorithmSerde> for StraightThroughAlgorithm { type Error = error_stack::Report<ParsingError>; fn try_from(value: StraightThroughAlgorithmSerde) -> Result<Self, Self::Error> { let inner = match value { StraightThroughAlgorithmSerde::Direct(algorithm) => algorithm, StraightThroughAlgorithmSerde::Nested { algorithm } => algorithm, }; match &inner { StraightThroughAlgorithmInner::Priority(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Priority Algorithm", ))? } StraightThroughAlgorithmInner::VolumeSplit(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Volume split Algorithm", ))? } _ => {} }; Ok(match inner { StraightThroughAlgorithmInner::Single(single) => Self::Single(single), StraightThroughAlgorithmInner::Priority(plist) => Self::Priority(plist), StraightThroughAlgorithmInner::VolumeSplit(vsplit) => Self::VolumeSplit(vsplit), }) } } impl From<StraightThroughAlgorithm> for StraightThroughAlgorithmSerde { fn from(value: StraightThroughAlgorithm) -> Self { let inner = match value { StraightThroughAlgorithm::Single(conn) => StraightThroughAlgorithmInner::Single(conn), StraightThroughAlgorithm::Priority(plist) => { StraightThroughAlgorithmInner::Priority(plist) } StraightThroughAlgorithm::VolumeSplit(vsplit) => { StraightThroughAlgorithmInner::VolumeSplit(vsplit) } }; Self::Nested { algorithm: inner } } } impl From<StraightThroughAlgorithm> for StaticRoutingAlgorithm { fn from(value: StraightThroughAlgorithm) -> Self { match value { StraightThroughAlgorithm::Single(conn) => Self::Single(conn), StraightThroughAlgorithm::Priority(conns) => Self::Priority(conns), StraightThroughAlgorithm::VolumeSplit(splits) => Self::VolumeSplit(splits), } } } impl StaticRoutingAlgorithm { pub fn get_kind(&self) -> RoutingAlgorithmKind { match self { Self::Single(_) => RoutingAlgorithmKind::Single, Self::Priority(_) => RoutingAlgorithmKind::Priority, Self::VolumeSplit(_) => RoutingAlgorithmKind::VolumeSplit, Self::Advanced(_) => RoutingAlgorithmKind::Advanced, Self::ThreeDsDecisionRule(_) => RoutingAlgorithmKind::ThreeDsDecisionRule, } } } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingAlgorithmRef { pub algorithm_id: Option<common_utils::id_type::RoutingId>, pub timestamp: i64, pub config_algo_id: Option<String>, pub surcharge_config_algo_id: Option<String>, } impl RoutingAlgorithmRef { pub fn update_algorithm_id(&mut self, new_id: common_utils::id_type::RoutingId) { self.algorithm_id = Some(new_id); self.timestamp = common_utils::date_time::now_unix_timestamp(); } pub fn update_conditional_config_id(&mut self, ids: String) { self.config_algo_id = Some(ids); self.timestamp = common_utils::date_time::now_unix_timestamp(); } pub fn update_surcharge_config_id(&mut self, ids: String) { self.surcharge_config_algo_id = Some(ids); self.timestamp = common_utils::date_time::now_unix_timestamp(); } pub fn parse_routing_algorithm( value: Option<pii::SecretSerdeValue>, ) -> Result<Option<Self>, error_stack::Report<ParsingError>> { value .map(|val| val.parse_value::<Self>("RoutingAlgorithmRef")) .transpose() } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingDictionaryRecord { #[schema(value_type = String)] pub id: common_utils::id_type::RoutingId, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, pub name: String, pub kind: RoutingAlgorithmKind, pub description: String, pub created_at: i64, pub modified_at: i64, pub algorithm_for: Option<TransactionType>, pub decision_engine_routing_id: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingDictionary { #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, pub active_id: Option<String>, pub records: Vec<RoutingDictionaryRecord>, } #[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)] #[serde(untagged)] pub enum RoutingKind { Config(RoutingDictionary), RoutingAlgorithm(Vec<RoutingDictionaryRecord>), } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct RoutingAlgorithmId { #[schema(value_type = String)] pub routing_algorithm_id: common_utils::id_type::RoutingId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingLinkWrapper { pub profile_id: common_utils::id_type::ProfileId, pub algorithm_id: RoutingAlgorithmId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DynamicAlgorithmWithTimestamp<T> { pub algorithm_id: Option<T>, pub timestamp: i64, } impl<T> DynamicAlgorithmWithTimestamp<T> { pub fn new(algorithm_id: Option<T>) -> Self { Self { algorithm_id, timestamp: common_utils::date_time::now_unix_timestamp(), } } } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct DynamicRoutingAlgorithmRef { pub success_based_algorithm: Option<SuccessBasedAlgorithm>, pub dynamic_routing_volume_split: Option<u8>, pub elimination_routing_algorithm: Option<EliminationRoutingAlgorithm>, pub contract_based_routing: Option<ContractRoutingAlgorithm>, #[serde(default)] pub is_merchant_created_in_decision_engine: bool, } pub trait DynamicRoutingAlgoAccessor { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>; fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures; } impl DynamicRoutingAlgoAccessor for SuccessBasedAlgorithm { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { self.algorithm_id_with_timestamp } fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { &mut self.enabled_feature } } impl DynamicRoutingAlgoAccessor for EliminationRoutingAlgorithm { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { self.algorithm_id_with_timestamp } fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { &mut self.enabled_feature } } impl DynamicRoutingAlgoAccessor for ContractRoutingAlgorithm { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { self.algorithm_id_with_timestamp } fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { &mut self.enabled_feature } } impl EliminationRoutingAlgorithm { pub fn new( algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< common_utils::id_type::RoutingId, >, ) -> Self { Self { algorithm_id_with_timestamp, enabled_feature: DynamicRoutingFeatures::None, } } } impl SuccessBasedAlgorithm { pub fn new( algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< common_utils::id_type::RoutingId, >, ) -> Self { Self { algorithm_id_with_timestamp, enabled_feature: DynamicRoutingFeatures::None, } } } impl DynamicRoutingAlgorithmRef { pub fn update(&mut self, new: Self) { if let Some(elimination_routing_algorithm) = new.elimination_routing_algorithm { self.elimination_routing_algorithm = Some(elimination_routing_algorithm) } if let Some(success_based_algorithm) = new.success_based_algorithm { self.success_based_algorithm = Some(success_based_algorithm) } if let Some(contract_based_routing) = new.contract_based_routing { self.contract_based_routing = Some(contract_based_routing) } } pub fn update_enabled_features( &mut self, algo_type: DynamicRoutingType, feature_to_enable: DynamicRoutingFeatures, ) { match algo_type { DynamicRoutingType::SuccessRateBasedRouting => { self.success_based_algorithm .as_mut() .map(|algo| algo.enabled_feature = feature_to_enable); } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm .as_mut() .map(|algo| algo.enabled_feature = feature_to_enable); } DynamicRoutingType::ContractBasedRouting => { self.contract_based_routing .as_mut() .map(|algo| algo.enabled_feature = feature_to_enable); } } } pub fn update_volume_split(&mut self, volume: Option<u8>) { self.dynamic_routing_volume_split = volume } pub fn update_merchant_creation_status_in_decision_engine(&mut self, is_created: bool) { self.is_merchant_created_in_decision_engine = is_created; } pub fn is_success_rate_routing_enabled(&self) -> bool { self.success_based_algorithm .as_ref() .map(|success_based_routing| { success_based_routing.enabled_feature == DynamicRoutingFeatures::DynamicConnectorSelection || success_based_routing.enabled_feature == DynamicRoutingFeatures::Metrics }) .unwrap_or_default() } pub fn is_elimination_enabled(&self) -> bool { self.elimination_routing_algorithm .as_ref() .map(|elimination_routing| { elimination_routing.enabled_feature == DynamicRoutingFeatures::DynamicConnectorSelection || elimination_routing.enabled_feature == DynamicRoutingFeatures::Metrics }) .unwrap_or_default() } } #[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)] pub struct RoutingVolumeSplit { pub routing_type: RoutingType, pub split: u8, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingVolumeSplitWrapper { pub routing_info: RoutingVolumeSplit, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum RoutingType { #[default] Static, Dynamic, } impl RoutingType { pub fn is_dynamic_routing(self) -> bool { self == Self::Dynamic } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SuccessBasedAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractRoutingAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct EliminationRoutingAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, } impl EliminationRoutingAlgorithm { pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) { self.enabled_feature = feature_to_enable } } impl SuccessBasedAlgorithm { pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) { self.enabled_feature = feature_to_enable } } impl DynamicRoutingAlgorithmRef { pub fn update_algorithm_id( &mut self, new_id: common_utils::id_type::RoutingId, enabled_feature: DynamicRoutingFeatures, dynamic_routing_type: DynamicRoutingType, ) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } DynamicRoutingType::ContractBasedRouting => { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } }; } pub fn update_feature( &mut self, enabled_feature: DynamicRoutingFeatures, dynamic_routing_type: DynamicRoutingType, ) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature, }) } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature, }) } DynamicRoutingType::ContractBasedRouting => { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature, }) } }; } pub fn disable_algorithm_id(&mut self, dynamic_routing_type: DynamicRoutingType) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { if let Some(success_based_algo) = &self.success_based_algorithm { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: success_based_algo.enabled_feature, }); } } DynamicRoutingType::EliminationRouting => { if let Some(elimination_based_algo) = &self.elimination_routing_algorithm { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: elimination_based_algo.enabled_feature, }); } } DynamicRoutingType::ContractBasedRouting => { if let Some(contract_based_algo) = &self.contract_based_routing { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: contract_based_algo.enabled_feature, }); } } } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ToggleDynamicRoutingQuery { pub enable: DynamicRoutingFeatures, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CreateDynamicRoutingQuery { pub enable: DynamicRoutingFeatures, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DynamicRoutingVolumeSplitQuery { pub split: u8, } #[derive( Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum DynamicRoutingFeatures { Metrics, DynamicConnectorSelection, #[default] None, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DynamicRoutingUpdateConfigQuery { #[schema(value_type = String)] pub algorithm_id: common_utils::id_type::RoutingId, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ToggleDynamicRoutingWrapper { pub profile_id: common_utils::id_type::ProfileId, pub feature_to_enable: DynamicRoutingFeatures, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ToggleDynamicRoutingPath { #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct CreateDynamicRoutingWrapper { pub profile_id: common_utils::id_type::ProfileId, pub feature_to_enable: DynamicRoutingFeatures, pub payload: DynamicRoutingPayload, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum DynamicRoutingPayload { SuccessBasedRoutingPayload(SuccessBasedRoutingConfig), EliminationRoutingPayload(EliminationRoutingConfig), } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct RoutingVolumeSplitResponse { pub split: u8, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct EliminationRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, pub elimination_analyser_config: Option<EliminationAnalyserConfig>, #[schema(value_type = DecisionEngineEliminationData)] pub decision_engine_configs: Option<open_router::DecisionEngineEliminationData>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, ToSchema)] #[serde(deny_unknown_fields)] pub struct EliminationAnalyserConfig { pub bucket_size: Option<u64>, pub bucket_leak_interval_in_secs: Option<u64>, } impl EliminationAnalyserConfig { pub fn update(&mut self, new: Self) { if let Some(bucket_size) = new.bucket_size { self.bucket_size = Some(bucket_size) } if let Some(bucket_leak_interval_in_secs) = new.bucket_leak_interval_in_secs { self.bucket_leak_interval_in_secs = Some(bucket_leak_interval_in_secs) } } } impl Default for EliminationRoutingConfig { fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), elimination_analyser_config: Some(EliminationAnalyserConfig { bucket_size: Some(5), bucket_leak_interval_in_secs: Some(60), }), decision_engine_configs: None, } } } impl EliminationRoutingConfig { pub fn update(&mut self, new: Self) { if let Some(params) = new.params { self.params = Some(params) } if let Some(new_config) = new.elimination_analyser_config { self.elimination_analyser_config .as_mut() .map(|config| config.update(new_config)); } if let Some(new_config) = new.decision_engine_configs { self.decision_engine_configs .as_mut() .map(|config| config.update(new_config)); } } pub fn open_router_config_default() -> Self { Self { elimination_analyser_config: None, params: None, decision_engine_configs: Some(open_router::DecisionEngineEliminationData { threshold: DEFAULT_ELIMINATION_THRESHOLD, }), } } pub fn get_decision_engine_configs( &self, ) -> Result<open_router::DecisionEngineEliminationData, error_stack::Report<ValidationError>> { self.decision_engine_configs .clone() .ok_or(error_stack::Report::new( ValidationError::MissingRequiredField { field_name: "decision_engine_configs".to_string(), }, )) } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct SuccessBasedRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, pub config: Option<SuccessBasedRoutingConfigBody>, #[schema(value_type = DecisionEngineSuccessRateData)] pub decision_engine_configs: Option<open_router::DecisionEngineSuccessRateData>, } impl Default for SuccessBasedRoutingConfig { fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), config: Some(SuccessBasedRoutingConfigBody { min_aggregates_size: Some(5), default_success_rate: Some(100.0), max_aggregates_size: Some(8), current_block_threshold: Some(CurrentBlockThreshold { duration_in_mins: None, max_total_count: Some(5), }), specificity_level: SuccessRateSpecificityLevel::default(), exploration_percent: Some(20.0), shuffle_on_tie_during_exploitation: Some(false), }), decision_engine_configs: None, } } } #[derive( serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, PartialEq, strum::Display, )] pub enum DynamicRoutingConfigParams { PaymentMethod, PaymentMethodType, AuthenticationType, Currency, Country, CardNetwork, CardBin, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct SuccessBasedRoutingConfigBody { pub min_aggregates_size: Option<u32>, pub default_success_rate: Option<f64>, pub max_aggregates_size: Option<u32>, pub current_block_threshold: Option<CurrentBlockThreshold>, #[serde(default)] pub specificity_level: SuccessRateSpecificityLevel, pub exploration_percent: Option<f64>, pub shuffle_on_tie_during_exploitation: Option<bool>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct CurrentBlockThreshold { pub duration_in_mins: Option<u64>, pub max_total_count: Option<u64>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Default, Clone, Copy, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SuccessRateSpecificityLevel { #[default] Merchant, Global, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SuccessBasedRoutingPayloadWrapper { pub updated_config: SuccessBasedRoutingConfig, pub algorithm_id: common_utils::id_type::RoutingId, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct EliminationRoutingPayloadWrapper { pub updated_config: EliminationRoutingConfig, pub algorithm_id: common_utils::id_type::RoutingId, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractBasedRoutingPayloadWrapper { pub updated_config: ContractBasedRoutingConfig, pub algorithm_id: common_utils::id_type::RoutingId, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractBasedRoutingSetupPayloadWrapper { pub config: Option<ContractBasedRoutingConfig>, pub profile_id: common_utils::id_type::ProfileId, pub features_to_enable: DynamicRoutingFeatures, } #[derive( Debug, Clone, Copy, strum::Display, serde::Serialize, serde::Deserialize, PartialEq, Eq, )] pub enum DynamicRoutingType { SuccessRateBasedRouting, EliminationRouting, ContractBasedRouting, } impl SuccessBasedRoutingConfig { pub fn update(&mut self, new: Self) { if let Some(params) = new.params { self.params = Some(params) } if let Some(new_config) = new.config { self.config.as_mut().map(|config| config.update(new_config)); } if let Some(new_config) = new.decision_engine_configs { self.decision_engine_configs .as_mut() .map(|config| config.update(new_config)); } } pub fn open_router_config_default() -> Self { Self { params: None, config: None, decision_engine_configs: Some(open_router::DecisionEngineSuccessRateData { default_latency_threshold: Some(DEFAULT_LATENCY_THRESHOLD), default_bucket_size: Some(DEFAULT_BUCKET_SIZE), default_hedging_percent: Some(DEFAULT_HEDGING_PERCENT), default_lower_reset_factor: None, default_upper_reset_factor: None, default_gateway_extra_score: None, sub_level_input_config: Some(vec![ open_router::DecisionEngineSRSubLevelInputConfig { payment_method_type: Some(DEFAULT_PAYMENT_METHOD.to_string()), payment_method: None, latency_threshold: None, bucket_size: Some(DEFAULT_BUCKET_SIZE), hedging_percent: Some(DEFAULT_HEDGING_PERCENT), lower_reset_factor: None, upper_reset_factor: None, gateway_extra_score: None, }, ]), }), } } pub fn get_decision_engine_configs( &self, ) -> Result<open_router::DecisionEngineSuccessRateData, error_stack::Report<ValidationError>> { self.decision_engine_configs .clone() .ok_or(error_stack::Report::new( ValidationError::MissingRequiredField { field_name: "decision_engine_configs".to_string(), }, )) } } impl SuccessBasedRoutingConfigBody { pub fn update(&mut self, new: Self) { if let Some(min_aggregates_size) = new.min_aggregates_size { self.min_aggregates_size = Some(min_aggregates_size) } if let Some(default_success_rate) = new.default_success_rate { self.default_success_rate = Some(default_success_rate) } if let Some(max_aggregates_size) = new.max_aggregates_size { self.max_aggregates_size = Some(max_aggregates_size) } if let Some(current_block_threshold) = new.current_block_threshold { self.current_block_threshold .as_mut() .map(|threshold| threshold.update(current_block_threshold)); } self.specificity_level = new.specificity_level; if let Some(exploration_percent) = new.exploration_percent { self.exploration_percent = Some(exploration_percent); } if let Some(shuffle_on_tie_during_exploitation) = new.shuffle_on_tie_during_exploitation { self.shuffle_on_tie_during_exploitation = Some(shuffle_on_tie_during_exploitation); } } } impl CurrentBlockThreshold { pub fn update(&mut self, new: Self) { if let Some(max_total_count) = new.max_total_count { self.max_total_count = Some(max_total_count) } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct ContractBasedRoutingConfig { pub config: Option<ContractBasedRoutingConfigBody>, pub label_info: Option<Vec<LabelInformation>>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct ContractBasedRoutingConfigBody { pub constants: Option<Vec<f64>>, pub time_scale: Option<ContractBasedTimeScale>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct LabelInformation { pub label: String, pub target_count: u64, pub target_time: u64, #[schema(value_type = String)] pub mca_id: common_utils::id_type::MerchantConnectorAccountId, } impl LabelInformation { pub fn update_target_time(&mut self, new: &Self) { self.target_time = new.target_time; } pub fn update_target_count(&mut self, new: &Self) { self.target_count = new.target_count; } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ContractBasedTimeScale { Day, Month, } impl Default for ContractBasedRoutingConfig { fn default() -> Self { Self { config: Some(ContractBasedRoutingConfigBody { constants: Some(vec![0.7, 0.35]), time_scale: Some(ContractBasedTimeScale::Day), }), label_info: None, } } } impl ContractBasedRoutingConfig { pub fn update(&mut self, new: Self) { if let Some(new_config) = new.config { self.config.as_mut().map(|config| config.update(new_config)); } if let Some(new_label_info) = new.label_info { new_label_info.iter().for_each(|new_label_info| { if let Some(existing_label_infos) = &mut self.label_info { let mut updated = false; for existing_label_info in &mut *existing_label_infos { if existing_label_info.mca_id == new_label_info.mca_id { existing_label_info.update_target_time(new_label_info); existing_label_info.update_target_count(new_label_info); updated = true; } } if !updated { existing_label_infos.push(new_label_info.clone()); } } else { self.label_info = Some(vec![new_label_info.clone()]); } }); } } } impl ContractBasedRoutingConfigBody { pub fn update(&mut self, new: Self) { if let Some(new_cons) = new.constants { self.constants = Some(new_cons) } if let Some(new_time_scale) = new.time_scale { self.time_scale = Some(new_time_scale) } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct RoutableConnectorChoiceWithBucketName { pub routable_connector_choice: RoutableConnectorChoice, pub bucket_name: String, } impl RoutableConnectorChoiceWithBucketName { pub fn new(routable_connector_choice: RoutableConnectorChoice, bucket_name: String) -> Self { Self { routable_connector_choice, bucket_name, } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalSuccessRateConfigEventRequest { pub min_aggregates_size: Option<u32>, pub default_success_rate: Option<f64>, pub specificity_level: SuccessRateSpecificityLevel, pub exploration_percent: Option<f64>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalSuccessRateEventRequest { pub id: String, pub params: String, pub labels: Vec<String>, pub config: Option<CalSuccessRateConfigEventRequest>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct EliminationRoutingEventBucketConfig { pub bucket_size: Option<u64>, pub bucket_leak_interval_in_secs: Option<u64>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct EliminationRoutingEventRequest { pub id: String, pub params: String, pub labels: Vec<String>, pub config: Option<EliminationRoutingEventBucketConfig>, } /// API-1 types #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalContractScoreEventRequest { pub id: String, pub params: String, pub labels: Vec<String>, pub config: Option<ContractBasedRoutingConfig>, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct LabelWithScoreEventResponse { pub score: f64, pub label: String, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct CalSuccessRateEventResponse { pub labels_with_score: Vec<LabelWithScoreEventResponse>, pub routing_approach: RoutingApproach, } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum RoutingApproach { Exploitation, Exploration, Elimination, ContractBased, Default, } impl RoutingApproach { pub fn from_decision_engine_approach(approach: &str) -> Self { match approach { "SR_SELECTION_V3_ROUTING" => Self::Exploitation, "SR_V3_HEDGING" => Self::Exploration, _ => Self::Default, } } } impl std::fmt::Display for RoutingApproach { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Exploitation => write!(f, "Exploitation"), Self::Exploration => write!(f, "Exploration"), Self::Elimination => write!(f, "Elimination"), Self::ContractBased => write!(f, "ContractBased"), Self::Default => write!(f, "Default"), } } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RuleMigrationQuery { pub profile_id: common_utils::id_type::ProfileId, pub merchant_id: common_utils::id_type::MerchantId, pub limit: Option<u32>, pub offset: Option<u32>, } impl RuleMigrationQuery { pub fn validated_limit(&self) -> u32 { self.limit.unwrap_or(50).min(1000) } } #[derive(Debug, serde::Serialize)] pub struct RuleMigrationResult { pub success: Vec<RuleMigrationResponse>, pub errors: Vec<RuleMigrationError>, } #[derive(Debug, serde::Serialize)] pub struct RuleMigrationResponse { pub profile_id: common_utils::id_type::ProfileId, pub euclid_algorithm_id: common_utils::id_type::RoutingId, pub decision_engine_algorithm_id: String, pub is_active_rule: bool, } #[derive(Debug, serde::Serialize)] pub struct RuleMigrationError { pub profile_id: common_utils::id_type::ProfileId, pub algorithm_id: common_utils::id_type::RoutingId, pub error: String, } impl RuleMigrationResponse { pub fn new( profile_id: common_utils::id_type::ProfileId, euclid_algorithm_id: common_utils::id_type::RoutingId, decision_engine_algorithm_id: String, is_active_rule: bool, ) -> Self { Self { profile_id, euclid_algorithm_id, decision_engine_algorithm_id, is_active_rule, } } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingResultSource { /// External Decision Engine DecisionEngine, /// Inbuilt Hyperswitch Routing Engine HyperswitchRouting, } //TODO: temporary change will be refactored afterwards #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, ToSchema)] pub struct RoutingEvaluateRequest { pub created_by: String, #[schema(value_type = Object)] ///Parameters that can be used in the routing evaluate request. ///eg: {"parameters": { /// "payment_method": {"type": "enum_variant", "value": "card"}, /// "payment_method_type": {"type": "enum_variant", "value": "credit"}, /// "amount": {"type": "number", "value": 10}, /// "currency": {"type": "str_value", "value": "INR"}, /// "authentication_type": {"type": "enum_variant", "value": "three_ds"}, /// "card_bin": {"type": "str_value", "value": "424242"}, /// "capture_method": {"type": "enum_variant", "value": "scheduled"}, /// "business_country": {"type": "str_value", "value": "IN"}, /// "billing_country": {"type": "str_value", "value": "IN"}, /// "business_label": {"type": "str_value", "value": "business_label"}, /// "setup_future_usage": {"type": "enum_variant", "value": "off_session"}, /// "card_network": {"type": "enum_variant", "value": "visa"}, /// "payment_type": {"type": "enum_variant", "value": "recurring_mandate"}, /// "mandate_type": {"type": "enum_variant", "value": "single_use"}, /// "mandate_acceptance_type": {"type": "enum_variant", "value": "online"}, /// "metadata":{"type": "metadata_variant", "value": {"key": "key1", "value": "value1"}} /// }} pub parameters: std::collections::HashMap<String, Option<ValueType>>, pub fallback_output: Vec<DeRoutableConnectorChoice>, } impl common_utils::events::ApiEventMetric for RoutingEvaluateRequest {} #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RoutingEvaluateResponse { pub status: String, pub output: serde_json::Value, #[serde(deserialize_with = "deserialize_connector_choices")] pub evaluated_output: Vec<RoutableConnectorChoice>, #[serde(deserialize_with = "deserialize_connector_choices")] pub eligible_connectors: Vec<RoutableConnectorChoice>, } impl common_utils::events::ApiEventMetric for RoutingEvaluateResponse {} fn deserialize_connector_choices<'de, D>( deserializer: D, ) -> Result<Vec<RoutableConnectorChoice>, D::Error> where D: serde::Deserializer<'de>, { let infos = Vec::<DeRoutableConnectorChoice>::deserialize(deserializer)?; Ok(infos .into_iter() .map(RoutableConnectorChoice::from) .collect()) } impl From<DeRoutableConnectorChoice> for RoutableConnectorChoice { fn from(choice: DeRoutableConnectorChoice) -> Self { Self { choice_kind: RoutableChoiceKind::FullStruct, connector: choice.gateway_name, merchant_connector_id: choice.gateway_id, } } } /// Routable Connector chosen for a payment #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DeRoutableConnectorChoice { pub gateway_name: RoutableConnectors, #[schema(value_type = String)] pub gateway_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } /// Represents a value in the DSL #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "value", rename_all = "snake_case")] pub enum ValueType { /// Represents a number literal Number(u64), /// Represents an enum variant EnumVariant(String), /// Represents a Metadata variant MetadataVariant(MetadataValue), /// Represents a arbitrary String value StrValue(String), /// Represents a global reference, which is a reference to a global variable GlobalRef(String), /// Represents an array of numbers. This is basically used for /// "one of the given numbers" operations /// eg: payment.method.amount = (1, 2, 3) NumberArray(Vec<u64>), /// Similar to NumberArray but for enum variants /// eg: payment.method.cardtype = (debit, credit) EnumVariantArray(Vec<String>), /// Like a number array but can include comparisons. Useful for /// conditions like "500 < amount < 1000" /// eg: payment.amount = (> 500, < 1000) NumberComparisonArray(Vec<NumberComparison>), } #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)] pub struct MetadataValue { pub key: String, pub value: String, } /// Represents a number comparison for "NumberComparisonArrayValue" #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct NumberComparison { pub comparison_type: ComparisonType, pub number: u64, } /// Conditional comparison type #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ComparisonType { Equal, NotEqual, LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, }
crates/api_models/src/routing.rs
api_models::src::routing
12,112
true
// File: crates/api_models/src/health_check.rs // Module: api_models::src::health_check use std::collections::hash_map::HashMap; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RouterHealthCheckResponse { pub database: bool, pub redis: bool, #[serde(skip_serializing_if = "Option::is_none")] pub vault: Option<bool>, #[cfg(feature = "olap")] pub analytics: bool, #[cfg(feature = "olap")] pub opensearch: bool, pub outgoing_request: bool, #[cfg(feature = "dynamic_routing")] pub grpc_health_check: HealthCheckMap, #[cfg(feature = "dynamic_routing")] pub decision_engine: bool, pub unified_connector_service: Option<bool>, } impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {} /// gRPC based services eligible for Health check #[derive(Debug, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum HealthCheckServices { /// Dynamic routing service DynamicRoutingService, } pub type HealthCheckMap = HashMap<HealthCheckServices, bool>; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SchedulerHealthCheckResponse { pub database: bool, pub redis: bool, pub outgoing_request: bool, } pub enum HealthState { Running, Error, NotApplicable, } impl From<HealthState> for bool { fn from(value: HealthState) -> Self { match value { HealthState::Running => true, HealthState::Error | HealthState::NotApplicable => false, } } } impl From<HealthState> for Option<bool> { fn from(value: HealthState) -> Self { match value { HealthState::Running => Some(true), HealthState::Error => Some(false), HealthState::NotApplicable => None, } } } impl common_utils::events::ApiEventMetric for SchedulerHealthCheckResponse {}
crates/api_models/src/health_check.rs
api_models::src::health_check
441
true
// File: crates/api_models/src/ephemeral_key.rs // Module: api_models::src::ephemeral_key use common_utils::id_type; #[cfg(feature = "v2")] use masking::Secret; use serde; use utoipa::ToSchema; #[cfg(feature = "v1")] /// Information required to create an ephemeral key. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct EphemeralKeyCreateRequest { /// Customer ID for which an ephemeral key must be created #[schema( min_length = 1, max_length = 64, value_type = String, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44" )] pub customer_id: id_type::CustomerId, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ResourceId { #[schema(value_type = String)] Customer(id_type::GlobalCustomerId), } #[cfg(feature = "v2")] /// Information required to create a client secret. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ClientSecretCreateRequest { /// Resource ID for which a client secret must be created pub resource_id: ResourceId, } #[cfg(feature = "v2")] /// client_secret for the resource_id mentioned #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema)] pub struct ClientSecretResponse { /// Client Secret id #[schema(value_type = String, max_length = 32, min_length = 1)] pub id: id_type::ClientSecretId, /// resource_id to which this client secret belongs to #[schema(value_type = ResourceId)] pub resource_id: ResourceId, /// time at which this client secret was created pub created_at: time::PrimitiveDateTime, /// time at which this client secret would expire pub expires: time::PrimitiveDateTime, #[schema(value_type=String)] /// client secret pub secret: Secret<String>, } #[cfg(feature = "v1")] impl common_utils::events::ApiEventMetric for EphemeralKeyCreateRequest { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[cfg(feature = "v1")] impl common_utils::events::ApiEventMetric for EphemeralKeyCreateResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for ClientSecretCreateRequest { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for ClientSecretResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[cfg(feature = "v1")] /// ephemeral_key for the customer_id mentioned #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema)] pub struct EphemeralKeyCreateResponse { /// customer_id to which this ephemeral key belongs to #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// time at which this ephemeral key was created pub created_at: i64, /// time at which this ephemeral key would expire pub expires: i64, /// ephemeral key pub secret: String, }
crates/api_models/src/ephemeral_key.rs
api_models::src::ephemeral_key
896
true
// File: crates/api_models/src/mandates.rs // Module: api_models::src::mandates use common_types::payments as common_payments_types; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::enums as api_enums; #[derive(Default, Debug, Deserialize, Serialize)] pub struct MandateId { pub mandate_id: String, } #[derive(Default, Debug, Deserialize, Serialize, ToSchema)] pub struct MandateRevokedResponse { /// The identifier for mandate pub mandate_id: String, /// The status for mandates #[schema(value_type = MandateStatus)] pub status: api_enums::MandateStatus, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, } #[derive(Default, Debug, Deserialize, Serialize, ToSchema, Clone)] pub struct MandateResponse { /// The identifier for mandate pub mandate_id: String, /// The status for mandates #[schema(value_type = MandateStatus)] pub status: api_enums::MandateStatus, /// The identifier for payment method pub payment_method_id: String, /// The payment method pub payment_method: String, /// The payment method type pub payment_method_type: Option<String>, /// The card details for mandate pub card: Option<MandateCardDetails>, /// Details about the customer’s acceptance #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>, } #[derive(Default, Debug, Deserialize, Serialize, ToSchema, Clone)] pub struct MandateCardDetails { /// The last 4 digits of card pub last4_digits: Option<String>, /// The expiry month of card #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, /// The expiry year of card #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, /// The card holder name #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, /// The token from card locker #[schema(value_type = Option<String>)] pub card_token: Option<Secret<String>>, /// The card scheme network for the particular card pub scheme: Option<String>, /// The country code in in which the card was issued pub issuer_country: Option<String>, #[schema(value_type = Option<String>)] /// A unique identifier alias to identify a particular card pub card_fingerprint: Option<Secret<String>>, /// The first 6 digits of card pub card_isin: Option<String>, /// The bank that issued the card pub card_issuer: Option<String>, /// The network that facilitates payment card transactions #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// The type of the payment card pub card_type: Option<String>, /// The nick_name of the card holder #[schema(value_type = Option<String>)] pub nick_name: Option<Secret<String>>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MandateListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// offset on the number of objects to return pub offset: Option<i64>, /// status of the mandate pub mandate_status: Option<api_enums::MandateStatus>, /// connector linked to mandate pub connector: Option<String>, /// The time at which mandate is created #[schema(example = "2022-09-10T10:11:12Z")] pub created_time: Option<PrimitiveDateTime>, /// Time less than the mandate created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(rename = "created_time.lt")] pub created_time_lt: Option<PrimitiveDateTime>, /// Time greater than the mandate created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(rename = "created_time.gt")] pub created_time_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the mandate created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(rename = "created_time.lte")] pub created_time_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the mandate created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(rename = "created_time.gte")] pub created_time_gte: Option<PrimitiveDateTime>, } /// Details required for recurring payment #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum RecurringDetails { MandateId(String), PaymentMethodId(String), ProcessorPaymentToken(ProcessorPaymentToken), /// Network transaction ID and Card Details for MIT payments when payment_method_data /// is not stored in the application NetworkTransactionIdAndCardDetails(NetworkTransactionIdAndCardDetails), } /// Processor payment token for MIT payments where payment_method_data is not available #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct ProcessorPaymentToken { pub processor_payment_token: String, #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct NetworkTransactionIdAndCardDetails { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: cards::CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, /// The network transaction ID provided by the card network during a CIT (Customer Initiated Transaction), /// where `setup_future_usage` is set to `off_session`. #[schema(value_type = String)] pub network_transaction_id: Secret<String>, } impl RecurringDetails { pub fn is_network_transaction_id_and_card_details_flow(self) -> bool { matches!(self, Self::NetworkTransactionIdAndCardDetails(_)) } }
crates/api_models/src/mandates.rs
api_models::src::mandates
1,761
true
// File: crates/api_models/src/feature_matrix.rs // Module: api_models::src::feature_matrix use std::collections::HashSet; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; #[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)] pub struct FeatureMatrixRequest { // List of connectors for which the feature matrix is requested #[schema(value_type = Option<Vec<Connector>>)] pub connectors: Option<Vec<common_enums::connector_enums::Connector>>, } #[derive(Debug, Clone, ToSchema, Serialize)] pub struct CardSpecificFeatures { /// Indicates whether three_ds card payments are supported #[schema(value_type = FeatureStatus)] pub three_ds: common_enums::FeatureStatus, /// Indicates whether non three_ds card payments are supported #[schema(value_type = FeatureStatus)] pub no_three_ds: common_enums::FeatureStatus, /// List of supported card networks #[schema(value_type = Vec<CardNetwork>)] pub supported_card_networks: Vec<common_enums::CardNetwork>, } #[derive(Debug, Clone, ToSchema, Serialize)] #[serde(untagged)] pub enum PaymentMethodSpecificFeatures { /// Card specific features Card(CardSpecificFeatures), } #[derive(Debug, ToSchema, Serialize)] pub struct SupportedPaymentMethod { /// The payment method supported by the connector #[schema(value_type = PaymentMethod)] pub payment_method: common_enums::PaymentMethod, /// The payment method type supported by the connector #[schema(value_type = PaymentMethodType)] pub payment_method_type: common_enums::PaymentMethodType, /// The display name of the payment method type pub payment_method_type_display_name: String, /// Indicates whether the payment method supports mandates via the connector #[schema(value_type = FeatureStatus)] pub mandates: common_enums::FeatureStatus, /// Indicates whether the payment method supports refunds via the connector #[schema(value_type = FeatureStatus)] pub refunds: common_enums::FeatureStatus, /// List of supported capture methods supported by the payment method type #[schema(value_type = Vec<CaptureMethod>)] pub supported_capture_methods: Vec<common_enums::CaptureMethod>, /// Information on the Payment method specific payment features #[serde(flatten)] pub payment_method_specific_features: Option<PaymentMethodSpecificFeatures>, /// List of countries supported by the payment method type via the connector #[schema(value_type = Option<HashSet<CountryAlpha3>>)] pub supported_countries: Option<HashSet<common_enums::CountryAlpha3>>, /// List of currencies supported by the payment method type via the connector #[schema(value_type = Option<HashSet<Currency>>)] pub supported_currencies: Option<HashSet<common_enums::Currency>>, } #[derive(Debug, ToSchema, Serialize)] pub struct ConnectorFeatureMatrixResponse { /// The name of the connector pub name: String, /// The display name of the connector pub display_name: String, /// The description of the connector pub description: String, /// The category of the connector #[schema(value_type = HyperswitchConnectorCategory, example = "payment_gateway")] pub category: common_enums::HyperswitchConnectorCategory, /// The integration status of the connector #[schema(value_type = ConnectorIntegrationStatus, example = "live")] pub integration_status: common_enums::ConnectorIntegrationStatus, /// The list of payment methods supported by the connector pub supported_payment_methods: Option<Vec<SupportedPaymentMethod>>, /// The list of webhook flows supported by the connector #[schema(value_type = Option<Vec<EventClass>>)] pub supported_webhook_flows: Option<Vec<common_enums::EventClass>>, } #[derive(Debug, Serialize, ToSchema)] pub struct FeatureMatrixListResponse { /// The number of connectors included in the response pub connector_count: usize, // The list of payments response objects pub connectors: Vec<ConnectorFeatureMatrixResponse>, } impl common_utils::events::ApiEventMetric for FeatureMatrixListResponse {} impl common_utils::events::ApiEventMetric for FeatureMatrixRequest {}
crates/api_models/src/feature_matrix.rs
api_models::src::feature_matrix
887
true
// File: crates/api_models/src/apple_pay_certificates_migration.rs // Module: api_models::src::apple_pay_certificates_migration #[derive(Debug, Clone, serde::Serialize)] pub struct ApplePayCertificatesMigrationResponse { pub migration_successful: Vec<common_utils::id_type::MerchantId>, pub migration_failed: Vec<common_utils::id_type::MerchantId>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct ApplePayCertificatesMigrationRequest { pub merchant_ids: Vec<common_utils::id_type::MerchantId>, } impl common_utils::events::ApiEventMetric for ApplePayCertificatesMigrationRequest {}
crates/api_models/src/apple_pay_certificates_migration.rs
api_models::src::apple_pay_certificates_migration
138
true
// File: crates/api_models/src/three_ds_decision_rule.rs // Module: api_models::src::three_ds_decision_rule use euclid::frontend::dir::enums::{ CustomerDeviceDisplaySize, CustomerDevicePlatform, CustomerDeviceType, }; use utoipa::ToSchema; /// Represents the payment data used in the 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentData { /// The amount of the payment in minor units (e.g., cents for USD). #[schema(value_type = i64)] pub amount: common_utils::types::MinorUnit, /// The currency of the payment. #[schema(value_type = Currency)] pub currency: common_enums::Currency, } /// Represents metadata about the payment method used in the 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodMetaData { /// The card network (e.g., Visa, Mastercard) if the payment method is a card. #[schema(value_type = CardNetwork)] pub card_network: Option<common_enums::CardNetwork>, } /// Represents data about the customer's device used in the 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CustomerDeviceData { /// The platform of the customer's device (e.g., Web, Android, iOS). pub platform: Option<CustomerDevicePlatform>, /// The type of the customer's device (e.g., Mobile, Tablet, Desktop). pub device_type: Option<CustomerDeviceType>, /// The display size of the customer's device. pub display_size: Option<CustomerDeviceDisplaySize>, } /// Represents data about the issuer used in the 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IssuerData { /// The name of the issuer. pub name: Option<String>, /// The country of the issuer. #[schema(value_type = Country)] pub country: Option<common_enums::Country>, } /// Represents data about the acquirer used in the 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AcquirerData { /// The country of the acquirer. #[schema(value_type = Country)] pub country: Option<common_enums::Country>, /// The fraud rate associated with the acquirer. pub fraud_rate: Option<f64>, } /// Represents the request to execute a 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ThreeDsDecisionRuleExecuteRequest { /// The ID of the routing algorithm to be executed. #[schema(value_type = String)] pub routing_id: common_utils::id_type::RoutingId, /// Data related to the payment. pub payment: PaymentData, /// Optional metadata about the payment method. pub payment_method: Option<PaymentMethodMetaData>, /// Optional data about the customer's device. pub customer_device: Option<CustomerDeviceData>, /// Optional data about the issuer. pub issuer: Option<IssuerData>, /// Optional data about the acquirer. pub acquirer: Option<AcquirerData>, } /// Represents the response from executing a 3DS decision rule. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ThreeDsDecisionRuleExecuteResponse { /// The decision made by the 3DS decision rule engine. #[schema(value_type = ThreeDSDecision)] pub decision: common_types::three_ds_decision_rule_engine::ThreeDSDecision, } impl common_utils::events::ApiEventMetric for ThreeDsDecisionRuleExecuteRequest { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::ThreeDsDecisionRule) } } impl common_utils::events::ApiEventMetric for ThreeDsDecisionRuleExecuteResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::ThreeDsDecisionRule) } }
crates/api_models/src/three_ds_decision_rule.rs
api_models::src::three_ds_decision_rule
911
true
// File: crates/api_models/src/webhook_events.rs // Module: api_models::src::webhook_events use std::collections::HashSet; use common_enums::{EventClass, EventType, WebhookDeliveryAttempt}; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; /// The constraints to apply when filtering events. #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] pub struct EventListConstraints { /// Filter events created after the specified time. #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created_after: Option<PrimitiveDateTime>, /// Filter events created before the specified time. #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created_before: Option<PrimitiveDateTime>, /// Include at most the specified number of events. pub limit: Option<u16>, /// Include events after the specified offset. pub offset: Option<u16>, /// Filter all events associated with the specified object identifier (Payment Intent ID, /// Refund ID, etc.) pub object_id: Option<String>, /// Filter all events associated with the specified business profile ID. #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// Filter events by their class. pub event_classes: Option<HashSet<EventClass>>, /// Filter events by their type. pub event_types: Option<HashSet<EventType>>, /// Filter all events by `is_overall_delivery_successful` field of the event. pub is_delivered: Option<bool>, } #[derive(Debug)] pub enum EventListConstraintsInternal { GenericFilter { created_after: Option<PrimitiveDateTime>, created_before: Option<PrimitiveDateTime>, limit: Option<i64>, offset: Option<i64>, event_classes: Option<HashSet<EventClass>>, event_types: Option<HashSet<EventType>>, is_delivered: Option<bool>, }, ObjectIdFilter { object_id: String, }, } /// The response body for each item when listing events. #[derive(Debug, Serialize, ToSchema)] pub struct EventListItemResponse { /// The identifier for the Event. #[schema(max_length = 64, example = "evt_018e31720d1b7a2b82677d3032cab959")] pub event_id: String, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The identifier for the Business Profile. #[schema(max_length = 64, value_type = String, example = "SqB0zwDGR5wHppWf0bx7GKr1f2")] pub profile_id: common_utils::id_type::ProfileId, /// The identifier for the object (Payment Intent ID, Refund ID, etc.) #[schema(max_length = 64, example = "QHrfd5LUDdZaKtAjdJmMu0dMa1")] pub object_id: String, /// Specifies the type of event, which includes the object and its status. pub event_type: EventType, /// Specifies the class of event (the type of object: Payment, Refund, etc.) pub event_class: EventClass, /// Indicates whether the webhook was ultimately delivered or not. pub is_delivery_successful: Option<bool>, /// The identifier for the initial delivery attempt. This will be the same as `event_id` for /// the initial delivery attempt. #[schema(max_length = 64, example = "evt_018e31720d1b7a2b82677d3032cab959")] pub initial_attempt_id: String, /// Time at which the event was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, } /// The response body of list initial delivery attempts api call. #[derive(Debug, Serialize, ToSchema)] pub struct TotalEventsResponse { /// The list of events pub events: Vec<EventListItemResponse>, /// Count of total events pub total_count: i64, } impl TotalEventsResponse { pub fn new(total_count: i64, events: Vec<EventListItemResponse>) -> Self { Self { events, total_count, } } } impl common_utils::events::ApiEventMetric for TotalEventsResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.events.first().map(|event| event.merchant_id.clone())?, }) } } /// The response body for retrieving an event. #[derive(Debug, Serialize, ToSchema)] pub struct EventRetrieveResponse { #[serde(flatten)] pub event_information: EventListItemResponse, /// The request information (headers and body) sent in the webhook. pub request: OutgoingWebhookRequestContent, /// The response information (headers, body and status code) received for the webhook sent. pub response: OutgoingWebhookResponseContent, /// Indicates the type of delivery attempt. pub delivery_attempt: Option<WebhookDeliveryAttempt>, } impl common_utils::events::ApiEventMetric for EventRetrieveResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.event_information.merchant_id.clone(), }) } } /// The request information (headers and body) sent in the webhook. #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct OutgoingWebhookRequestContent { /// The request body sent in the webhook. #[schema(value_type = String)] #[serde(alias = "payload")] pub body: Secret<String>, /// The request headers sent in the webhook. #[schema( value_type = Vec<(String, String)>, example = json!([["content-type", "application/json"], ["content-length", "1024"]])) ] pub headers: Vec<(String, Secret<String>)>, } /// The response information (headers, body and status code) received for the webhook sent. #[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OutgoingWebhookResponseContent { /// The response body received for the webhook sent. #[schema(value_type = Option<String>)] #[serde(alias = "payload")] pub body: Option<Secret<String>>, /// The response headers received for the webhook sent. #[schema( value_type = Option<Vec<(String, String)>>, example = json!([["content-type", "application/json"], ["content-length", "1024"]])) ] pub headers: Option<Vec<(String, Secret<String>)>>, /// The HTTP status code for the webhook sent. #[schema(example = 200)] pub status_code: Option<u16>, /// Error message in case any error occurred when trying to deliver the webhook. #[schema(example = 200)] pub error_message: Option<String>, } #[derive(Debug, serde::Serialize)] pub struct EventListRequestInternal { pub merchant_id: common_utils::id_type::MerchantId, pub constraints: EventListConstraints, } impl common_utils::events::ApiEventMetric for EventListRequestInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.merchant_id.clone(), }) } } #[derive(Debug, serde::Serialize)] pub struct WebhookDeliveryAttemptListRequestInternal { pub merchant_id: common_utils::id_type::MerchantId, pub initial_attempt_id: String, } impl common_utils::events::ApiEventMetric for WebhookDeliveryAttemptListRequestInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.merchant_id.clone(), }) } } #[derive(Debug, serde::Serialize)] pub struct WebhookDeliveryRetryRequestInternal { pub merchant_id: common_utils::id_type::MerchantId, pub event_id: String, } impl common_utils::events::ApiEventMetric for WebhookDeliveryRetryRequestInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.merchant_id.clone(), }) } }
crates/api_models/src/webhook_events.rs
api_models::src::webhook_events
1,974
true
// File: crates/api_models/src/relay.rs // Module: api_models::src::relay use common_utils::types::MinorUnit; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::enums as api_enums; #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayRequest { /// The identifier that is associated to a resource at the connector reference to which the relay request is being made #[schema(example = "7256228702616471803954")] pub connector_resource_id: String, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub connector_id: common_utils::id_type::MerchantConnectorAccountId, /// The type of relay request #[serde(rename = "type")] #[schema(value_type = RelayType)] pub relay_type: api_enums::RelayType, /// The data that is associated with the relay request pub data: Option<RelayData>, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum RelayData { /// The data that is associated with a refund relay request Refund(RelayRefundRequestData), } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayRefundRequestData { /// The amount that is being refunded #[schema(value_type = i64 , example = 6540)] pub amount: MinorUnit, /// The currency in which the amount is being refunded #[schema(value_type = Currency)] pub currency: api_enums::Currency, /// The reason for the refund #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayResponse { /// The unique identifier for the Relay #[schema(example = "relay_mbabizu24mvu3mela5njyhpit4", value_type = String)] pub id: common_utils::id_type::RelayId, /// The status of the relay request #[schema(value_type = RelayStatus)] pub status: api_enums::RelayStatus, /// The identifier that is associated to a resource at the connector reference to which the relay request is being made #[schema(example = "pi_3MKEivSFNglxLpam0ZaL98q9")] pub connector_resource_id: String, /// The error details if the relay request failed pub error: Option<RelayError>, /// The identifier that is associated to a resource at the connector to which the relay request is being made #[schema(example = "re_3QY4TnEOqOywnAIx1Mm1p7GQ")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub connector_id: common_utils::id_type::MerchantConnectorAccountId, /// The business profile that is associated with this relay request. #[schema(example = "pro_abcdefghijklmnopqrstuvwxyz", value_type = String)] pub profile_id: common_utils::id_type::ProfileId, /// The type of relay request #[serde(rename = "type")] #[schema(value_type = RelayType)] pub relay_type: api_enums::RelayType, /// The data that is associated with the relay request pub data: Option<RelayData>, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayError { /// The error code pub code: String, /// The error message pub message: String, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayRetrieveRequest { /// The unique identifier for the Relay #[serde(default)] pub force_sync: bool, /// The unique identifier for the Relay pub id: common_utils::id_type::RelayId, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayRetrieveBody { /// The unique identifier for the Relay #[serde(default)] pub force_sync: bool, } impl common_utils::events::ApiEventMetric for RelayRequest {} impl common_utils::events::ApiEventMetric for RelayResponse {} impl common_utils::events::ApiEventMetric for RelayRetrieveRequest {} impl common_utils::events::ApiEventMetric for RelayRetrieveBody {}
crates/api_models/src/relay.rs
api_models::src::relay
1,040
true
// File: crates/api_models/src/admin.rs // Module: api_models::src::admin use std::collections::{HashMap, HashSet}; use common_types::primitive_wrappers; use common_utils::{ consts, crypto::Encryptable, errors::{self, CustomResult}, ext_traits::Encode, id_type, link_utils, pii, }; #[cfg(feature = "v1")] use common_utils::{crypto::OptionalEncryptableName, ext_traits::ValueExt}; #[cfg(feature = "v2")] use masking::ExposeInterface; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use super::payments::AddressDetails; use crate::{ consts::{MAX_ORDER_FULFILLMENT_EXPIRY, MIN_ORDER_FULFILLMENT_EXPIRY}, enums as api_enums, payment_methods, }; #[cfg(feature = "v1")] use crate::{profile_acquirer::ProfileAcquirerResponse, routing}; #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] pub struct MerchantAccountListRequest { pub organization_id: id_type::OrganizationId, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantAccountCreate { /// The identifier for the Merchant Account #[schema(value_type = String, max_length = 64, min_length = 1, example = "y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_id: id_type::MerchantId, /// Name of the Merchant Account #[schema(value_type= Option<String>,example = "NewAge Retailer")] pub merchant_name: Option<Secret<String>>, /// Details about the merchant, can contain phone and emails of primary and secondary contact person pub merchant_details: Option<MerchantDetails>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<url::Url>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// The routing algorithm to be used for routing payments to desired connectors #[serde(skip)] #[schema(deprecated)] pub routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used for routing payouts to desired connectors #[cfg(feature = "payouts")] #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. #[schema(default = false, example = false)] pub sub_merchants_enabled: Option<bool>, /// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)] pub parent_merchant_id: Option<id_type::MerchantId>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = false, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled. #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Metadata is useful for storing additional, unstructured information on an object #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<MerchantAccountMetadata>, /// API key that will be used for client side API access. A publishable key has to be always paired with a `client_secret`. /// A `client_secret` can be obtained by creating a payment with `confirm` set to false #[schema(example = "AH3423bkjbkjdsfbkj")] pub publishable_key: Option<String>, /// An identifier for the vault used to store payment method information. #[schema(example = "locker_abc123")] pub locker_id: Option<String>, /// Details about the primary business unit of the merchant account #[schema(value_type = Option<PrimaryBusinessDetails>)] pub primary_business_details: Option<Vec<PrimaryBusinessDetails>>, /// The frm routing algorithm to be used for routing payments to desired FRM's #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The id of the organization to which the merchant belongs to, if not passed an organization is created #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: Option<id_type::OrganizationId>, /// Default payment method collect link config #[schema(value_type = Option<BusinessCollectLinkConfig>)] pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, /// Product Type of this merchant account #[schema(value_type = Option<MerchantProductType>, example = "Orchestration")] pub product_type: Option<api_enums::MerchantProductType>, /// Merchant Account Type of this merchant account #[schema(value_type = Option<MerchantAccountRequestType>, example = "standard")] pub merchant_account_type: Option<api_enums::MerchantAccountRequestType>, } #[cfg(feature = "v1")] impl MerchantAccountCreate { pub fn get_merchant_reference_id(&self) -> id_type::MerchantId { self.merchant_id.clone() } pub fn get_payment_response_hash_key(&self) -> Option<String> { self.payment_response_hash_key.clone().or(Some( common_utils::crypto::generate_cryptographically_secure_random_string(64), )) } pub fn get_primary_details_as_value( &self, ) -> CustomResult<serde_json::Value, errors::ParsingError> { self.primary_business_details .clone() .unwrap_or_default() .encode_to_value() } pub fn get_pm_link_config_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.pm_collect_link_config .as_ref() .map(|pm_collect_link_config| pm_collect_link_config.encode_to_value()) .transpose() } pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.merchant_details .as_ref() .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) .transpose() } pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.metadata .as_ref() .map(|metadata| metadata.encode_to_value().map(Secret::new)) .transpose() } pub fn parse_routing_algorithm(&self) -> CustomResult<(), errors::ParsingError> { match self.routing_algorithm { Some(ref routing_algorithm) => { let _: routing::StaticRoutingAlgorithm = routing_algorithm .clone() .parse_value("StaticRoutingAlgorithm")?; Ok(()) } None => Ok(()), } } // Get the enable payment response hash as a boolean, where the default value is true pub fn get_enable_payment_response_hash(&self) -> bool { self.enable_payment_response_hash.unwrap_or(true) } } #[cfg(feature = "v2")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] #[schema(as = MerchantAccountCreate)] pub struct MerchantAccountCreateWithoutOrgId { /// Name of the Merchant Account, This will be used as a prefix to generate the id #[schema(value_type= String, max_length = 64, example = "NewAge Retailer")] pub merchant_name: Secret<common_utils::new_type::MerchantName>, /// Details about the merchant, contains phone and emails of primary and secondary contact person. pub merchant_details: Option<MerchantDetails>, /// Metadata is useful for storing additional, unstructured information about the merchant account. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } // In v2 the struct used in the API is MerchantAccountCreateWithoutOrgId // The following struct is only used internally, so we can reuse the common // part of `create_merchant_account` without duplicating its code for v2 #[cfg(feature = "v2")] #[derive(Clone, Debug, Serialize, ToSchema)] pub struct MerchantAccountCreate { pub merchant_name: Secret<common_utils::new_type::MerchantName>, pub merchant_details: Option<MerchantDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub organization_id: id_type::OrganizationId, /// Product Type of this merchant account #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } #[cfg(feature = "v2")] impl MerchantAccountCreate { pub fn get_merchant_reference_id(&self) -> id_type::MerchantId { id_type::MerchantId::from_merchant_name(self.merchant_name.clone().expose()) } pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.merchant_details .as_ref() .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) .transpose() } pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.metadata .as_ref() .map(|metadata| metadata.encode_to_value().map(Secret::new)) .transpose() } pub fn get_primary_details_as_value( &self, ) -> CustomResult<serde_json::Value, errors::ParsingError> { Vec::<PrimaryBusinessDetails>::new().encode_to_value() } } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct CardTestingGuardConfig { /// Determines if Card IP Blocking is enabled for profile pub card_ip_blocking_status: CardTestingGuardStatus, /// Determines the unsuccessful payment threshold for Card IP Blocking for profile pub card_ip_blocking_threshold: i32, /// Determines if Guest User Card Blocking is enabled for profile pub guest_user_card_blocking_status: CardTestingGuardStatus, /// Determines the unsuccessful payment threshold for Guest User Card Blocking for profile pub guest_user_card_blocking_threshold: i32, /// Determines if Customer Id Blocking is enabled for profile pub customer_id_blocking_status: CardTestingGuardStatus, /// Determines the unsuccessful payment threshold for Customer Id Blocking for profile pub customer_id_blocking_threshold: i32, /// Determines Redis Expiry for Card Testing Guard for profile pub card_testing_guard_expiry: i32, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardTestingGuardStatus { Enabled, Disabled, } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct AuthenticationConnectorDetails { /// List of authentication connectors #[schema(value_type = Vec<AuthenticationConnectors>)] pub authentication_connectors: Vec<common_enums::AuthenticationConnectors>, /// URL of the (customer service) website that will be shown to the shopper in case of technical errors during the 3D Secure 2 process. pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred. pub three_ds_requestor_app_url: Option<String>, } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct ExternalVaultConnectorDetails { /// Merchant Connector id to be stored for vault connector #[schema(value_type = Option<String>)] pub vault_connector_id: id_type::MerchantConnectorAccountId, /// External vault to be used for storing payment method information #[schema(value_type = Option<VaultSdk>)] pub vault_sdk: Option<common_enums::VaultSdk>, } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct MerchantAccountMetadata { pub compatible_connector: Option<api_enums::Connector>, #[serde(flatten)] pub data: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantAccountUpdate { /// The identifier for the Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Name of the Merchant Account #[schema(example = "NewAge Retailer")] pub merchant_name: Option<String>, /// Details about the merchant pub merchant_details: Option<MerchantDetails>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<url::Url>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// The routing algorithm to be used for routing payments to desired connectors #[serde(skip)] #[schema(deprecated)] pub routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. #[schema(default = false, example = false)] pub sub_merchants_enabled: Option<bool>, /// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)] pub parent_merchant_id: Option<id_type::MerchantId>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = false, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// API key that will be used for server side API access #[schema(example = "AH3423bkjbkjdsfbkj")] pub publishable_key: Option<String>, /// An identifier for the vault used to store payment method information. #[schema(example = "locker_abc123")] pub locker_id: Option<String>, /// Details about the primary business unit of the merchant account pub primary_business_details: Option<Vec<PrimaryBusinessDetails>>, /// The frm routing algorithm to be used for routing payments to desired FRM's #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The default profile that must be used for creating merchant accounts and payments #[schema(max_length = 64, value_type = Option<String>)] pub default_profile: Option<id_type::ProfileId>, /// Default payment method collect link config #[schema(value_type = Option<BusinessCollectLinkConfig>)] pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, } #[cfg(feature = "v1")] impl MerchantAccountUpdate { pub fn get_primary_details_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.primary_business_details .as_ref() .map(|primary_business_details| primary_business_details.encode_to_value()) .transpose() } pub fn get_pm_link_config_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.pm_collect_link_config .as_ref() .map(|pm_collect_link_config| pm_collect_link_config.encode_to_value()) .transpose() } pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.merchant_details .as_ref() .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) .transpose() } pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.metadata .as_ref() .map(|metadata| metadata.encode_to_value().map(Secret::new)) .transpose() } pub fn get_webhook_details_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.webhook_details .as_ref() .map(|webhook_details| webhook_details.encode_to_value()) .transpose() } pub fn parse_routing_algorithm(&self) -> CustomResult<(), errors::ParsingError> { match self.routing_algorithm { Some(ref routing_algorithm) => { let _: routing::StaticRoutingAlgorithm = routing_algorithm .clone() .parse_value("StaticRoutingAlgorithm")?; Ok(()) } None => Ok(()), } } // Get the enable payment response hash as a boolean, where the default value is true pub fn get_enable_payment_response_hash(&self) -> bool { self.enable_payment_response_hash.unwrap_or(true) } } #[cfg(feature = "v2")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantAccountUpdate { /// Name of the Merchant Account #[schema(example = "NewAge Retailer")] pub merchant_name: Option<String>, /// Details about the merchant pub merchant_details: Option<MerchantDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] impl MerchantAccountUpdate { pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.merchant_details .as_ref() .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) .transpose() } pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.metadata .as_ref() .map(|metadata| metadata.encode_to_value().map(Secret::new)) .transpose() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, ToSchema, Serialize)] pub struct MerchantAccountResponse { /// The identifier for the Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Name of the Merchant Account #[schema(value_type = Option<String>,example = "NewAge Retailer")] pub merchant_name: OptionalEncryptableName, /// The URL to redirect after completion of the payment #[schema(max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<String>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = false, example = true)] pub enable_payment_response_hash: bool, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf")] pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: bool, /// Details about the merchant #[schema(value_type = Option<MerchantDetails>)] pub merchant_details: Option<Encryptable<pii::SecretSerdeValue>>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[serde(skip)] #[schema(deprecated)] pub routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. #[schema(default = false, example = false)] pub sub_merchants_enabled: Option<bool>, /// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)] pub parent_merchant_id: Option<id_type::MerchantId>, /// API key that will be used for server side API access #[schema(example = "AH3423bkjbkjdsfbkj")] pub publishable_key: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// An identifier for the vault used to store payment method information. #[schema(example = "locker_abc123")] pub locker_id: Option<String>, /// Details about the primary business unit of the merchant account #[schema(value_type = Vec<PrimaryBusinessDetails>)] pub primary_business_details: Vec<PrimaryBusinessDetails>, /// The frm routing algorithm to be used to process the incoming request from merchant to outgoing payment FRM. #[schema(value_type = Option<StaticRoutingAlgorithm>, max_length = 255, example = r#"{"type": "single", "data": "stripe" }"#)] pub frm_routing_algorithm: Option<serde_json::Value>, /// The organization id merchant is associated with #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: id_type::OrganizationId, /// A boolean value to indicate if the merchant has recon service is enabled or not, by default value is false pub is_recon_enabled: bool, /// The default profile that must be used for creating merchant accounts and payments #[schema(max_length = 64, value_type = Option<String>)] pub default_profile: Option<id_type::ProfileId>, /// Used to indicate the status of the recon module for a merchant account #[schema(value_type = ReconStatus, example = "not_requested")] pub recon_status: api_enums::ReconStatus, /// Default payment method collect link config #[schema(value_type = Option<BusinessCollectLinkConfig>)] pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, /// Product Type of this merchant account #[schema(value_type = Option<MerchantProductType>, example = "Orchestration")] pub product_type: Option<api_enums::MerchantProductType>, /// Merchant Account Type of this merchant account #[schema(value_type = MerchantAccountType, example = "standard")] pub merchant_account_type: api_enums::MerchantAccountType, } #[cfg(feature = "v2")] #[derive(Clone, Debug, ToSchema, Serialize)] pub struct MerchantAccountResponse { /// The identifier for the Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub id: id_type::MerchantId, /// Name of the Merchant Account #[schema(value_type = String,example = "NewAge Retailer")] pub merchant_name: Secret<String>, /// Details about the merchant #[schema(value_type = Option<MerchantDetails>)] pub merchant_details: Option<Encryptable<pii::SecretSerdeValue>>, /// API key that will be used for server side API access #[schema(example = "AH3423bkjbkjdsfbkj")] pub publishable_key: String, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// The id of the organization which the merchant is associated with #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: id_type::OrganizationId, /// Used to indicate the status of the recon module for a merchant account #[schema(value_type = ReconStatus, example = "not_requested")] pub recon_status: api_enums::ReconStatus, /// Product Type of this merchant account #[schema(value_type = Option<MerchantProductType>, example = "Orchestration")] pub product_type: Option<api_enums::MerchantProductType>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantDetails { /// The merchant's primary contact name #[schema(value_type = Option<String>, max_length = 255, example = "John Doe")] pub primary_contact_person: Option<Secret<String>>, /// The merchant's primary phone number #[schema(value_type = Option<String>, max_length = 255, example = "999999999")] pub primary_phone: Option<Secret<String>>, /// The merchant's primary email address #[schema(value_type = Option<String>, max_length = 255, example = "johndoe@test.com")] pub primary_email: Option<pii::Email>, /// The merchant's secondary contact name #[schema(value_type = Option<String>, max_length= 255, example = "John Doe2")] pub secondary_contact_person: Option<Secret<String>>, /// The merchant's secondary phone number #[schema(value_type = Option<String>, max_length = 255, example = "999999988")] pub secondary_phone: Option<Secret<String>>, /// The merchant's secondary email address #[schema(value_type = Option<String>, max_length = 255, example = "johndoe2@test.com")] pub secondary_email: Option<pii::Email>, /// The business website of the merchant #[schema(max_length = 255, example = "www.example.com")] pub website: Option<String>, /// A brief description about merchant's business #[schema( max_length = 255, example = "Online Retail with a wide selection of organic products for North America" )] pub about_business: Option<String>, /// The merchant's address details pub address: Option<AddressDetails>, #[schema(value_type = Option<String>, example = "123456789")] pub merchant_tax_registration_id: Option<Secret<String>>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize, PartialEq)] #[serde(deny_unknown_fields)] pub struct PrimaryBusinessDetails { #[schema(value_type = CountryAlpha2)] pub country: api_enums::CountryAlpha2, #[schema(example = "food")] pub business: String, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct WebhookDetails { ///The version for Webhook #[schema(max_length = 255, max_length = 255, example = "1.0.2")] pub webhook_version: Option<String>, ///The user name for Webhook login #[schema(max_length = 255, max_length = 255, example = "ekart_retail")] pub webhook_username: Option<String>, ///The password for Webhook login #[schema(value_type = Option<String>, max_length = 255, example = "ekart@123")] pub webhook_password: Option<Secret<String>>, ///The url for the webhook endpoint #[schema(value_type = Option<String>, example = "www.ekart.com/webhooks")] pub webhook_url: Option<Secret<String>>, /// If this property is true, a webhook message is posted whenever a new payment is created #[schema(example = true)] pub payment_created_enabled: Option<bool>, /// If this property is true, a webhook message is posted whenever a payment is successful #[schema(example = true)] pub payment_succeeded_enabled: Option<bool>, /// If this property is true, a webhook message is posted whenever a payment fails #[schema(example = true)] pub payment_failed_enabled: Option<bool>, /// List of payment statuses that triggers a webhook for payment intents #[schema(value_type = Vec<IntentStatus>, example = json!(["succeeded", "failed", "partially_captured", "requires_merchant_action"]))] pub payment_statuses_enabled: Option<Vec<api_enums::IntentStatus>>, /// List of refund statuses that triggers a webhook for refunds #[schema(value_type = Vec<IntentStatus>, example = json!(["success", "failure"]))] pub refund_statuses_enabled: Option<Vec<api_enums::RefundStatus>>, /// List of payout statuses that triggers a webhook for payouts #[cfg(feature = "payouts")] #[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["success", "failed"]))] pub payout_statuses_enabled: Option<Vec<api_enums::PayoutStatus>>, } impl WebhookDetails { fn validate_statuses<T>(statuses: &[T], status_type_name: &str) -> Result<(), String> where T: strum::IntoEnumIterator + Copy + PartialEq + std::fmt::Debug, T: Into<Option<api_enums::EventType>>, { let valid_statuses: Vec<T> = T::iter().filter(|s| (*s).into().is_some()).collect(); for status in statuses { if !valid_statuses.contains(status) { return Err(format!( "Invalid {status_type_name} webhook status provided: {status:?}" )); } } Ok(()) } pub fn validate(&self) -> Result<(), String> { if let Some(payment_statuses) = &self.payment_statuses_enabled { Self::validate_statuses(payment_statuses, "payment")?; } if let Some(refund_statuses) = &self.refund_statuses_enabled { Self::validate_statuses(refund_statuses, "refund")?; } #[cfg(feature = "payouts")] { if let Some(payout_statuses) = &self.payout_statuses_enabled { Self::validate_statuses(payout_statuses, "payout")?; } } Ok(()) } } #[derive(Debug, Serialize, ToSchema)] pub struct MerchantAccountDeleteResponse { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// If the connector is deleted or not #[schema(example = false)] pub deleted: bool, } #[derive(Default, Debug, Deserialize, Serialize)] pub struct MerchantId { pub merchant_id: id_type::MerchantId, } #[cfg(feature = "v1")] #[derive(Debug, Deserialize, ToSchema, Serialize)] pub struct MerchantConnectorId { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } #[cfg(feature = "v2")] #[derive(Debug, Deserialize, ToSchema, Serialize)] pub struct MerchantConnectorId { #[schema(value_type = String)] pub id: id_type::MerchantConnectorAccountId, } #[cfg(feature = "v2")] /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorCreate { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector #[schema(value_type = Connector, example = "stripe")] pub connector_name: api_enums::Connector, /// This is an unique label you can generate and pass in order to identify this connector account on your Hyperswitch dashboard and reports, If not passed then if will take `connector_name`_`profile_name`. Eg: if your profile label is `default`, connector label can be `stripe_default` #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: Option<pii::SecretSerdeValue>, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(value_type = PaymentMethodsEnabled)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// pm_auth_config will relate MCA records to their respective chosen auth services, based on payment_method and pmt #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = Option<ConnectorStatus>, example = "inactive")] // By default the ConnectorStatus is Active pub status: Option<api_enums::ConnectorStatus>, /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials #[schema(value_type = Option<ConnectorWalletDetails>)] pub connector_wallets_details: Option<ConnectorWalletDetails>, /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<MerchantConnectorAccountFeatureMetadata>)] pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v2")] impl MerchantConnectorCreate { pub fn get_transaction_type(&self) -> api_enums::TransactionType { match self.connector_type { #[cfg(feature = "payouts")] api_enums::ConnectorType::PayoutProcessor => api_enums::TransactionType::Payout, _ => api_enums::TransactionType::Payment, } } pub fn get_frm_config_as_secret(&self) -> Option<Vec<Secret<serde_json::Value>>> { match self.frm_configs.as_ref() { Some(frm_value) => { let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| config.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() .ok()?; Some(configs_for_frm_value) } None => None, } } pub fn get_connector_label(&self, profile_name: String) -> String { match self.connector_label.clone() { Some(connector_label) => connector_label, None => format!("{}_{}", self.connector_name, profile_name), } } } #[cfg(feature = "v1")] /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorCreate { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector #[schema(value_type = Connector, example = "stripe")] pub connector_name: api_enums::Connector, /// This is an unique label you can generate and pass in order to identify this connector account on your Hyperswitch dashboard and reports. Eg: if your profile label is `default`, connector label can be `stripe_default` #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: Option<pii::SecretSerdeValue>, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(example = json!([ { "payment_method": "wallet", "payment_method_types": [ "upi_collect", "upi_intent" ], "payment_method_issuers": [ "labore magna ipsum", "aute" ], "payment_schemes": [ "Discover", "Discover" ], "accepted_currencies": { "type": "enable_only", "list": ["USD", "EUR"] }, "accepted_countries": { "type": "disable_only", "list": ["FR", "DE","IN"] }, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ]))] pub payment_methods_enabled: Option<Vec<PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is in Test mode. By default, its value is false. #[schema(default = false, example = false)] pub test_mode: Option<bool>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// The business country to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead pub business_label: Option<String>, /// The business sublabel to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(example = "chase")] pub business_sub_label: Option<String>, /// Unique ID of the connector #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = Option<ConnectorStatus>, example = "inactive")] pub status: Option<api_enums::ConnectorStatus>, /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials #[schema(value_type = Option<ConnectorWalletDetails>)] pub connector_wallets_details: Option<ConnectorWalletDetails>, } #[cfg(feature = "v1")] impl MerchantConnectorCreate { pub fn get_transaction_type(&self) -> api_enums::TransactionType { match self.connector_type { #[cfg(feature = "payouts")] api_enums::ConnectorType::PayoutProcessor => api_enums::TransactionType::Payout, _ => api_enums::TransactionType::Payment, } } pub fn get_frm_config_as_secret(&self) -> Option<Vec<Secret<serde_json::Value>>> { match self.frm_configs.as_ref() { Some(frm_value) => { let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| config.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() .ok()?; Some(configs_for_frm_value) } None => None, } } } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum AdditionalMerchantData { OpenBankingRecipientData(MerchantRecipientData), } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] /// Feature metadata for merchant connector account pub struct MerchantConnectorAccountFeatureMetadata { /// Revenue recovery metadata for merchant connector account pub revenue_recovery: Option<RevenueRecoveryMetadata>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] /// Revenue recovery metadata for merchant connector account pub struct RevenueRecoveryMetadata { /// The maximum number of retries allowed for an invoice. This limit is set by the merchant for each `billing connector`. Once this limit is reached, no further retries will be attempted. #[schema(value_type = u16, example = "15")] pub max_retry_count: u16, /// Maximum number of `billing connector` retries before revenue recovery can start executing retries. #[schema(value_type = u16, example = "10")] pub billing_connector_retry_threshold: u16, /// Billing account reference id is payment gateway id at billing connector end. /// Merchants need to provide a mapping between these merchant connector account and the corresponding account reference IDs for each `billing connector`. #[schema(value_type = u16, example = r#"{ "mca_vDSg5z6AxnisHq5dbJ6g": "stripe_123", "mca_vDSg5z6AumisHqh4x5m1": "adyen_123" }"#)] pub billing_account_reference: HashMap<id_type::MerchantConnectorAccountId, String>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MerchantAccountData { /// IBAN-based account for international transfers Iban { /// International Bank Account Number (up to 34 characters) #[schema(value_type = String)] iban: Secret<String>, /// Account holder name name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// UK BACS payment system Bacs { /// 8-digit UK account number #[schema(value_type = String)] account_number: Secret<String>, /// 6-digit UK sort code #[schema(value_type = String, example = "123456")] sort_code: Secret<String>, /// Account holder name name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// UK Faster Payments (instant transfers) FasterPayments { /// 8-digit UK account number #[schema(value_type = String)] account_number: Secret<String>, /// 6-digit UK sort code #[schema(value_type = String)] sort_code: Secret<String>, /// Account holder name name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// SEPA payments (Euro zone) Sepa { /// IBAN for SEPA transfers #[schema(value_type = String, example = "FR1420041010050500013M02606")] iban: Secret<String>, /// Account holder name name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// SEPA Instant payments (10-second transfers) SepaInstant { /// IBAN for instant SEPA transfers #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Account holder name name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// Polish Elixir payment system Elixir { /// Polish account number (26 digits) #[schema(value_type = String, example = "12345678901234567890123456")] account_number: Secret<String>, /// Polish IBAN (28 chars) #[schema(value_type = String, example = "PL27114020040000300201355387")] iban: Secret<String>, /// Account holder name name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// Swedish Bankgiro system Bankgiro { /// Bankgiro number (7-8 digits) #[schema(value_type = String, example = "5402-9656")] number: Secret<String>, /// Account holder name #[schema(example = "Erik Andersson")] name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, /// Swedish Plusgiro system Plusgiro { /// Plusgiro number (2-8 digits) #[schema(value_type = String, example = "4789-2")] number: Secret<String>, /// Account holder name #[schema(example = "Anna Larsson")] name: String, #[schema(value_type = Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MerchantRecipientData { #[schema(value_type= Option<String>)] ConnectorRecipientId(Secret<String>), #[schema(value_type= Option<String>)] WalletId(Secret<String>), AccountData(MerchantAccountData), } // Different patterns of authentication. #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(tag = "auth_type")] pub enum ConnectorAuthType { TemporaryAuth, HeaderKey { api_key: Secret<String>, }, BodyKey { api_key: Secret<String>, key1: Secret<String>, }, SignatureKey { api_key: Secret<String>, key1: Secret<String>, api_secret: Secret<String>, }, MultiAuthKey { api_key: Secret<String>, key1: Secret<String>, api_secret: Secret<String>, key2: Secret<String>, }, CurrencyAuthKey { auth_key_map: HashMap<common_enums::Currency, pii::SecretSerdeValue>, }, CertificateAuth { // certificate should be base64 encoded certificate: Secret<String>, // private_key should be base64 encoded private_key: Secret<String>, }, #[default] NoKey, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorWebhookDetails { #[schema(value_type = String, example = "12345678900987654321")] pub merchant_secret: Secret<String>, #[schema(value_type = String, example = "12345678900987654321")] pub additional_secret: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)] pub struct MerchantConnectorInfo { pub connector_label: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } impl MerchantConnectorInfo { pub fn new( connector_label: String, merchant_connector_id: id_type::MerchantConnectorAccountId, ) -> Self { Self { connector_label, merchant_connector_id, } } } /// Response of creating a new Merchant Connector for the merchant account." #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorResponse { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector #[schema(value_type = Connector, example = "stripe")] pub connector_name: common_enums::connector_enums::Connector, /// A unique label to identify the connector account created under a profile #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Unique ID of the merchant connector account #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub id: id_type::MerchantConnectorAccountId, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: pii::SecretSerdeValue, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(value_type = Vec<PaymentMethodsEnabled>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// identifier for the verified domains of a particular connector account pub applepay_verified_domains: Option<Vec<String>>, /// pm_auth_config will relate MCA records to their respective chosen auth services, based on payment_method and pmt #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: api_enums::ConnectorStatus, #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials #[schema(value_type = Option<ConnectorWalletDetails>)] pub connector_wallets_details: Option<ConnectorWalletDetails>, /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<MerchantConnectorAccountFeatureMetadata>)] pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v2")] impl MerchantConnectorResponse { pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.id.clone(), } } } /// Response of creating a new Merchant Connector for the merchant account." #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorResponse { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector #[schema(value_type = Connector, example = "stripe")] pub connector_name: String, /// A unique label to identify the connector account created under a profile #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Unique ID of the merchant connector account #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: pii::SecretSerdeValue, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(example = json!([ { "payment_method": "wallet", "payment_method_types": [ "upi_collect", "upi_intent" ], "payment_method_issuers": [ "labore magna ipsum", "aute" ], "payment_schemes": [ "Discover", "Discover" ], "accepted_currencies": { "type": "enable_only", "list": ["USD", "EUR"] }, "accepted_countries": { "type": "disable_only", "list": ["FR", "DE","IN"] }, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ]))] pub payment_methods_enabled: Option<Vec<PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is in Test mode. By default, its value is false. #[schema(default = false, example = false)] pub test_mode: Option<bool>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// The business country to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, ///The business label to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(example = "travel")] pub business_label: Option<String>, /// The business sublabel to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(example = "chase")] pub business_sub_label: Option<String>, /// identifier for the verified domains of a particular connector account pub applepay_verified_domains: Option<Vec<String>>, #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: api_enums::ConnectorStatus, #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials #[schema(value_type = Option<ConnectorWalletDetails>)] pub connector_wallets_details: Option<ConnectorWalletDetails>, } #[cfg(feature = "v1")] impl MerchantConnectorResponse { pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.merchant_connector_id.clone(), } } } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorListResponse { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector #[schema(value_type = Connector, example = "stripe")] pub connector_name: String, /// A unique label to identify the connector account created under a profile #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Unique ID of the merchant connector account #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(example = json!([ { "payment_method": "wallet", "payment_method_types": [ "upi_collect", "upi_intent" ], "payment_method_issuers": [ "labore magna ipsum", "aute" ], "payment_schemes": [ "Discover", "Discover" ], "accepted_currencies": { "type": "enable_only", "list": ["USD", "EUR"] }, "accepted_countries": { "type": "disable_only", "list": ["FR", "DE","IN"] }, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ]))] pub payment_methods_enabled: Option<Vec<PaymentMethodsEnabled>>, /// A boolean value to indicate if the connector is in Test mode. By default, its value is false. #[schema(default = false, example = false)] pub test_mode: Option<bool>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// The business country to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, ///The business label to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(example = "travel")] pub business_label: Option<String>, /// The business sublabel to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead #[schema(example = "chase")] pub business_sub_label: Option<String>, /// identifier for the verified domains of a particular connector account pub applepay_verified_domains: Option<Vec<String>>, #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: api_enums::ConnectorStatus, } #[cfg(feature = "v1")] impl MerchantConnectorListResponse { pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.merchant_connector_id.clone(), } } pub fn get_connector_name(&self) -> String { self.connector_name.clone() } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorListResponse { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector #[schema(value_type = Connector, example = "stripe")] pub connector_name: common_enums::connector_enums::Connector, /// A unique label to identify the connector account created under a profile #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Unique ID of the merchant connector account #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub id: id_type::MerchantConnectorAccountId, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(value_type = Vec<PaymentMethodsEnabled>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// identifier for the verified domains of a particular connector account pub applepay_verified_domains: Option<Vec<String>>, #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: api_enums::ConnectorStatus, } #[cfg(feature = "v2")] impl MerchantConnectorListResponse { pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.id.clone(), } } pub fn get_connector_name(&self) -> common_enums::connector_enums::Connector { self.connector_name } } /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorUpdate { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// This is an unique label you can generate and pass in order to identify this connector account on your Hyperswitch dashboard and reports. Eg: if your profile label is `default`, connector label can be `stripe_default` #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: Option<pii::SecretSerdeValue>, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(example = json!([ { "payment_method": "wallet", "payment_method_types": [ "upi_collect", "upi_intent" ], "payment_method_issuers": [ "labore magna ipsum", "aute" ], "payment_schemes": [ "Discover", "Discover" ], "accepted_currencies": { "type": "enable_only", "list": ["USD", "EUR"] }, "accepted_countries": { "type": "disable_only", "list": ["FR", "DE","IN"] }, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ]))] pub payment_methods_enabled: Option<Vec<PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is in Test mode. By default, its value is false. #[schema(default = false, example = false)] pub test_mode: Option<bool>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// pm_auth_config will relate MCA records to their respective chosen auth services, based on payment_method and pmt #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: Option<api_enums::ConnectorStatus>, /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials #[schema(value_type = Option<ConnectorWalletDetails>)] pub connector_wallets_details: Option<ConnectorWalletDetails>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ConnectorWalletDetails { /// This field contains the Apple Pay certificates and credentials for iOS and Web Apple Pay flow #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub apple_pay_combined: Option<pii::SecretSerdeValue>, /// This field is for our legacy Apple Pay flow that contains the Apple Pay certificates and credentials for only iOS Apple Pay flow #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub apple_pay: Option<pii::SecretSerdeValue>, /// This field contains the Amazon Pay certificates and credentials #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub amazon_pay: Option<pii::SecretSerdeValue>, /// This field contains the Samsung Pay certificates and credentials #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub samsung_pay: Option<pii::SecretSerdeValue>, /// This field contains the Paze certificates and credentials #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub paze: Option<pii::SecretSerdeValue>, /// This field contains the Google Pay certificates and credentials #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub google_pay: Option<pii::SecretSerdeValue>, } /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorUpdate { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// This is an unique label you can generate and pass in order to identify this connector account on your Hyperswitch dashboard and reports, If not passed then if will take `connector_name`_`profile_name`. Eg: if your profile label is `default`, connector label can be `stripe_default` #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: Option<pii::SecretSerdeValue>, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(value_type = Option<Vec<PaymentMethodsEnabled>>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// pm_auth_config will relate MCA records to their respective chosen auth services, based on payment_method and pmt #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: Option<api_enums::ConnectorStatus>, /// The identifier for the Merchant Account #[schema(value_type = String, max_length = 64, min_length = 1, example = "y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_id: id_type::MerchantId, /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials pub connector_wallets_details: Option<ConnectorWalletDetails>, /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<MerchantConnectorAccountFeatureMetadata>)] pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v2")] impl MerchantConnectorUpdate { pub fn get_frm_config_as_secret(&self) -> Option<Vec<Secret<serde_json::Value>>> { match self.frm_configs.as_ref() { Some(frm_value) => { let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| config.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() .ok()?; Some(configs_for_frm_value) } None => None, } } } ///Details of FrmConfigs are mentioned here... it should be passed in payment connector create api call, and stored in merchant_connector_table #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct FrmConfigs { ///this is the connector that can be used for the payment #[schema(value_type = ConnectorType, example = "payment_processor")] pub gateway: Option<api_enums::Connector>, ///payment methods that can be used in the payment pub payment_methods: Vec<FrmPaymentMethod>, } ///Details of FrmPaymentMethod are mentioned here... it should be passed in payment connector create api call, and stored in merchant_connector_table #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct FrmPaymentMethod { ///payment methods(card, wallet, etc) that can be used in the payment #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: Option<common_enums::PaymentMethod>, ///payment method types(credit, debit) that can be used in the payment. This field is deprecated. It has not been removed to provide backward compatibility. pub payment_method_types: Option<Vec<FrmPaymentMethodType>>, ///frm flow type to be used, can be pre/post #[schema(value_type = Option<FrmPreferredFlowTypes>)] pub flow: Option<api_enums::FrmPreferredFlowTypes>, } ///Details of FrmPaymentMethodType are mentioned here... it should be passed in payment connector create api call, and stored in merchant_connector_table #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct FrmPaymentMethodType { ///payment method types(credit, debit) that can be used in the payment #[schema(value_type = PaymentMethodType)] pub payment_method_type: Option<common_enums::PaymentMethodType>, ///card networks(like visa mastercard) types that can be used in the payment #[schema(value_type = CardNetwork)] pub card_networks: Option<Vec<common_enums::CardNetwork>>, ///frm flow type to be used, can be pre/post #[schema(value_type = FrmPreferredFlowTypes)] pub flow: api_enums::FrmPreferredFlowTypes, ///action that the frm would take, in case fraud is detected #[schema(value_type = FrmAction)] pub action: api_enums::FrmAction, } /// Details of all the payment methods enabled for the connector for the given merchant account #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodsEnabled { /// Type of payment method. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: common_enums::PaymentMethod, /// Subtype of payment method #[schema(value_type = Option<Vec<RequestPaymentMethodTypes>>,example = json!(["credit"]))] pub payment_method_types: Option<Vec<payment_methods::RequestPaymentMethodTypes>>, } impl PaymentMethodsEnabled { /// Get payment_method #[cfg(feature = "v1")] pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> { Some(self.payment_method) } /// Get payment_method_types #[cfg(feature = "v1")] pub fn get_payment_method_type( &self, ) -> Option<&Vec<payment_methods::RequestPaymentMethodTypes>> { self.payment_method_types.as_ref() } } #[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)] #[serde( deny_unknown_fields, tag = "type", content = "list", rename_all = "snake_case" )] pub enum AcceptedCurrencies { #[schema(value_type = Vec<Currency>)] EnableOnly(Vec<api_enums::Currency>), #[schema(value_type = Vec<Currency>)] DisableOnly(Vec<api_enums::Currency>), AllAccepted, } #[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)] #[serde( deny_unknown_fields, tag = "type", content = "list", rename_all = "snake_case" )] /// Object to filter the customer countries for which the payment method is displayed pub enum AcceptedCountries { #[schema(value_type = Vec<CountryAlpha2>)] EnableOnly(Vec<api_enums::CountryAlpha2>), #[schema(value_type = Vec<CountryAlpha2>)] DisableOnly(Vec<api_enums::CountryAlpha2>), AllAccepted, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct MerchantConnectorDeleteResponse { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Unique ID of the connector #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, /// If the connector is deleted or not #[schema(example = false)] pub deleted: bool, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct MerchantConnectorDeleteResponse { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Unique ID of the connector #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub id: id_type::MerchantConnectorAccountId, /// If the connector is deleted or not #[schema(example = false)] pub deleted: bool, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleKVResponse { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Status of KV for the specific merchant #[schema(example = true)] pub kv_enabled: bool, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)] pub struct MerchantKeyTransferRequest { /// Offset for merchant account #[schema(example = 32)] pub from: u32, /// Limit for merchant account #[schema(example = 32)] pub limit: u32, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct TransferKeyResponse { /// The identifier for the Merchant Account #[schema(example = 32)] pub total_transferred: usize, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleKVRequest { #[serde(skip_deserializing)] #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Status of KV for the specific merchant #[schema(example = true)] pub kv_enabled: bool, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleAllKVRequest { /// Status of KV for the specific merchant #[schema(example = true)] pub kv_enabled: bool, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleAllKVResponse { ///Total number of updated merchants #[schema(example = 20)] pub total_updated: usize, /// Status of KV for the specific merchant #[schema(example = true)] pub kv_enabled: bool, } /// Merchant connector details used to make payments. #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MerchantConnectorDetailsWrap { /// Creds Identifier is to uniquely identify the credentials. Do not send any sensitive info, like encoded_data in this field. And do not send the string "null". pub creds_identifier: String, /// Merchant connector details type type. Base64 Encode the credentials and send it in this type and send as a string. #[schema(value_type = Option<MerchantConnectorDetails>, example = r#"{ "connector_account_details": { "auth_type": "HeaderKey", "api_key":"sk_test_xxxxxexamplexxxxxx12345" }, "metadata": { "user_defined_field_1": "sample_1", "user_defined_field_2": "sample_2", }, }"#)] pub encoded_data: Option<Secret<String>>, } #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] pub struct MerchantConnectorDetails { /// Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: pii::SecretSerdeValue, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Deserialize, ToSchema, Default, Serialize)] #[serde(deny_unknown_fields)] pub struct ProfileCreate { /// The name of profile #[schema(max_length = 64)] pub profile_name: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<url::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// The routing algorithm to be used for routing payments to desired connectors #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))] pub routing_algorithm: Option<serde_json::Value>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(example = 900)] pub intent_fulfillment_time: Option<u32>, /// The frm routing algorithm to be used for routing payments to desired FRM's #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<u32>, /// Default Payment Link config for all payment links created under this profile pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, /// Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. #[serde(default)] pub is_tax_connector_enabled: bool, /// Indicates if network tokenization is enabled or not. #[serde(default)] pub is_network_tokenization_enabled: bool, /// Indicates if is_auto_retries_enabled is enabled or not. pub is_auto_retries_enabled: Option<bool>, /// Maximum number of auto retries allowed for a payment pub max_auto_retries_enabled: Option<u8>, /// Bool indicating if extended authentication must be requested for all payments #[schema(value_type = Option<bool>)] pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, /// Indicates if click to pay is enabled or not. #[serde(default)] pub is_click_to_pay_enabled: bool, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: Option<bool>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, /// Indicates if the redirection has to open in the iframe #[schema(example = false)] pub is_iframe_redirection_enabled: Option<bool>, /// Indicates if pre network tokenization is enabled or not pub is_pre_network_tokenization_enabled: Option<bool>, /// Four-digit code assigned based on business type to determine processing fees and risk level #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, /// Merchant country code. /// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates. /// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks. /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, /// Time interval (in hours) for polling the connector to check for new disputes #[schema(value_type = Option<i32>, example = 2)] pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, /// Indicates if manual retry for payment is enabled or not pub is_manual_retry_enabled: Option<bool>, /// Bool indicating if overcapture must be requested for all payments #[schema(value_type = Option<bool>)] pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, /// Indicates if external vault is enabled or not. #[schema(value_type = Option<ExternalVaultEnabled>, example = "Enable")] pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>, /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, /// Merchant Connector id to be stored for billing_processor connector #[schema(value_type = Option<String>)] pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, /// Flag to enable Level 2 and Level 3 processing data for card transactions #[schema(value_type = Option<bool>)] pub is_l2_l3_enabled: Option<bool>, } #[nutype::nutype( validate(greater_or_equal = MIN_ORDER_FULFILLMENT_EXPIRY, less_or_equal = MAX_ORDER_FULFILLMENT_EXPIRY), derive(Clone, Copy, Debug, Deserialize, Serialize) )] pub struct OrderFulfillmentTime(i64); #[cfg(feature = "v2")] #[derive(Clone, Debug, Deserialize, ToSchema, Default, Serialize)] #[serde(deny_unknown_fields)] pub struct ProfileCreate { /// The name of profile #[schema(max_length = 64)] pub profile_name: String, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<common_utils::types::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(value_type = Option<u32>, example = 900)] pub order_fulfillment_time: Option<OrderFulfillmentTime>, /// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment #[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")] pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<u32>, /// Default Payment Link config for all payment links created under this profile pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, /// Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. #[serde(default)] pub is_tax_connector_enabled: bool, /// Indicates if network tokenization is enabled or not. #[serde(default)] pub is_network_tokenization_enabled: bool, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] #[serde(default)] pub is_click_to_pay_enabled: bool, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: Option<bool>, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, /// Indicates if the redirection has to open in the iframe #[schema(example = false)] pub is_iframe_redirection_enabled: Option<bool>, /// Indicates if external vault is enabled or not. pub is_external_vault_enabled: Option<bool>, /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, /// Four-digit code assigned based on business type to determine processing fees and risk level #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, /// Merchant country code. /// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates. /// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks. /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, /// Enable split payments, i.e., split the amount between multiple payment methods #[schema(value_type = Option<SplitTxnsEnabled>, default = "skip")] pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, /// Merchant Connector id to be stored for billing_processor connector #[schema(value_type = Option<String>)] pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, /// Flag to enable Level 2 and Level 3 processing data for card transactions #[schema(value_type = Option<bool>)] pub is_l2_l3_enabled: Option<bool>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, ToSchema, Serialize)] pub struct ProfileResponse { /// The identifier for Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// The identifier for profile. This must be used for creating merchant accounts, payments and payouts #[schema(max_length = 64, value_type = String, example = "pro_abcdefghijklmnopqrstuvwxyz")] pub profile_id: id_type::ProfileId, /// Name of the profile #[schema(max_length = 64)] pub profile_name: String, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<String>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: bool, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: bool, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// The routing algorithm to be used for routing payments to desired connectors #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))] pub routing_algorithm: Option<serde_json::Value>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(example = 900)] pub intent_fulfillment_time: Option<i64>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<i64>, /// Default Payment Link config for all payment links created under this profile #[schema(value_type = Option<BusinessPaymentLinkConfig>)] pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<MaskedHeaders>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. pub is_tax_connector_enabled: bool, /// Indicates if network tokenization is enabled or not. #[schema(default = false, example = false)] pub is_network_tokenization_enabled: bool, /// Indicates if is_auto_retries_enabled is enabled or not. #[schema(default = false, example = false)] pub is_auto_retries_enabled: bool, /// Maximum number of auto retries allowed for a payment pub max_auto_retries_enabled: Option<i16>, /// Bool indicating if extended authentication must be requested for all payments #[schema(value_type = Option<bool>)] pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] pub is_click_to_pay_enabled: bool, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: bool, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: bool, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, /// Indicates if pre network tokenization is enabled or not #[schema(default = false, example = false)] pub is_pre_network_tokenization_enabled: bool, /// Acquirer configs #[schema(value_type = Option<Vec<ProfileAcquirerResponse>>)] pub acquirer_configs: Option<Vec<ProfileAcquirerResponse>>, /// Indicates if the redirection has to open in the iframe #[schema(example = false)] pub is_iframe_redirection_enabled: Option<bool>, /// Four-digit code assigned based on business type to determine processing fees and risk level #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, /// Merchant country code. /// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates. /// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks. /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, /// Time interval (in hours) for polling the connector to check dispute statuses #[schema(value_type = Option<u32>, example = 2)] pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, /// Indicates if manual retry for payment is enabled or not pub is_manual_retry_enabled: Option<bool>, /// Bool indicating if overcapture must be requested for all payments #[schema(value_type = Option<bool>)] pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, /// Indicates if external vault is enabled or not. #[schema(value_type = Option<ExternalVaultEnabled>, example = "Enable")] pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>, /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, /// Merchant Connector id to be stored for billing_processor connector #[schema(value_type = Option<String>)] pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, /// Flag to enable Level 2 and Level 3 processing data for card transactions #[schema(value_type = Option<bool>)] pub is_l2_l3_enabled: Option<bool>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, ToSchema, Serialize)] pub struct ProfileResponse { /// The identifier for Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// The identifier for profile. This must be used for creating merchant accounts, payments and payouts #[schema(max_length = 64, value_type = String, example = "pro_abcdefghijklmnopqrstuvwxyz")] pub id: id_type::ProfileId, /// Name of the profile #[schema(max_length = 64)] pub profile_name: String, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<common_utils::types::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: bool, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: bool, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<i64>, /// Default Payment Link config for all payment links created under this profile #[schema(value_type = Option<BusinessPaymentLinkConfig>)] pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<MaskedHeaders>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(value_type = Option<u32>, example = 900)] pub order_fulfillment_time: Option<OrderFulfillmentTime>, /// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment #[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")] pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. pub is_tax_connector_enabled: bool, /// Indicates if network tokenization is enabled or not. #[schema(default = false, example = false)] pub is_network_tokenization_enabled: bool, /// Indicates if CVV should be collected during payment or not. #[schema(value_type = Option<bool>)] pub should_collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] pub is_click_to_pay_enabled: bool, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: bool, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, /// Indicates if the redirection has to open in the iframe #[schema(example = false)] pub is_iframe_redirection_enabled: Option<bool>, /// Indicates if external vault is enabled or not. pub is_external_vault_enabled: Option<bool>, /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, /// Four-digit code assigned based on business type to determine processing fees and risk level #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, /// Merchant country code. /// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates. /// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks. /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, /// Enable split payments, i.e., split the amount between multiple payment methods #[schema(value_type = SplitTxnsEnabled, default = "skip")] pub split_txns_enabled: common_enums::SplitTxnsEnabled, /// Indicates the state of revenue recovery algorithm type #[schema(value_type = Option<RevenueRecoveryAlgorithmType>, example = "cascading")] pub revenue_recovery_retry_algorithm_type: Option<common_enums::enums::RevenueRecoveryAlgorithmType>, /// Merchant Connector id to be stored for billing_processor connector #[schema(value_type = Option<String>)] pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, /// Flag to enable Level 2 and Level 3 processing data for card transactions #[schema(value_type = Option<bool>)] pub is_l2_l3_enabled: Option<bool>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct ProfileUpdate { /// The name of profile #[schema(max_length = 64)] pub profile_name: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<url::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// The routing algorithm to be used for routing payments to desired connectors #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))] pub routing_algorithm: Option<serde_json::Value>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(example = 900)] pub intent_fulfillment_time: Option<u32>, /// The frm routing algorithm to be used for routing payments to desired FRM's #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<u32>, /// Default Payment Link config for all payment links created under this profile pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Bool indicating if extended authentication must be requested for all payments #[schema(value_type = Option<bool>)] pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. pub is_tax_connector_enabled: Option<bool>, /// Indicates if dynamic routing is enabled or not. #[serde(default)] pub dynamic_routing_algorithm: Option<serde_json::Value>, /// Indicates if network tokenization is enabled or not. pub is_network_tokenization_enabled: Option<bool>, /// Indicates if is_auto_retries_enabled is enabled or not. pub is_auto_retries_enabled: Option<bool>, /// Maximum number of auto retries allowed for a payment pub max_auto_retries_enabled: Option<u8>, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] pub is_click_to_pay_enabled: Option<bool>, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: Option<bool>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, /// Indicates if the redirection has to open in the iframe #[schema(example = false)] pub is_iframe_redirection_enabled: Option<bool>, /// Indicates if pre network tokenization is enabled or not #[schema(default = false, example = false)] pub is_pre_network_tokenization_enabled: Option<bool>, /// Four-digit code assigned based on business type to determine processing fees and risk level #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, /// Merchant country code. /// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates. /// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks. /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, /// Time interval (in hours) for polling the connector to check for new disputes #[schema(value_type = Option<u32>, example = 2)] pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>, /// Indicates if manual retry for payment is enabled or not pub is_manual_retry_enabled: Option<bool>, /// Bool indicating if overcapture must be requested for all payments #[schema(value_type = Option<bool>)] pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>, /// Indicates if external vault is enabled or not. #[schema(value_type = Option<ExternalVaultEnabled>, example = "Enable")] pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>, /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, /// Merchant Connector id to be stored for billing_processor connector #[schema(value_type = Option<String>)] pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, /// Flag to enable Level 2 and Level 3 processing data for card transactions #[schema(value_type = Option<bool>)] pub is_l2_l3_enabled: Option<bool>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct ProfileUpdate { /// The name of profile #[schema(max_length = 64)] pub profile_name: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<common_utils::types::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(value_type = Option<u32>, example = 900)] pub order_fulfillment_time: Option<OrderFulfillmentTime>, /// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment #[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")] pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<u32>, /// Default Payment Link config for all payment links created under this profile pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. pub is_tax_connector_enabled: Option<bool>, /// Indicates if network tokenization is enabled or not. pub is_network_tokenization_enabled: Option<bool>, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] pub is_click_to_pay_enabled: Option<bool>, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: Option<bool>, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, /// Indicates if external vault is enabled or not. pub is_external_vault_enabled: Option<bool>, /// External Vault Connector Details pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>, /// Four-digit code assigned based on business type to determine processing fees and risk level #[schema(value_type = Option<MerchantCategoryCode>, example = "5411")] pub merchant_category_code: Option<api_enums::MerchantCategoryCode>, /// Merchant country code. /// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates. /// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks. /// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior. #[schema(value_type = Option<MerchantCountryCode>, example = "840")] pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>, /// Indicates the state of revenue recovery algorithm type #[schema(value_type = Option<RevenueRecoveryAlgorithmType>, example = "cascading")] pub revenue_recovery_retry_algorithm_type: Option<common_enums::enums::RevenueRecoveryAlgorithmType>, /// Enable split payments, i.e., split the amount between multiple payment methods #[schema(value_type = Option<SplitTxnsEnabled>, default = "skip")] pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>, /// Merchant Connector id to be stored for billing_processor connector #[schema(value_type = Option<String>)] pub billing_processor_id: Option<id_type::MerchantConnectorAccountId>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BusinessCollectLinkConfig { #[serde(flatten)] pub config: BusinessGenericLinkConfig, /// List of payment methods shown on collect UI #[schema(value_type = Vec<EnabledPaymentMethod>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs", "sepa"]}]"#)] pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BusinessPayoutLinkConfig { #[serde(flatten)] pub config: BusinessGenericLinkConfig, /// Form layout of the payout link #[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")] pub form_layout: Option<api_enums::UIWidgetFormLayout>, /// Allows for removing any validations / pre-requisites which are necessary in a production environment #[schema(value_type = Option<bool>, default = false)] pub payout_test_mode: Option<bool>, } #[derive(Clone, Debug, serde::Serialize)] pub struct MaskedHeaders(HashMap<String, String>); impl MaskedHeaders { fn mask_value(value: &str) -> String { let value_len = value.len(); let masked_value = if value_len <= 4 { "*".repeat(value_len) } else { value .char_indices() .map(|(index, ch)| { if index < 2 || index >= value_len - 2 { // Show the first two and last two characters, mask the rest with '*' ch } else { // Mask the remaining characters '*' } }) .collect::<String>() }; masked_value } pub fn from_headers(headers: HashMap<String, Secret<String>>) -> Self { let masked_headers = headers .into_iter() .map(|(key, value)| (key, Self::mask_value(value.peek()))) .collect(); Self(masked_headers) } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BusinessGenericLinkConfig { /// Custom domain name to be used for hosting the link pub domain_name: Option<String>, /// A list of allowed domains (glob patterns) where this link can be embedded / opened from pub allowed_domains: HashSet<String>, #[serde(flatten)] #[schema(value_type = GenericLinkUiConfig)] pub ui_config: link_utils::GenericLinkUiConfig, } impl BusinessGenericLinkConfig { pub fn validate(&self) -> Result<(), &str> { // Validate host domain name let host_domain_valid = self .domain_name .clone() .map(|host_domain| link_utils::validate_strict_domain(&host_domain)) .unwrap_or(true); if !host_domain_valid { return Err("Invalid host domain name received in payout_link_config"); } let are_allowed_domains_valid = self .allowed_domains .clone() .iter() .all(|allowed_domain| link_utils::validate_wildcard_domain(allowed_domain)); if !are_allowed_domains_valid { return Err("Invalid allowed domain names received in payout_link_config"); } Ok(()) } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct BusinessPaymentLinkConfig { /// Custom domain name to be used for hosting the link in your own domain pub domain_name: Option<String>, /// Default payment link config for all future payment link #[serde(flatten)] #[schema(value_type = PaymentLinkConfigRequest)] pub default_config: Option<PaymentLinkConfigRequest>, /// list of configs for multi theme setup pub business_specific_configs: Option<HashMap<String, PaymentLinkConfigRequest>>, /// A list of allowed domains (glob patterns) where this link can be embedded / opened from #[schema(value_type = Option<HashSet<String>>)] pub allowed_domains: Option<HashSet<String>>, /// Toggle for HyperSwitch branding visibility pub branding_visibility: Option<bool>, } impl BusinessPaymentLinkConfig { pub fn validate(&self) -> Result<(), &str> { let host_domain_valid = self .domain_name .clone() .map(|host_domain| link_utils::validate_strict_domain(&host_domain)) .unwrap_or(true); if !host_domain_valid { return Err("Invalid host domain name received in payment_link_config"); } let are_allowed_domains_valid = self .allowed_domains .clone() .map(|allowed_domains| { allowed_domains .iter() .all(|allowed_domain| link_utils::validate_wildcard_domain(allowed_domain)) }) .unwrap_or(true); if !are_allowed_domains_valid { return Err("Invalid allowed domain names received in payment_link_config"); } Ok(()) } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkConfigRequest { /// custom theme for the payment link #[schema(value_type = Option<String>, max_length = 255, example = "#4E6ADD")] pub theme: Option<String>, /// merchant display logo #[schema(value_type = Option<String>, max_length = 255, example = "https://i.pinimg.com/736x/4d/83/5c/4d835ca8aafbbb15f84d07d926fda473.jpg")] pub logo: Option<String>, /// Custom merchant name for payment link #[schema(value_type = Option<String>, max_length = 255, example = "hyperswitch")] pub seller_name: Option<String>, /// Custom layout for sdk #[schema(value_type = Option<String>, max_length = 255, example = "accordion")] pub sdk_layout: Option<String>, /// Display only the sdk for payment link #[schema(default = false, example = true)] pub display_sdk_only: Option<bool>, /// Enable saved payment method option for payment link #[schema(default = false, example = true)] pub enabled_saved_payment_method: Option<bool>, /// Hide card nickname field option for payment link #[schema(default = false, example = true)] pub hide_card_nickname_field: Option<bool>, /// Show card form by default for payment link #[schema(default = true, example = true)] pub show_card_form_by_default: Option<bool>, /// Dynamic details related to merchant to be rendered in payment link pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>, /// Configurations for the background image for details section pub background_image: Option<PaymentLinkBackgroundImageConfig>, /// Custom layout for details section #[schema(value_type = Option<PaymentLinkDetailsLayout>, example = "layout1")] pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, /// Text for payment link's handle confirm button pub payment_button_text: Option<String>, /// Text for customizing message for card terms pub custom_message_for_card_terms: Option<String>, /// Custom background colour for payment link's handle confirm button pub payment_button_colour: Option<String>, /// Skip the status screen after payment completion pub skip_status_screen: Option<bool>, /// Custom text colour for payment link's handle confirm button pub payment_button_text_colour: Option<String>, /// Custom background colour for the payment link pub background_colour: Option<String>, /// SDK configuration rules pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: Option<bool>, /// Optional header for the SDK's payment form pub payment_form_header_text: Option<String>, /// Label type in the SDK's payment form #[schema(value_type = Option<PaymentLinkSdkLabelType>, example = "floating")] pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, /// Boolean for controlling whether or not to show the explicit consent for storing cards #[schema(value_type = Option<PaymentLinkShowSdkTerms>, example = "always")] pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, /// Boolean to control payment button text for setup mandate calls pub is_setup_mandate_flow: Option<bool>, /// Hex color for the CVC icon during error state pub color_icon_card_cvc_error: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkTransactionDetails { /// Key for the transaction details #[schema(value_type = String, max_length = 255, example = "Policy-Number")] pub key: String, /// Value for the transaction details #[schema(value_type = String, max_length = 255, example = "297472368473924")] pub value: String, /// UI configuration for the transaction details pub ui_configuration: Option<TransactionDetailsUiConfiguration>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct TransactionDetailsUiConfiguration { /// Position of the key-value pair in the UI #[schema(value_type = Option<i8>, example = 5)] pub position: Option<i8>, /// Whether the key should be bold #[schema(default = false, example = true)] pub is_key_bold: Option<bool>, /// Whether the value should be bold #[schema(default = false, example = true)] pub is_value_bold: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkBackgroundImageConfig { /// URL of the image #[schema(value_type = String, example = "https://hyperswitch.io/favicon.ico")] pub url: common_utils::types::Url, /// Position of the image in the UI #[schema(value_type = Option<ElementPosition>, example = "top-left")] pub position: Option<api_enums::ElementPosition>, /// Size of the image in the UI #[schema(value_type = Option<ElementSize>, example = "contain")] pub size: Option<api_enums::ElementSize>, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, ToSchema)] pub struct PaymentLinkConfig { /// custom theme for the payment link pub theme: String, /// merchant display logo pub logo: String, /// Custom merchant name for payment link pub seller_name: String, /// Custom layout for sdk pub sdk_layout: String, /// Display only the sdk for payment link pub display_sdk_only: bool, /// Enable saved payment method option for payment link pub enabled_saved_payment_method: bool, /// Hide card nickname field option for payment link pub hide_card_nickname_field: bool, /// Show card form by default for payment link pub show_card_form_by_default: bool, /// A list of allowed domains (glob patterns) where this link can be embedded / opened from pub allowed_domains: Option<HashSet<String>>, /// Dynamic details related to merchant to be rendered in payment link pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>, /// Configurations for the background image for details section pub background_image: Option<PaymentLinkBackgroundImageConfig>, /// Custom layout for details section #[schema(value_type = Option<PaymentLinkDetailsLayout>, example = "layout1")] pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, /// Toggle for HyperSwitch branding visibility pub branding_visibility: Option<bool>, /// Text for payment link's handle confirm button pub payment_button_text: Option<String>, /// Text for customizing message for card terms pub custom_message_for_card_terms: Option<String>, /// Custom background colour for payment link's handle confirm button pub payment_button_colour: Option<String>, /// Skip the status screen after payment completion pub skip_status_screen: Option<bool>, /// Custom text colour for payment link's handle confirm button pub payment_button_text_colour: Option<String>, /// Custom background colour for the payment link pub background_colour: Option<String>, /// SDK configuration rules pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: bool, /// Optional header for the SDK's payment form pub payment_form_header_text: Option<String>, /// Label type in the SDK's payment form #[schema(value_type = Option<PaymentLinkSdkLabelType>, example = "floating")] pub payment_form_label_type: Option<api_enums::PaymentLinkSdkLabelType>, /// Boolean for controlling whether or not to show the explicit consent for storing cards #[schema(value_type = Option<PaymentLinkShowSdkTerms>, example = "always")] pub show_card_terms: Option<api_enums::PaymentLinkShowSdkTerms>, /// Boolean to control payment button text for setup mandate calls pub is_setup_mandate_flow: Option<bool>, /// Hex color for the CVC icon during error state pub color_icon_card_cvc_error: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct ExtendedCardInfoChoice { pub enabled: bool, } impl common_utils::events::ApiEventMetric for ExtendedCardInfoChoice {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct ConnectorAgnosticMitChoice { pub enabled: bool, } impl common_utils::events::ApiEventMetric for ConnectorAgnosticMitChoice {} impl common_utils::events::ApiEventMetric for payment_methods::PaymentMethodMigrate {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ExtendedCardInfoConfig { /// Merchant public key #[schema(value_type = String)] pub public_key: Secret<String>, /// TTL for extended card info #[schema(default = 900, maximum = 7200, value_type = u16)] #[serde(default)] pub ttl_in_secs: TtlForExtendedCardInfo, } #[derive(Debug, serde::Serialize, Clone)] pub struct TtlForExtendedCardInfo(u16); impl Default for TtlForExtendedCardInfo { fn default() -> Self { Self(consts::DEFAULT_TTL_FOR_EXTENDED_CARD_INFO) } } impl<'de> Deserialize<'de> for TtlForExtendedCardInfo { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let value = u16::deserialize(deserializer)?; // Check if value exceeds the maximum allowed if value > consts::MAX_TTL_FOR_EXTENDED_CARD_INFO { Err(serde::de::Error::custom( "ttl_in_secs must be less than or equal to 7200 (2hrs)", )) } else { Ok(Self(value)) } } } impl std::ops::Deref for TtlForExtendedCardInfo { type Target = u16; fn deref(&self) -> &Self::Target { &self.0 } }
crates/api_models/src/admin.rs
api_models::src::admin
35,419
true
// File: crates/api_models/src/connector_onboarding.rs // Module: api_models::src::connector_onboarding use common_utils::id_type; use super::{admin, enums}; #[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] pub struct ActionUrlRequest { pub connector: enums::Connector, pub connector_id: id_type::MerchantConnectorAccountId, pub return_url: String, } #[derive(serde::Serialize, Debug, Clone)] #[serde(rename_all = "lowercase")] pub enum ActionUrlResponse { PayPal(PayPalActionUrlResponse), } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] pub struct OnboardingSyncRequest { pub profile_id: id_type::ProfileId, pub connector_id: id_type::MerchantConnectorAccountId, pub connector: enums::Connector, } #[derive(serde::Serialize, Debug, Clone)] pub struct PayPalActionUrlResponse { pub action_url: String, } #[derive(serde::Serialize, Debug, Clone)] #[serde(rename_all = "lowercase")] pub enum OnboardingStatus { PayPal(PayPalOnboardingStatus), } #[derive(serde::Serialize, Debug, Clone)] #[serde(rename_all = "snake_case")] pub enum PayPalOnboardingStatus { AccountNotFound, PaymentsNotReceivable, PpcpCustomDenied, MorePermissionsNeeded, EmailNotVerified, Success(PayPalOnboardingDone), ConnectorIntegrated(Box<admin::MerchantConnectorResponse>), } #[derive(serde::Serialize, Debug, Clone)] pub struct PayPalOnboardingDone { pub payer_id: id_type::MerchantId, } #[derive(serde::Serialize, Debug, Clone)] pub struct PayPalIntegrationDone { pub connector_id: String, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] pub struct ResetTrackingIdRequest { pub connector_id: id_type::MerchantConnectorAccountId, pub connector: enums::Connector, }
crates/api_models/src/connector_onboarding.rs
api_models::src::connector_onboarding
415
true
// File: crates/api_models/src/chat.rs // Module: api_models::src::chat use common_utils::id_type; use masking::Secret; use time::PrimitiveDateTime; #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ChatRequest { pub message: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ChatResponse { pub response: Secret<serde_json::Value>, pub merchant_id: id_type::MerchantId, pub status: String, #[serde(skip_serializing)] pub query_executed: Option<Secret<String>>, #[serde(skip_serializing)] pub row_count: Option<i32>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ChatListRequest { pub merchant_id: Option<id_type::MerchantId>, pub limit: Option<i64>, pub offset: Option<i64>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ChatConversation { pub id: String, pub session_id: Option<String>, pub user_id: Option<String>, pub merchant_id: Option<String>, pub profile_id: Option<String>, pub org_id: Option<String>, pub role_id: Option<String>, pub user_query: Secret<String>, pub response: Secret<serde_json::Value>, pub database_query: Option<String>, pub interaction_status: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ChatListResponse { pub conversations: Vec<ChatConversation>, }
crates/api_models/src/chat.rs
api_models::src::chat
360
true
// File: crates/api_models/src/pm_auth.rs // Module: api_models::src::pm_auth use common_enums::{PaymentMethod, PaymentMethodType}; use common_utils::{ events::{ApiEventMetric, ApiEventsType}, id_type, impl_api_event_type, }; #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct LinkTokenCreateRequest { pub language: Option<String>, // optional language field to be passed pub client_secret: Option<String>, // client secret to be passed in req body pub payment_id: id_type::PaymentId, // payment_id to be passed in req body for redis pm_auth connector name fetch pub payment_method: PaymentMethod, // payment_method to be used for filtering pm_auth connector pub payment_method_type: PaymentMethodType, // payment_method_type to be used for filtering pm_auth connector } #[derive(Debug, Clone, serde::Serialize)] pub struct LinkTokenCreateResponse { pub link_token: String, // link_token received in response pub connector: String, // pm_auth connector name in response } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct ExchangeTokenCreateRequest { pub public_token: String, pub client_secret: Option<String>, pub payment_id: id_type::PaymentId, pub payment_method: PaymentMethod, pub payment_method_type: PaymentMethodType, } #[derive(Debug, Clone, serde::Serialize)] pub struct ExchangeTokenCreateResponse { pub access_token: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodAuthConfig { pub enabled_payment_methods: Vec<PaymentMethodAuthConnectorChoice>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodAuthConnectorChoice { pub payment_method: PaymentMethod, pub payment_method_type: PaymentMethodType, pub connector_name: String, pub mca_id: id_type::MerchantConnectorAccountId, } impl_api_event_type!( Miscellaneous, ( LinkTokenCreateRequest, LinkTokenCreateResponse, ExchangeTokenCreateRequest, ExchangeTokenCreateResponse ) );
crates/api_models/src/pm_auth.rs
api_models::src::pm_auth
476
true
// File: crates/api_models/src/payments/trait_impls.rs // Module: api_models::src::payments::trait_impls #[cfg(feature = "v1")] use common_enums::enums; #[cfg(feature = "v1")] use common_utils::errors; #[cfg(feature = "v1")] use crate::payments; #[cfg(feature = "v1")] impl crate::ValidateFieldAndGet<payments::PaymentsRequest> for common_types::primitive_wrappers::RequestExtendedAuthorizationBool { fn validate_field_and_get( &self, request: &payments::PaymentsRequest, ) -> errors::CustomResult<Self, errors::ValidationError> where Self: Sized, { match request.capture_method{ Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::Scheduled) | Some(enums::CaptureMethod::SequentialAutomatic) | None => Err(error_stack::report!(errors::ValidationError::InvalidValue { message: "request_extended_authorization must be sent only if capture method is manual or manual_multiple".to_string() })), Some(enums::CaptureMethod::Manual) | Some(enums::CaptureMethod::ManualMultiple) => Ok(*self) } } }
crates/api_models/src/payments/trait_impls.rs
api_models::src::payments::trait_impls
262
true
// File: crates/api_models/src/payments/additional_info.rs // Module: api_models::src::payments::additional_info use common_utils::new_type::{ MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId, }; use masking::Secret; use utoipa::ToSchema; use crate::enums as api_enums; #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankDebitAdditionalData { Ach(Box<AchBankDebitAdditionalData>), Bacs(Box<BacsBankDebitAdditionalData>), Becs(Box<BecsBankDebitAdditionalData>), Sepa(Box<SepaBankDebitAdditionalData>), SepaGuarenteedDebit(Box<SepaBankDebitAdditionalData>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBankDebitAdditionalData { /// Partially masked account number for ach bank debit payment #[schema(value_type = String, example = "0001****3456")] pub account_number: MaskedBankAccount, /// Partially masked routing number for ach bank debit payment #[schema(value_type = String, example = "110***000")] pub routing_number: MaskedRoutingNumber, /// Card holder's name #[schema(value_type = Option<String>, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, /// Name of the bank #[schema(value_type = Option<BankNames>, example = "ach")] pub bank_name: Option<common_enums::BankNames>, /// Bank account type #[schema(value_type = Option<BankType>, example = "checking")] pub bank_type: Option<common_enums::BankType>, /// Bank holder entity type #[schema(value_type = Option<BankHolderType>, example = "personal")] pub bank_holder_type: Option<common_enums::BankHolderType>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankDebitAdditionalData { /// Partially masked account number for Bacs payment method #[schema(value_type = String, example = "0001****3456")] pub account_number: MaskedBankAccount, /// Partially masked sort code for Bacs payment method #[schema(value_type = String, example = "108800")] pub sort_code: MaskedSortCode, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BecsBankDebitAdditionalData { /// Partially masked account number for Becs payment method #[schema(value_type = String, example = "0001****3456")] pub account_number: MaskedBankAccount, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] pub bsb_number: Secret<String>, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankDebitAdditionalData { /// Partially masked international bank account number (iban) for SEPA #[schema(value_type = String, example = "DE8937******013000")] pub iban: MaskedIban, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub enum BankRedirectDetails { BancontactCard(Box<BancontactBankRedirectAdditionalData>), Blik(Box<BlikBankRedirectAdditionalData>), Giropay(Box<GiropayBankRedirectAdditionalData>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BancontactBankRedirectAdditionalData { /// Last 4 digits of the card number #[schema(value_type = Option<String>, example = "4242")] pub last4: Option<String>, /// The card's expiry month #[schema(value_type = Option<String>, example = "12")] pub card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = Option<String>, example = "24")] pub card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = Option<String>, example = "John Test")] pub card_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BlikBankRedirectAdditionalData { #[schema(value_type = Option<String>, example = "3GD9MO")] pub blik_code: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GiropayBankRedirectAdditionalData { #[schema(value_type = Option<String>)] /// Masked bank account bic code pub bic: Option<MaskedSortCode>, /// Partially masked international bank account number (iban) for SEPA #[schema(value_type = Option<String>)] pub iban: Option<MaskedIban>, /// Country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferAdditionalData { Ach {}, Sepa {}, Bacs {}, Multibanco {}, Permata {}, Bca {}, BniVa {}, BriVa {}, CimbVa {}, DanamonVa {}, MandiriVa {}, Pix(Box<PixBankTransferAdditionalData>), Pse {}, LocalBankTransfer(Box<LocalBankTransferAdditionalData>), InstantBankTransfer {}, InstantBankTransferFinland {}, InstantBankTransferPoland {}, IndonesianBankTransfer { #[schema(value_type = Option<BankNames>, example = "bri")] bank_name: Option<common_enums::BankNames>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PixBankTransferAdditionalData { /// Partially masked unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e ****** 6fa48899c1d1")] pub pix_key: Option<MaskedBankAccount>, /// Partially masked CPF - CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "**** 124689")] pub cpf: Option<MaskedBankAccount>, /// Partially masked CNPJ - CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "**** 417312")] pub cnpj: Option<MaskedBankAccount>, /// Partially masked source bank account number #[schema(value_type = Option<String>, example = "********-****-4073-****-9fa964d08bc5")] pub source_bank_account_id: Option<MaskedBankAccount>, /// Partially masked destination bank account number _Deprecated: Will be removed in next stable release._ #[schema(value_type = Option<String>, example = "********-****-460b-****-f23b4e71c97b", deprecated)] pub destination_bank_account_id: Option<MaskedBankAccount>, /// The expiration date and time for the Pix QR code in ISO 8601 format #[schema(value_type = Option<String>, example = "2025-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expiry_date: Option<time::PrimitiveDateTime>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct LocalBankTransferAdditionalData { /// Partially masked bank code #[schema(value_type = Option<String>, example = "**** OA2312")] pub bank_code: Option<MaskedBankAccount>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum GiftCardAdditionalData { Givex(Box<GivexGiftCardAdditionalData>), PaySafeCard {}, BhnCardNetwork {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GivexGiftCardAdditionalData { /// Last 4 digits of the gift card number #[schema(value_type = String, example = "4242")] pub last4: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardTokenAdditionalData { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiAdditionalData { UpiCollect(Box<UpiCollectAdditionalData>), #[schema(value_type = UpiIntentData)] UpiIntent(Box<super::UpiIntentData>), #[schema(value_type = UpiQrData)] UpiQr(Box<super::UpiQrData>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiCollectAdditionalData { /// Masked VPA ID #[schema(value_type = Option<String>, example = "ab********@okhdfcbank")] pub vpa_id: Option<MaskedUpiVpaId>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WalletAdditionalDataForCard { /// Last 4 digits of the card number pub last4: String, /// The information of the payment method pub card_network: String, /// The type of payment method #[serde(rename = "type")] pub card_type: Option<String>, }
crates/api_models/src/payments/additional_info.rs
api_models::src::payments::additional_info
2,480
true
// File: crates/api_models/src/process_tracker/revenue_recovery.rs // Module: api_models::src::process_tracker::revenue_recovery use common_utils::id_type; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::enums; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct RevenueRecoveryResponse { pub id: String, pub name: Option<String>, #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub schedule_time_for_payment: Option<PrimitiveDateTime>, #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub schedule_time_for_psync: Option<PrimitiveDateTime>, #[schema(value_type = ProcessTrackerStatus, example = "finish")] pub status: enums::ProcessTrackerStatus, pub business_status: String, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct RevenueRecoveryId { pub revenue_recovery_id: id_type::GlobalPaymentId, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct RevenueRecoveryRetriggerRequest { /// The task we want to resume pub revenue_recovery_task: String, /// Time at which the job was scheduled at #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub schedule_time: Option<PrimitiveDateTime>, /// Status of The Process Tracker Task pub status: enums::ProcessTrackerStatus, /// Business Status of The Process Tracker Task pub business_status: String, }
crates/api_models/src/process_tracker/revenue_recovery.rs
api_models::src::process_tracker::revenue_recovery
435
true
// File: crates/api_models/src/user_role/role.rs // Module: api_models::src::user_role::role use common_enums::{ EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource, RoleScope, }; #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CreateRoleRequest { pub role_name: String, pub groups: Vec<PermissionGroup>, pub role_scope: RoleScope, pub entity_type: Option<EntityType>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CreateRoleV2Request { pub role_name: String, pub role_scope: RoleScope, pub entity_type: Option<EntityType>, pub parent_groups: Vec<ParentGroupInfoRequest>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UpdateRoleRequest { pub groups: Option<Vec<PermissionGroup>>, pub role_name: Option<String>, } #[derive(Debug, serde::Serialize)] pub struct RoleInfoWithGroupsResponse { pub role_id: String, pub groups: Vec<PermissionGroup>, pub role_name: String, pub role_scope: RoleScope, pub entity_type: EntityType, } #[derive(Debug, serde::Serialize)] pub struct RoleInfoWithParents { pub role_id: String, pub parent_groups: Vec<ParentGroupDescription>, pub role_name: String, pub role_scope: RoleScope, } #[derive(Debug, serde::Serialize)] pub struct ParentGroupDescription { pub name: ParentGroup, pub description: String, pub scopes: Vec<PermissionScope>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ParentGroupInfoRequest { pub name: ParentGroup, pub scopes: Vec<PermissionScope>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ListRolesQueryParams { pub entity_type: Option<EntityType>, pub groups: Option<bool>, } #[derive(Debug, serde::Serialize)] pub struct RoleInfoResponseNew { pub role_id: String, pub role_name: String, pub entity_type: EntityType, pub groups: Vec<PermissionGroup>, pub scope: RoleScope, } #[derive(Debug, serde::Serialize)] pub struct RoleInfoResponseWithParentsGroup { pub role_id: String, pub role_name: String, pub entity_type: EntityType, pub parent_groups: Vec<ParentGroupDescription>, pub role_scope: RoleScope, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetRoleRequest { pub role_id: String, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ListRolesAtEntityLevelRequest { pub entity_type: EntityType, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetParentGroupsInfoQueryParams { pub entity_type: Option<EntityType>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub enum RoleCheckType { Invite, Update, } #[derive(Debug, serde::Serialize, Clone)] pub struct MinimalRoleInfo { pub role_id: String, pub role_name: String, } #[derive(Debug, serde::Serialize)] pub struct GroupsAndResources { pub groups: Vec<PermissionGroup>, pub resources: Vec<Resource>, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum ListRolesResponse { WithGroups(Vec<RoleInfoResponseNew>), WithParentGroups(Vec<RoleInfoResponseWithParentsGroup>), } #[derive(Debug, serde::Serialize)] pub struct ParentGroupInfo { pub name: ParentGroup, pub resources: Vec<Resource>, pub scopes: Vec<PermissionScope>, }
crates/api_models/src/user_role/role.rs
api_models::src::user_role::role
774
true
// File: crates/api_models/src/user/theme.rs // Module: api_models::src::user::theme use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm}; use common_enums::EntityType; use common_utils::{ id_type, types::user::{EmailThemeConfig, ThemeLineage}, }; use masking::Secret; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize)] pub struct GetThemeResponse { pub theme_id: String, pub theme_name: String, pub entity_type: EntityType, pub tenant_id: id_type::TenantId, pub org_id: Option<id_type::OrganizationId>, pub merchant_id: Option<id_type::MerchantId>, pub profile_id: Option<id_type::ProfileId>, pub email_config: EmailThemeConfig, pub theme_data: ThemeData, } #[derive(Debug, MultipartForm)] pub struct UploadFileAssetData { pub asset_name: Text<String>, #[multipart(limit = "10MB")] pub asset_data: Bytes, } #[derive(Serialize, Deserialize, Debug)] pub struct UploadFileRequest { pub asset_name: String, pub asset_data: Secret<Vec<u8>>, } #[derive(Serialize, Deserialize, Debug)] pub struct CreateThemeRequest { pub lineage: ThemeLineage, pub theme_name: String, pub theme_data: ThemeData, pub email_config: Option<EmailThemeConfig>, } #[derive(Serialize, Deserialize, Debug)] pub struct CreateUserThemeRequest { pub entity_type: EntityType, pub theme_name: String, pub theme_data: ThemeData, pub email_config: Option<EmailThemeConfig>, } #[derive(Serialize, Deserialize, Debug)] pub struct UpdateThemeRequest { pub theme_data: Option<ThemeData>, pub email_config: Option<EmailThemeConfig>, } // All the below structs are for the theme.json file, // which will be used by frontend to style the dashboard. #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct ThemeData { settings: Settings, urls: Option<Urls>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct Settings { colors: Colors, sidebar: Option<Sidebar>, typography: Option<Typography>, buttons: Buttons, borders: Option<Borders>, spacing: Option<Spacing>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct Colors { primary: String, secondary: Option<String>, background: Option<String>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct Sidebar { primary: String, text_color: Option<String>, text_color_primary: Option<String>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct Typography { font_family: Option<String>, font_size: Option<String>, heading_font_size: Option<String>, text_color: Option<String>, link_color: Option<String>, link_hover_color: Option<String>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct Buttons { primary: PrimaryButton, secondary: Option<SecondaryButton>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct PrimaryButton { background_color: Option<String>, text_color: Option<String>, hover_background_color: String, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct SecondaryButton { background_color: Option<String>, text_color: Option<String>, hover_background_color: Option<String>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct Borders { default_radius: Option<String>, border_color: Option<String>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct Spacing { padding: Option<String>, margin: Option<String>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] struct Urls { favicon_url: Option<String>, logo_url: Option<String>, } #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "snake_case")] pub struct EntityTypeQueryParam { pub entity_type: EntityType, }
crates/api_models/src/user/theme.rs
api_models::src::user::theme
923
true
// File: crates/api_models/src/user/dashboard_metadata.rs // Module: api_models::src::user::dashboard_metadata use common_enums::{CountryAlpha2, MerchantProductType}; use common_types::primitive_wrappers::SafeString; use common_utils::{id_type, pii}; use masking::Secret; use strum::EnumString; #[derive(Debug, serde::Deserialize, serde::Serialize)] pub enum SetMetaDataRequest { ProductionAgreement(ProductionAgreementRequest), SetupProcessor(SetupProcessor), ConfigureEndpoint, SetupComplete, FirstProcessorConnected(ProcessorConnected), SecondProcessorConnected(ProcessorConnected), ConfiguredRouting(ConfiguredRouting), TestPayment(TestPayment), IntegrationMethod(IntegrationMethod), ConfigurationType(ConfigurationType), IntegrationCompleted, SPRoutingConfigured(ConfiguredRouting), Feedback(Feedback), ProdIntent(ProdIntent), SPTestPayment, DownloadWoocom, ConfigureWoocom, SetupWoocomWebhook, IsMultipleConfiguration, #[serde(skip)] IsChangePasswordRequired, OnboardingSurvey(OnboardingSurvey), ReconStatus(ReconStatus), } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ProductionAgreementRequest { pub version: String, #[serde(skip_deserializing)] pub ip_address: Option<Secret<String, pii::IpAddress>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SetupProcessor { pub connector_id: String, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ProcessorConnected { pub processor_id: id_type::MerchantConnectorAccountId, pub processor_name: String, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct OnboardingSurvey { pub designation: Option<SafeString>, pub about_business: Option<SafeString>, pub business_website: Option<SafeString>, pub hyperswitch_req: Option<SafeString>, pub major_markets: Option<Vec<SafeString>>, pub business_size: Option<SafeString>, pub required_features: Option<Vec<SafeString>>, pub required_processors: Option<Vec<SafeString>>, pub planned_live_date: Option<SafeString>, pub miscellaneous: Option<SafeString>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ConfiguredRouting { pub routing_id: String, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TestPayment { pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct IntegrationMethod { pub integration_type: String, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum ConfigurationType { Single, Multiple, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct Feedback { pub email: pii::Email, pub description: Option<SafeString>, pub rating: Option<i32>, pub category: Option<SafeString>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ProdIntent { pub legal_business_name: Option<SafeString>, pub business_label: Option<SafeString>, pub business_location: Option<CountryAlpha2>, pub display_name: Option<SafeString>, pub poc_email: Option<pii::Email>, pub business_type: Option<SafeString>, pub business_identifier: Option<SafeString>, pub business_website: Option<SafeString>, pub poc_name: Option<Secret<SafeString>>, pub poc_contact: Option<Secret<SafeString>>, pub comments: Option<SafeString>, pub is_completed: bool, #[serde(default)] pub product_type: MerchantProductType, pub business_country_name: Option<SafeString>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ReconStatus { pub is_order_data_set: bool, pub is_processor_data_set: bool, } #[derive(Debug, serde::Deserialize, EnumString, serde::Serialize)] pub enum GetMetaDataRequest { ProductionAgreement, SetupProcessor, ConfigureEndpoint, SetupComplete, FirstProcessorConnected, SecondProcessorConnected, ConfiguredRouting, TestPayment, IntegrationMethod, ConfigurationType, IntegrationCompleted, StripeConnected, PaypalConnected, SPRoutingConfigured, Feedback, ProdIntent, SPTestPayment, DownloadWoocom, ConfigureWoocom, SetupWoocomWebhook, IsMultipleConfiguration, IsChangePasswordRequired, OnboardingSurvey, ReconStatus, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(transparent)] pub struct GetMultipleMetaDataPayload { pub results: Vec<GetMetaDataRequest>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetMultipleMetaDataRequest { pub keys: String, } #[derive(Debug, serde::Serialize)] pub enum GetMetaDataResponse { ProductionAgreement(bool), SetupProcessor(Option<SetupProcessor>), ConfigureEndpoint(bool), SetupComplete(bool), FirstProcessorConnected(Option<ProcessorConnected>), SecondProcessorConnected(Option<ProcessorConnected>), ConfiguredRouting(Option<ConfiguredRouting>), TestPayment(Option<TestPayment>), IntegrationMethod(Option<IntegrationMethod>), ConfigurationType(Option<ConfigurationType>), IntegrationCompleted(bool), StripeConnected(Option<ProcessorConnected>), PaypalConnected(Option<ProcessorConnected>), SPRoutingConfigured(Option<ConfiguredRouting>), Feedback(Option<Feedback>), ProdIntent(Option<ProdIntent>), SPTestPayment(bool), DownloadWoocom(bool), ConfigureWoocom(bool), SetupWoocomWebhook(bool), IsMultipleConfiguration(bool), IsChangePasswordRequired(bool), OnboardingSurvey(Option<OnboardingSurvey>), ReconStatus(Option<ReconStatus>), }
crates/api_models/src/user/dashboard_metadata.rs
api_models::src::user::dashboard_metadata
1,254
true
// File: crates/api_models/src/user/sample_data.rs // Module: api_models::src::user::sample_data use common_enums::{AuthenticationType, CountryAlpha2}; use time::PrimitiveDateTime; use crate::enums::Connector; #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct SampleDataRequest { pub record: Option<usize>, pub connector: Option<Vec<Connector>>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_time: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_time: Option<PrimitiveDateTime>, // The amount for each sample will be between min_amount and max_amount (in dollars) pub min_amount: Option<i64>, pub max_amount: Option<i64>, pub currency: Option<Vec<common_enums::Currency>>, pub auth_type: Option<Vec<AuthenticationType>>, pub business_country: Option<CountryAlpha2>, pub business_label: Option<String>, pub profile_id: Option<common_utils::id_type::ProfileId>, }
crates/api_models/src/user/sample_data.rs
api_models::src::user::sample_data
250
true
// File: crates/api_models/src/errors/types.rs // Module: api_models::src::errors::types use reqwest::StatusCode; use router_derive::PolymorphicSchema; use serde::Serialize; use utoipa::ToSchema; #[derive(Debug, serde::Serialize)] pub enum ErrorType { InvalidRequestError, RouterError, ConnectorError, } #[derive(Debug, serde::Serialize, Clone)] pub struct ApiError { pub sub_code: &'static str, pub error_identifier: u16, pub error_message: String, pub extra: Option<Extra>, #[cfg(feature = "detailed_errors")] pub stacktrace: Option<serde_json::Value>, } impl ApiError { pub fn new( sub_code: &'static str, error_identifier: u16, error_message: impl ToString, extra: Option<Extra>, ) -> Self { Self { sub_code, error_identifier, error_message: error_message.to_string(), extra, #[cfg(feature = "detailed_errors")] stacktrace: None, } } } #[derive(Debug, serde::Serialize, ToSchema, PolymorphicSchema)] #[generate_schemas(GenericErrorResponseOpenApi)] pub struct ErrorResponse { #[serde(rename = "type")] #[schema( example = "invalid_request", value_type = &'static str )] pub error_type: &'static str, #[schema( example = "Missing required param: {param}", value_type = String )] pub message: String, #[schema( example = "IR_04", value_type = String )] pub code: String, #[serde(flatten)] pub extra: Option<Extra>, #[cfg(feature = "detailed_errors")] #[serde(skip_serializing_if = "Option::is_none")] pub stacktrace: Option<serde_json::Value>, } impl From<&ApiErrorResponse> for ErrorResponse { fn from(value: &ApiErrorResponse) -> Self { let error_info = value.get_internal_error(); let error_type = value.error_type(); Self { code: format!("{}_{:02}", error_info.sub_code, error_info.error_identifier), message: error_info.error_message.clone(), error_type, extra: error_info.extra.clone(), #[cfg(feature = "detailed_errors")] stacktrace: error_info.stacktrace.clone(), } } } #[derive(Debug, serde::Serialize, Default, Clone)] pub struct Extra { #[serde(skip_serializing_if = "Option::is_none")] pub payment_id: Option<common_utils::id_type::PaymentId>, #[serde(skip_serializing_if = "Option::is_none")] pub data: Option<serde_json::Value>, #[serde(skip_serializing_if = "Option::is_none")] pub connector: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub connector_transaction_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub fields: Option<String>, } #[derive(Serialize, Debug, Clone)] #[serde(tag = "type", content = "value")] pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), } impl ::core::fmt::Display for ApiErrorResponse { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let error_response: ErrorResponse = self.into(); write!( f, r#"{{"error":{}}}"#, serde_json::to_string(&error_response) .unwrap_or_else(|_| "API error response".to_string()) ) } } impl ApiErrorResponse { pub(crate) fn get_internal_error(&self) -> &ApiError { match self { Self::Unauthorized(i) | Self::ForbiddenCommonResource(i) | Self::ForbiddenPrivateResource(i) | Self::Conflict(i) | Self::Gone(i) | Self::Unprocessable(i) | Self::InternalServerError(i) | Self::NotImplemented(i) | Self::NotFound(i) | Self::MethodNotAllowed(i) | Self::BadRequest(i) | Self::DomainError(i) | Self::ConnectorError(i, _) => i, } } pub fn get_internal_error_mut(&mut self) -> &mut ApiError { match self { Self::Unauthorized(i) | Self::ForbiddenCommonResource(i) | Self::ForbiddenPrivateResource(i) | Self::Conflict(i) | Self::Gone(i) | Self::Unprocessable(i) | Self::InternalServerError(i) | Self::NotImplemented(i) | Self::NotFound(i) | Self::MethodNotAllowed(i) | Self::BadRequest(i) | Self::DomainError(i) | Self::ConnectorError(i, _) => i, } } pub(crate) fn error_type(&self) -> &'static str { match self { Self::Unauthorized(_) | Self::ForbiddenCommonResource(_) | Self::ForbiddenPrivateResource(_) | Self::Conflict(_) | Self::Gone(_) | Self::Unprocessable(_) | Self::NotImplemented(_) | Self::MethodNotAllowed(_) | Self::NotFound(_) | Self::BadRequest(_) => "invalid_request", Self::InternalServerError(_) => "api", Self::DomainError(_) => "blocked", Self::ConnectorError(_, _) => "connector", } } } impl std::error::Error for ApiErrorResponse {}
crates/api_models/src/errors/types.rs
api_models::src::errors::types
1,291
true
// File: crates/api_models/src/errors/actix.rs // Module: api_models::src::errors::actix use super::types::ApiErrorResponse; impl actix_web::ResponseError for ApiErrorResponse { fn status_code(&self) -> reqwest::StatusCode { use reqwest::StatusCode; match self { Self::Unauthorized(_) => StatusCode::UNAUTHORIZED, Self::ForbiddenCommonResource(_) => StatusCode::FORBIDDEN, Self::ForbiddenPrivateResource(_) => StatusCode::NOT_FOUND, Self::Conflict(_) => StatusCode::CONFLICT, Self::Gone(_) => StatusCode::GONE, Self::Unprocessable(_) => StatusCode::UNPROCESSABLE_ENTITY, Self::InternalServerError(_) => StatusCode::INTERNAL_SERVER_ERROR, Self::NotImplemented(_) => StatusCode::NOT_IMPLEMENTED, Self::ConnectorError(_, code) => *code, Self::MethodNotAllowed(_) => StatusCode::METHOD_NOT_ALLOWED, Self::NotFound(_) => StatusCode::NOT_FOUND, Self::BadRequest(_) => StatusCode::BAD_REQUEST, Self::DomainError(_) => StatusCode::OK, } } 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()) } }
crates/api_models/src/errors/actix.rs
api_models::src::errors::actix
293
true
// File: crates/api_models/src/events/locker_migration.rs // Module: api_models::src::events::locker_migration use common_utils::events::ApiEventMetric; use crate::locker_migration::MigrateCardResponse; impl ApiEventMetric for MigrateCardResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::RustLocker) } }
crates/api_models/src/events/locker_migration.rs
api_models::src::events::locker_migration
97
true
// File: crates/api_models/src/events/dispute.rs // Module: api_models::src::events::dispute use common_utils::events::{ApiEventMetric, ApiEventsType}; use super::{ DeleteEvidenceRequest, DisputeResponse, DisputeResponsePaymentsRetrieve, DisputeRetrieveRequest, DisputesAggregateResponse, SubmitEvidenceRequest, }; impl ApiEventMetric for SubmitEvidenceRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Dispute { dispute_id: self.dispute_id.clone(), }) } } impl ApiEventMetric for DisputeRetrieveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Dispute { dispute_id: self.dispute_id.clone(), }) } } impl ApiEventMetric for DisputeResponsePaymentsRetrieve { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Dispute { dispute_id: self.dispute_id.clone(), }) } } impl ApiEventMetric for DisputeResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Dispute { dispute_id: self.dispute_id.clone(), }) } } impl ApiEventMetric for DeleteEvidenceRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Dispute { dispute_id: self.dispute_id.clone(), }) } } impl ApiEventMetric for DisputesAggregateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } }
crates/api_models/src/events/dispute.rs
api_models::src::events::dispute
368
true
// File: crates/api_models/src/events/payouts.rs // Module: api_models::src::events::payouts use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::payouts::{ PayoutActionRequest, PayoutCreateRequest, PayoutCreateResponse, PayoutLinkInitiateRequest, PayoutListConstraints, PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse, PayoutRetrieveRequest, }; impl ApiEventMetric for PayoutRetrieveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payout { payout_id: self.payout_id.to_owned(), }) } } impl ApiEventMetric for PayoutCreateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { self.payout_id.as_ref().map(|id| ApiEventsType::Payout { payout_id: id.to_owned(), }) } } impl ApiEventMetric for PayoutCreateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payout { payout_id: self.payout_id.to_owned(), }) } } impl ApiEventMetric for PayoutActionRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payout { payout_id: self.payout_id.to_owned(), }) } } impl ApiEventMetric for PayoutListConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PayoutListFilterConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PayoutListResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PayoutListFilters { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PayoutLinkInitiateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payout { payout_id: self.payout_id.to_owned(), }) } }
crates/api_models/src/events/payouts.rs
api_models::src::events::payouts
530
true
// File: crates/api_models/src/events/user.rs // Module: api_models::src::events::user use common_utils::events::{ApiEventMetric, ApiEventsType}; #[cfg(feature = "dummy_connector")] use crate::user::sample_data::SampleDataRequest; #[cfg(feature = "control_center_theme")] use crate::user::theme::{ CreateThemeRequest, CreateUserThemeRequest, GetThemeResponse, UpdateThemeRequest, UploadFileRequest, }; use crate::user::{ dashboard_metadata::{ GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest, }, AcceptInviteFromEmailRequest, AuthSelectRequest, AuthorizeResponse, BeginTotpResponse, ChangePasswordRequest, CloneConnectorRequest, ConnectAccountRequest, CreateInternalUserRequest, CreateTenantUserRequest, CreateUserAuthenticationMethodRequest, CreateUserAuthenticationMethodResponse, ForgotPasswordRequest, GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponseV2, InviteUserRequest, PlatformAccountCreateRequest, PlatformAccountCreateResponse, ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest, SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, TwoFactorAuthStatusResponse, TwoFactorStatus, UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantAccountResponse, UserMerchantCreate, UserOrgMerchantCreateRequest, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; common_utils::impl_api_event_type!( Miscellaneous, ( SignUpRequest, SignUpWithMerchantIdRequest, ChangePasswordRequest, GetMultipleMetaDataPayload, GetMetaDataResponse, GetMetaDataRequest, SetMetaDataRequest, SwitchOrganizationRequest, SwitchMerchantRequest, SwitchProfileRequest, CreateInternalUserRequest, CreateTenantUserRequest, PlatformAccountCreateRequest, PlatformAccountCreateResponse, UserOrgMerchantCreateRequest, UserMerchantAccountResponse, UserMerchantCreate, AuthorizeResponse, ConnectAccountRequest, ForgotPasswordRequest, ResetPasswordRequest, RotatePasswordRequest, InviteUserRequest, ReInviteUserRequest, VerifyEmailRequest, SendVerifyEmailRequest, AcceptInviteFromEmailRequest, UpdateUserAccountDetailsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponseV2, TokenResponse, TwoFactorAuthStatusResponse, TwoFactorStatus, UserFromEmailRequest, BeginTotpResponse, VerifyRecoveryCodeRequest, VerifyTotpRequest, RecoveryCodes, GetUserAuthenticationMethodsRequest, CreateUserAuthenticationMethodRequest, CreateUserAuthenticationMethodResponse, UpdateUserAuthenticationMethodRequest, GetSsoAuthUrlRequest, SsoSignInRequest, AuthSelectRequest, CloneConnectorRequest ) ); #[cfg(feature = "control_center_theme")] common_utils::impl_api_event_type!( Miscellaneous, ( GetThemeResponse, UploadFileRequest, CreateThemeRequest, CreateUserThemeRequest, UpdateThemeRequest ) ); #[cfg(feature = "dummy_connector")] common_utils::impl_api_event_type!(Miscellaneous, (SampleDataRequest));
crates/api_models/src/events/user.rs
api_models::src::events::user
701
true
// File: crates/api_models/src/events/user_role.rs // Module: api_models::src::events::user_role use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ role::{ CreateRoleRequest, CreateRoleV2Request, GetParentGroupsInfoQueryParams, GetRoleRequest, GroupsAndResources, ListRolesAtEntityLevelRequest, ListRolesQueryParams, ListRolesResponse, ParentGroupInfoRequest, RoleInfoResponseNew, RoleInfoResponseWithParentsGroup, RoleInfoWithGroupsResponse, RoleInfoWithParents, UpdateRoleRequest, }, AuthorizationInfoResponse, DeleteUserRoleRequest, ListUsersInEntityRequest, UpdateUserRoleRequest, }; common_utils::impl_api_event_type!( Miscellaneous, ( GetRoleRequest, GetParentGroupsInfoQueryParams, AuthorizationInfoResponse, UpdateUserRoleRequest, DeleteUserRoleRequest, CreateRoleRequest, CreateRoleV2Request, UpdateRoleRequest, ListRolesAtEntityLevelRequest, RoleInfoResponseNew, RoleInfoWithGroupsResponse, ListUsersInEntityRequest, ListRolesQueryParams, GroupsAndResources, RoleInfoWithParents, ParentGroupInfoRequest, RoleInfoResponseWithParentsGroup, ListRolesResponse ) );
crates/api_models/src/events/user_role.rs
api_models::src::events::user_role
273
true
// File: crates/api_models/src/events/refund.rs // Module: api_models::src::events::refund use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::refunds::{ self, RefundAggregateResponse, RefundListFilters, RefundListMetaData, RefundListRequest, RefundListResponse, }; #[cfg(feature = "v1")] use crate::refunds::{ RefundManualUpdateRequest, RefundRequest, RefundUpdateRequest, RefundsRetrieveRequest, }; #[cfg(feature = "v1")] impl ApiEventMetric for RefundRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { let payment_id = self.payment_id.clone(); self.refund_id .clone() .map(|refund_id| ApiEventsType::Refund { payment_id: Some(payment_id), refund_id, }) } } #[cfg(feature = "v1")] impl ApiEventMetric for refunds::RefundResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { payment_id: Some(self.payment_id.clone()), refund_id: self.refund_id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for refunds::RefundResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { payment_id: Some(self.payment_id.clone()), refund_id: self.id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for RefundsRetrieveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { payment_id: None, refund_id: self.refund_id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for refunds::RefundsRetrieveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { payment_id: None, refund_id: self.refund_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for RefundUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { payment_id: None, refund_id: self.refund_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for RefundManualUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { payment_id: None, refund_id: self.refund_id.clone(), }) } } impl ApiEventMetric for RefundListRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for RefundListResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for RefundAggregateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for RefundListMetaData { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for RefundListFilters { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } }
crates/api_models/src/events/refund.rs
api_models::src::events::refund
796
true
// File: crates/api_models/src/events/external_service_auth.rs // Module: api_models::src::events::external_service_auth use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::external_service_auth::{ ExternalSignoutTokenRequest, ExternalTokenResponse, ExternalVerifyTokenRequest, ExternalVerifyTokenResponse, }; impl ApiEventMetric for ExternalTokenResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ExternalServiceAuth) } } impl ApiEventMetric for ExternalVerifyTokenRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ExternalServiceAuth) } } impl ApiEventMetric for ExternalVerifyTokenResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ExternalServiceAuth) } } impl ApiEventMetric for ExternalSignoutTokenRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ExternalServiceAuth) } }
crates/api_models/src/events/external_service_auth.rs
api_models::src::events::external_service_auth
232
true
// File: crates/api_models/src/events/payment.rs // Module: api_models::src::events::payment use common_utils::events::{ApiEventMetric, ApiEventsType}; #[cfg(feature = "v2")] use super::{ PaymentAttemptListRequest, PaymentAttemptListResponse, PaymentStartRedirectionRequest, PaymentsCreateIntentRequest, PaymentsGetIntentRequest, PaymentsIntentResponse, PaymentsRequest, RecoveryPaymentsCreate, RecoveryPaymentsResponse, }; #[cfg(feature = "v2")] use crate::payment_methods::{ ListMethodsForPaymentMethodsRequest, PaymentMethodListResponseForSession, }; use crate::{ payment_methods::{ self, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCollectLinkResponse, PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodUpdate, }, payments::{ self, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2, PaymentListResponse, PaymentsAggregateResponse, PaymentsSessionResponse, RedirectionResponse, }, }; #[cfg(feature = "v1")] use crate::{ payment_methods::{PaymentMethodListRequest, PaymentMethodListResponse}, payments::{ ExtendedCardInfoResponse, PaymentIdType, PaymentListFilterConstraints, PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelPostCaptureRequest, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse, PaymentsExtendAuthorizationRequest, PaymentsExternalAuthenticationRequest, PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, PaymentsManualUpdateResponse, PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse, PaymentsRejectRequest, PaymentsRetrieveRequest, PaymentsStartRequest, PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse, }, }; #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsRetrieveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { match self.resource_id { PaymentIdType::PaymentIntentId(ref id) => Some(ApiEventsType::Payment { payment_id: id.clone(), }), _ => None, } } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsStartRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCaptureRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.to_owned(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCompleteAuthorizeRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsDynamicTaxCalculationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsPostSessionTokensRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsUpdateMetadataRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsUpdateMetadataResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsPostSessionTokensResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsDynamicTaxCalculationResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCancelRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCancelPostCaptureRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsExtendAuthorizationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsApproveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsRejectRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for payments::PaymentsRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { match self.payment_id { Some(PaymentIdType::PaymentIntentId(ref id)) => Some(ApiEventsType::Payment { payment_id: id.clone(), }), _ => None, } } } #[cfg(feature = "v1")] impl ApiEventMetric for payments::PaymentsEligibilityRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for payments::PaymentsEligibilityResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsCreateIntentRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for payments::GiftCardBalanceCheckResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsGetIntentRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentAttemptListRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_intent_id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentAttemptListResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsIntentResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentsResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentsCancelRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentsCancelResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for payments::PaymentsResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } impl ApiEventMetric for PaymentMethodResponse { #[cfg(feature = "v1")] fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_id.clone(), payment_method: self.payment_method, payment_method_type: self.payment_method_type, }) } #[cfg(feature = "v2")] fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.id.clone(), payment_method_type: self.payment_method_type, payment_method_subtype: self.payment_method_subtype, }) } } impl ApiEventMetric for PaymentMethodMigrateResponse { #[cfg(feature = "v1")] fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_response.payment_method_id.clone(), payment_method: self.payment_method_response.payment_method, payment_method_type: self.payment_method_response.payment_method_type, }) } #[cfg(feature = "v2")] fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_response.id.clone(), payment_method_type: self.payment_method_response.payment_method_type, payment_method_subtype: self.payment_method_response.payment_method_subtype, }) } } impl ApiEventMetric for PaymentMethodUpdate {} #[cfg(feature = "v1")] impl ApiEventMetric for payment_methods::DefaultPaymentMethod { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_id.clone(), payment_method: None, payment_method_type: None, }) } } #[cfg(feature = "v2")] impl ApiEventMetric for payment_methods::PaymentMethodDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.id.clone(), payment_method_type: None, payment_method_subtype: None, }) } } #[cfg(feature = "v1")] impl ApiEventMetric for payment_methods::PaymentMethodDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_id.clone(), payment_method: None, payment_method_type: None, }) } } impl ApiEventMetric for payment_methods::CustomerPaymentMethodsListResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentMethodListRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodList { payment_id: self .client_secret .as_ref() .and_then(|cs| cs.rsplit_once("_secret_")) .map(|(pid, _)| pid.to_string()), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for ListMethodsForPaymentMethodsRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodList { payment_id: self .client_secret .as_ref() .and_then(|cs| cs.rsplit_once("_secret_")) .map(|(pid, _)| pid.to_string()), }) } } impl ApiEventMetric for ListCountriesCurrenciesRequest {} impl ApiEventMetric for ListCountriesCurrenciesResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentMethodListResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for payment_methods::CustomerDefaultPaymentMethodResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.default_payment_method_id.clone().unwrap_or_default(), payment_method: Some(self.payment_method), payment_method_type: self.payment_method_type, }) } } impl ApiEventMetric for PaymentMethodCollectLinkRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { self.pm_collect_link_id .as_ref() .map(|id| ApiEventsType::PaymentMethodCollectLink { link_id: id.clone(), }) } } impl ApiEventMetric for PaymentMethodCollectLinkRenderRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodCollectLink { link_id: self.pm_collect_link_id.clone(), }) } } impl ApiEventMetric for PaymentMethodCollectLinkResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodCollectLink { link_id: self.pm_collect_link_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentListFilterConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentListFilters { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentListFiltersV2 { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentListConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentListResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } #[cfg(feature = "v2")] impl ApiEventMetric for RecoveryPaymentsCreate { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for RecoveryPaymentsResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentListResponseV2 { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentsAggregateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for RedirectionResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsIncrementalAuthorizationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsExternalAuthenticationResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsExternalAuthenticationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for ExtendedCardInfoResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsManualUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsManualUpdateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } impl ApiEventMetric for PaymentsSessionResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentStartRedirectionRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentMethodListResponseForPayments { // Payment id would be populated by the request fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentMethodListResponseForSession {} #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentsCaptureResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } }
crates/api_models/src/events/payment.rs
api_models::src::events::payment
3,919
true
// File: crates/api_models/src/events/recon.rs // Module: api_models::src::events::recon use common_utils::events::{ApiEventMetric, ApiEventsType}; use masking::PeekInterface; use crate::recon::{ ReconStatusResponse, ReconTokenResponse, ReconUpdateMerchantRequest, VerifyTokenResponse, }; impl ApiEventMetric for ReconUpdateMerchantRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Recon) } } impl ApiEventMetric for ReconTokenResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Recon) } } impl ApiEventMetric for ReconStatusResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Recon) } } impl ApiEventMetric for VerifyTokenResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::User { user_id: self.user_email.peek().to_string(), }) } }
crates/api_models/src/events/recon.rs
api_models::src::events::recon
237
true
// File: crates/api_models/src/events/customer.rs // Module: api_models::src::events::customer use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::customers::{ CustomerDeleteResponse, CustomerListRequestWithConstraints, CustomerListResponse, CustomerRequest, CustomerResponse, CustomerUpdateRequestInternal, }; #[cfg(feature = "v1")] impl ApiEventMetric for CustomerDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: self.customer_id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for CustomerDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: Some(self.id.clone()), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for CustomerRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { self.get_merchant_reference_id() .clone() .map(|cid| ApiEventsType::Customer { customer_id: cid }) } } #[cfg(feature = "v2")] impl ApiEventMetric for CustomerRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: None }) } } #[cfg(feature = "v1")] impl ApiEventMetric for CustomerResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { self.get_merchant_reference_id() .clone() .map(|cid| ApiEventsType::Customer { customer_id: cid }) } } #[cfg(feature = "v2")] impl ApiEventMetric for CustomerResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: Some(self.id.clone()), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for CustomerUpdateRequestInternal { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: self.customer_id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for CustomerUpdateRequestInternal { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: Some(self.id.clone()), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for CustomerListRequestWithConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: self.customer_id.clone()?, }) } } #[cfg(feature = "v2")] impl ApiEventMetric for CustomerListRequestWithConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: None }) } } #[cfg(feature = "v1")] impl ApiEventMetric for CustomerListResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } #[cfg(feature = "v2")] impl ApiEventMetric for CustomerListResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } }
crates/api_models/src/events/customer.rs
api_models::src::events::customer
735
true
// File: crates/api_models/src/events/gsm.rs // Module: api_models::src::events::gsm use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::gsm; impl ApiEventMetric for gsm::GsmCreateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } } impl ApiEventMetric for gsm::GsmUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } } impl ApiEventMetric for gsm::GsmRetrieveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } } impl ApiEventMetric for gsm::GsmDeleteRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } } impl ApiEventMetric for gsm::GsmDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } } impl ApiEventMetric for gsm::GsmResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } }
crates/api_models/src/events/gsm.rs
api_models::src::events::gsm
296
true
// File: crates/api_models/src/events/revenue_recovery.rs // Module: api_models::src::events::revenue_recovery use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::process_tracker::revenue_recovery::{ RevenueRecoveryId, RevenueRecoveryResponse, RevenueRecoveryRetriggerRequest, }; impl ApiEventMetric for RevenueRecoveryResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ProcessTracker) } } impl ApiEventMetric for RevenueRecoveryId { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ProcessTracker) } } impl ApiEventMetric for RevenueRecoveryRetriggerRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ProcessTracker) } }
crates/api_models/src/events/revenue_recovery.rs
api_models::src::events::revenue_recovery
191
true
// File: crates/api_models/src/events/routing.rs // Module: api_models::src::events::routing use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::routing::{ ContractBasedRoutingPayloadWrapper, ContractBasedRoutingSetupPayloadWrapper, CreateDynamicRoutingWrapper, DynamicRoutingUpdateConfigQuery, EliminationRoutingPayloadWrapper, LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig, RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind, RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery, RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplit, RoutingVolumeSplitResponse, RoutingVolumeSplitWrapper, RuleMigrationError, RuleMigrationQuery, RuleMigrationResponse, RuleMigrationResult, SuccessBasedRoutingConfig, SuccessBasedRoutingPayloadWrapper, ToggleDynamicRoutingPath, ToggleDynamicRoutingQuery, ToggleDynamicRoutingWrapper, }; impl ApiEventMetric for RoutingKind { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for MerchantRoutingAlgorithm { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingAlgorithmId { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingDictionaryRecord { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for LinkedRoutingConfigRetrieveResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingPayloadWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for ProfileDefaultRoutingConfig { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingRetrieveQuery { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingConfigRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingRetrieveLinkQuery { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingLinkWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingRetrieveLinkQueryWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for ToggleDynamicRoutingQuery { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for SuccessBasedRoutingConfig { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for SuccessBasedRoutingPayloadWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for EliminationRoutingPayloadWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for ContractBasedRoutingPayloadWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for ContractBasedRoutingSetupPayloadWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for ToggleDynamicRoutingWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for CreateDynamicRoutingWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for DynamicRoutingUpdateConfigQuery { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingVolumeSplitWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for ToggleDynamicRoutingPath { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingVolumeSplitResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingVolumeSplit { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RuleMigrationQuery { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RuleMigrationResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RuleMigrationResult { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RuleMigrationError { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for crate::open_router::DecideGatewayResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for crate::open_router::OpenRouterDecideGatewayRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for crate::open_router::UpdateScorePayload { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for crate::open_router::UpdateScoreResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } }
crates/api_models/src/events/routing.rs
api_models::src::events::routing
1,461
true
// File: crates/api_models/src/events/apple_pay_certificates_migration.rs // Module: api_models::src::events::apple_pay_certificates_migration use common_utils::events::ApiEventMetric; use crate::apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse; impl ApiEventMetric for ApplePayCertificatesMigrationResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::ApplePayCertificatesMigration) } }
crates/api_models/src/events/apple_pay_certificates_migration.rs
api_models::src::events::apple_pay_certificates_migration
108
true
// File: crates/api_models/src/events/connector_onboarding.rs // Module: api_models::src::events::connector_onboarding use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::connector_onboarding::{ ActionUrlRequest, ActionUrlResponse, OnboardingStatus, OnboardingSyncRequest, ResetTrackingIdRequest, }; common_utils::impl_api_event_type!( Miscellaneous, ( ActionUrlRequest, ActionUrlResponse, OnboardingSyncRequest, OnboardingStatus, ResetTrackingIdRequest ) );
crates/api_models/src/events/connector_onboarding.rs
api_models::src::events::connector_onboarding
117
true
// File: crates/api_models/src/events/chat.rs // Module: api_models::src::events::chat use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::chat::{ChatListRequest, ChatListResponse, ChatRequest, ChatResponse}; common_utils::impl_api_event_type!( Chat, (ChatRequest, ChatResponse, ChatListRequest, ChatListResponse) );
crates/api_models/src/events/chat.rs
api_models::src::events::chat
84
true
// File: crates/api_models/src/analytics/payment_intents.rs // Module: api_models::src::analytics::payment_intents use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use common_utils::id_type; use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::{ AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType, }; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct PaymentIntentFilters { #[serde(default)] pub status: Vec<IntentStatus>, #[serde(default)] pub currency: Vec<Currency>, #[serde(default)] pub profile_id: Vec<id_type::ProfileId>, #[serde(default)] pub connector: Vec<Connector>, #[serde(default)] pub auth_type: Vec<AuthenticationType>, #[serde(default)] pub payment_method: Vec<PaymentMethod>, #[serde(default)] pub payment_method_type: Vec<PaymentMethodType>, #[serde(default)] pub card_network: Vec<String>, #[serde(default)] pub merchant_id: Vec<id_type::MerchantId>, #[serde(default)] pub card_last_4: Vec<String>, #[serde(default)] pub card_issuer: Vec<String>, #[serde(default)] pub error_reason: Vec<String>, #[serde(default)] pub customer_id: Vec<id_type::CustomerId>, } #[derive( Debug, serde::Serialize, serde::Deserialize, strum::AsRefStr, PartialEq, PartialOrd, Eq, Ord, strum::Display, strum::EnumIter, Clone, Copy, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentIntentDimensions { #[strum(serialize = "status")] #[serde(rename = "status")] PaymentIntentStatus, Currency, ProfileId, Connector, #[strum(serialize = "authentication_type")] #[serde(rename = "authentication_type")] AuthType, PaymentMethod, PaymentMethodType, CardNetwork, MerchantId, #[strum(serialize = "card_last_4")] #[serde(rename = "card_last_4")] CardLast4, CardIssuer, ErrorReason, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentIntentMetrics { SuccessfulSmartRetries, TotalSmartRetries, SmartRetriedAmount, PaymentIntentCount, PaymentsSuccessRate, PaymentProcessedAmount, SessionizedSuccessfulSmartRetries, SessionizedTotalSmartRetries, SessionizedSmartRetriedAmount, SessionizedPaymentIntentCount, SessionizedPaymentsSuccessRate, SessionizedPaymentProcessedAmount, SessionizedPaymentsDistribution, } impl ForexMetric for PaymentIntentMetrics { fn is_forex_metric(&self) -> bool { matches!( self, Self::PaymentProcessedAmount | Self::SmartRetriedAmount | Self::SessionizedPaymentProcessedAmount | Self::SessionizedSmartRetriedAmount ) } } #[derive(Debug, Default, serde::Serialize)] pub struct ErrorResult { pub reason: String, pub count: i64, pub percentage: f64, } pub mod metric_behaviour { pub struct SuccessfulSmartRetries; pub struct TotalSmartRetries; pub struct SmartRetriedAmount; pub struct PaymentIntentCount; pub struct PaymentsSuccessRate; } impl From<PaymentIntentMetrics> for NameDescription { fn from(value: PaymentIntentMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } impl From<PaymentIntentDimensions> for NameDescription { fn from(value: PaymentIntentDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Debug, serde::Serialize, Eq)] pub struct PaymentIntentMetricsBucketIdentifier { pub status: Option<IntentStatus>, pub currency: Option<Currency>, pub profile_id: Option<String>, pub connector: Option<String>, pub auth_type: Option<AuthenticationType>, pub payment_method: Option<String>, pub payment_method_type: Option<String>, pub card_network: Option<String>, pub merchant_id: Option<String>, pub card_last_4: Option<String>, pub card_issuer: Option<String>, pub error_reason: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] #[serde(with = "common_utils::custom_serde::iso8601custom")] pub start_time: time::PrimitiveDateTime, } impl PaymentIntentMetricsBucketIdentifier { #[allow(clippy::too_many_arguments)] pub fn new( status: Option<IntentStatus>, currency: Option<Currency>, profile_id: Option<String>, connector: Option<String>, auth_type: Option<AuthenticationType>, payment_method: Option<String>, payment_method_type: Option<String>, card_network: Option<String>, merchant_id: Option<String>, card_last_4: Option<String>, card_issuer: Option<String>, error_reason: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { status, currency, profile_id, connector, auth_type, payment_method, payment_method_type, card_network, merchant_id, card_last_4, card_issuer, error_reason, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } } impl Hash for PaymentIntentMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.status.map(|i| i.to_string()).hash(state); self.currency.hash(state); self.profile_id.hash(state); self.connector.hash(state); self.auth_type.map(|i| i.to_string()).hash(state); self.payment_method.hash(state); self.payment_method_type.hash(state); self.card_network.hash(state); self.merchant_id.hash(state); self.card_last_4.hash(state); self.card_issuer.hash(state); self.error_reason.hash(state); self.time_bucket.hash(state); } } impl PartialEq for PaymentIntentMetricsBucketIdentifier { fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } } #[derive(Debug, serde::Serialize)] pub struct PaymentIntentMetricsBucketValue { pub successful_smart_retries: Option<u64>, pub total_smart_retries: Option<u64>, pub smart_retried_amount: Option<u64>, pub smart_retried_amount_in_usd: Option<u64>, pub smart_retried_amount_without_smart_retries: Option<u64>, pub smart_retried_amount_without_smart_retries_in_usd: Option<u64>, pub payment_intent_count: Option<u64>, pub successful_payments: Option<u32>, pub successful_payments_without_smart_retries: Option<u32>, pub total_payments: Option<u32>, pub payments_success_rate: Option<f64>, pub payments_success_rate_without_smart_retries: Option<f64>, pub payment_processed_amount: Option<u64>, pub payment_processed_amount_in_usd: Option<u64>, pub payment_processed_count: Option<u64>, pub payment_processed_amount_without_smart_retries: Option<u64>, pub payment_processed_amount_without_smart_retries_in_usd: Option<u64>, pub payment_processed_count_without_smart_retries: Option<u64>, pub payments_success_rate_distribution_without_smart_retries: Option<f64>, pub payments_failure_rate_distribution_without_smart_retries: Option<f64>, } #[derive(Debug, serde::Serialize)] pub struct MetricsBucketResponse { #[serde(flatten)] pub values: PaymentIntentMetricsBucketValue, #[serde(flatten)] pub dimensions: PaymentIntentMetricsBucketIdentifier, }
crates/api_models/src/analytics/payment_intents.rs
api_models::src::analytics::payment_intents
1,835
true
// File: crates/api_models/src/analytics/api_event.rs // Module: api_models::src::analytics::api_event use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use super::{NameDescription, TimeRange}; #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ApiLogsRequest { #[serde(flatten)] pub query_param: QueryType, } pub enum FilterType { ApiCountFilter, LatencyFilter, StatusCodeFilter, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(tag = "type")] pub enum QueryType { Payment { payment_id: common_utils::id_type::PaymentId, }, Refund { payment_id: common_utils::id_type::PaymentId, refund_id: String, }, Dispute { payment_id: common_utils::id_type::PaymentId, dispute_id: String, }, } #[derive( Debug, serde::Serialize, serde::Deserialize, strum::AsRefStr, PartialEq, PartialOrd, Eq, Ord, strum::Display, strum::EnumIter, Clone, Copy, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum ApiEventDimensions { // Do not change the order of these enums // Consult the Dashboard FE folks since these also affects the order of metrics on FE StatusCode, FlowType, ApiFlow, } impl From<ApiEventDimensions> for NameDescription { fn from(value: ApiEventDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct ApiEventFilters { pub status_code: Vec<u64>, pub flow_type: Vec<String>, pub api_flow: Vec<String>, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ApiEventMetrics { Latency, ApiCount, StatusCodeCount, } impl From<ApiEventMetrics> for NameDescription { fn from(value: ApiEventMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Debug, serde::Serialize, Eq)] pub struct ApiEventMetricsBucketIdentifier { #[serde(rename = "time_range")] pub time_bucket: TimeRange, // Coz FE sucks #[serde(rename = "time_bucket")] #[serde(with = "common_utils::custom_serde::iso8601custom")] pub start_time: time::PrimitiveDateTime, } impl ApiEventMetricsBucketIdentifier { pub fn new(normalized_time_range: TimeRange) -> Self { Self { time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } } impl Hash for ApiEventMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.time_bucket.hash(state); } } impl PartialEq for ApiEventMetricsBucketIdentifier { fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } } #[derive(Debug, serde::Serialize)] pub struct ApiEventMetricsBucketValue { pub latency: Option<u64>, pub api_count: Option<u64>, pub status_code_count: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct ApiMetricsBucketResponse { #[serde(flatten)] pub values: ApiEventMetricsBucketValue, #[serde(flatten)] pub dimensions: ApiEventMetricsBucketIdentifier, }
crates/api_models/src/analytics/api_event.rs
api_models::src::analytics::api_event
890
true
// File: crates/api_models/src/analytics/outgoing_webhook_event.rs // Module: api_models::src::analytics::outgoing_webhook_event #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct OutgoingWebhookLogsRequest { pub payment_id: common_utils::id_type::PaymentId, pub event_id: Option<String>, pub refund_id: Option<String>, pub dispute_id: Option<String>, pub mandate_id: Option<String>, pub payment_method_id: Option<String>, pub attempt_id: Option<String>, }
crates/api_models/src/analytics/outgoing_webhook_event.rs
api_models::src::analytics::outgoing_webhook_event
119
true
// File: crates/api_models/src/analytics/refunds.rs // Module: api_models::src::analytics::refunds use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use common_utils::id_type; use crate::enums::{Currency, RefundStatus}; #[derive( Clone, Copy, Debug, Hash, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] // TODO RefundType api_models_oss need to mapped to storage_model #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RefundType { InstantRefund, RegularRefund, RetryRefund, } use super::{ForexMetric, NameDescription, TimeRange}; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct RefundFilters { #[serde(default)] pub currency: Vec<Currency>, #[serde(default)] pub refund_status: Vec<RefundStatus>, #[serde(default)] pub connector: Vec<String>, #[serde(default)] pub refund_type: Vec<RefundType>, #[serde(default)] pub profile_id: Vec<id_type::ProfileId>, #[serde(default)] pub refund_reason: Vec<String>, #[serde(default)] pub refund_error_message: Vec<String>, } #[derive( Debug, serde::Serialize, serde::Deserialize, strum::AsRefStr, PartialEq, PartialOrd, Eq, Ord, strum::Display, strum::EnumIter, Clone, Copy, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RefundDimensions { Currency, RefundStatus, Connector, RefundType, ProfileId, RefundReason, RefundErrorMessage, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundMetrics { RefundSuccessRate, RefundCount, RefundSuccessCount, RefundProcessedAmount, SessionizedRefundSuccessRate, SessionizedRefundCount, SessionizedRefundSuccessCount, SessionizedRefundProcessedAmount, SessionizedRefundReason, SessionizedRefundErrorMessage, } #[derive(Debug, Default, serde::Serialize)] pub struct ReasonsResult { pub reason: String, pub count: i64, pub percentage: f64, } #[derive(Debug, Default, serde::Serialize)] pub struct ErrorMessagesResult { pub error_message: String, pub count: i64, pub percentage: f64, } #[derive( Clone, Copy, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum RefundDistributions { #[strum(serialize = "refund_reason")] SessionizedRefundReason, #[strum(serialize = "refund_error_message")] SessionizedRefundErrorMessage, } impl ForexMetric for RefundMetrics { fn is_forex_metric(&self) -> bool { matches!( self, Self::RefundProcessedAmount | Self::SessionizedRefundProcessedAmount ) } } pub mod metric_behaviour { pub struct RefundSuccessRate; pub struct RefundCount; pub struct RefundSuccessCount; pub struct RefundProcessedAmount; } impl From<RefundMetrics> for NameDescription { fn from(value: RefundMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } impl From<RefundDimensions> for NameDescription { fn from(value: RefundDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Debug, serde::Serialize, Eq)] pub struct RefundMetricsBucketIdentifier { pub currency: Option<Currency>, pub refund_status: Option<String>, pub connector: Option<String>, pub refund_type: Option<String>, pub profile_id: Option<String>, pub refund_reason: Option<String>, pub refund_error_message: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] #[serde(with = "common_utils::custom_serde::iso8601custom")] pub start_time: time::PrimitiveDateTime, } impl Hash for RefundMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.currency.hash(state); self.refund_status.hash(state); self.connector.hash(state); self.refund_type.hash(state); self.profile_id.hash(state); self.refund_reason.hash(state); self.refund_error_message.hash(state); self.time_bucket.hash(state); } } impl PartialEq for RefundMetricsBucketIdentifier { fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } } impl RefundMetricsBucketIdentifier { #[allow(clippy::too_many_arguments)] pub fn new( currency: Option<Currency>, refund_status: Option<String>, connector: Option<String>, refund_type: Option<String>, profile_id: Option<String>, refund_reason: Option<String>, refund_error_message: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { currency, refund_status, connector, refund_type, profile_id, refund_reason, refund_error_message, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } } #[derive(Debug, serde::Serialize)] pub struct RefundMetricsBucketValue { pub successful_refunds: Option<u32>, pub total_refunds: Option<u32>, pub refund_success_rate: Option<f64>, pub refund_count: Option<u64>, pub refund_success_count: Option<u64>, pub refund_processed_amount: Option<u64>, pub refund_processed_amount_in_usd: Option<u64>, pub refund_processed_count: Option<u64>, pub refund_reason_distribution: Option<Vec<ReasonsResult>>, pub refund_error_message_distribution: Option<Vec<ErrorMessagesResult>>, pub refund_reason_count: Option<u64>, pub refund_error_message_count: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct RefundMetricsBucketResponse { #[serde(flatten)] pub values: RefundMetricsBucketValue, #[serde(flatten)] pub dimensions: RefundMetricsBucketIdentifier, }
crates/api_models/src/analytics/refunds.rs
api_models::src::analytics::refunds
1,570
true
// File: crates/api_models/src/analytics/payments.rs // Module: api_models::src::analytics::payments use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use common_utils::id_type; use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::{ AttemptStatus, AuthenticationType, CardNetwork, Connector, Currency, PaymentMethod, PaymentMethodType, RoutingApproach, }; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct PaymentFilters { #[serde(default)] pub currency: Vec<Currency>, #[serde(default)] pub status: Vec<AttemptStatus>, #[serde(default)] pub connector: Vec<Connector>, #[serde(default)] pub auth_type: Vec<AuthenticationType>, #[serde(default)] pub payment_method: Vec<PaymentMethod>, #[serde(default)] pub payment_method_type: Vec<PaymentMethodType>, #[serde(default)] pub client_source: Vec<String>, #[serde(default)] pub client_version: Vec<String>, #[serde(default)] pub card_network: Vec<CardNetwork>, #[serde(default)] pub profile_id: Vec<id_type::ProfileId>, #[serde(default)] pub merchant_id: Vec<id_type::MerchantId>, #[serde(default)] pub card_last_4: Vec<String>, #[serde(default)] pub card_issuer: Vec<String>, #[serde(default)] pub error_reason: Vec<String>, #[serde(default)] pub first_attempt: Vec<bool>, #[serde(default)] pub routing_approach: Vec<RoutingApproach>, #[serde(default)] pub signature_network: Vec<String>, #[serde(default)] pub is_issuer_regulated: Vec<bool>, #[serde(default)] pub is_debit_routed: Vec<bool>, } #[derive( Debug, serde::Serialize, serde::Deserialize, strum::AsRefStr, PartialEq, PartialOrd, Eq, Ord, strum::Display, strum::EnumIter, Clone, Copy, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PaymentDimensions { // Do not change the order of these enums // Consult the Dashboard FE folks since these also affects the order of metrics on FE Connector, PaymentMethod, PaymentMethodType, Currency, #[strum(serialize = "authentication_type")] #[serde(rename = "authentication_type")] AuthType, #[strum(serialize = "status")] #[serde(rename = "status")] PaymentStatus, ClientSource, ClientVersion, ProfileId, CardNetwork, MerchantId, #[strum(serialize = "card_last_4")] #[serde(rename = "card_last_4")] CardLast4, CardIssuer, ErrorReason, RoutingApproach, SignatureNetwork, IsIssuerRegulated, IsDebitRouted, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentMetrics { PaymentSuccessRate, PaymentCount, PaymentSuccessCount, PaymentProcessedAmount, AvgTicketSize, RetriesCount, ConnectorSuccessRate, DebitRouting, SessionizedPaymentSuccessRate, SessionizedPaymentCount, SessionizedPaymentSuccessCount, SessionizedPaymentProcessedAmount, SessionizedAvgTicketSize, SessionizedRetriesCount, SessionizedConnectorSuccessRate, SessionizedDebitRouting, PaymentsDistribution, FailureReasons, } impl ForexMetric for PaymentMetrics { fn is_forex_metric(&self) -> bool { matches!( self, Self::PaymentProcessedAmount | Self::AvgTicketSize | Self::DebitRouting | Self::SessionizedPaymentProcessedAmount | Self::SessionizedAvgTicketSize | Self::SessionizedDebitRouting, ) } } #[derive(Debug, Default, serde::Serialize)] pub struct ErrorResult { pub reason: String, pub count: i64, pub percentage: f64, } #[derive( Clone, Copy, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PaymentDistributions { #[strum(serialize = "error_message")] PaymentErrorMessage, } pub mod metric_behaviour { pub struct PaymentSuccessRate; pub struct PaymentCount; pub struct PaymentSuccessCount; pub struct PaymentProcessedAmount; pub struct AvgTicketSize; } impl From<PaymentMetrics> for NameDescription { fn from(value: PaymentMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } impl From<PaymentDimensions> for NameDescription { fn from(value: PaymentDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Debug, serde::Serialize, Eq)] pub struct PaymentMetricsBucketIdentifier { pub currency: Option<Currency>, pub status: Option<AttemptStatus>, pub connector: Option<String>, #[serde(rename = "authentication_type")] pub auth_type: Option<AuthenticationType>, pub payment_method: Option<String>, pub payment_method_type: Option<String>, pub client_source: Option<String>, pub client_version: Option<String>, pub profile_id: Option<String>, pub card_network: Option<String>, pub merchant_id: Option<String>, pub card_last_4: Option<String>, pub card_issuer: Option<String>, pub error_reason: Option<String>, pub routing_approach: Option<RoutingApproach>, pub signature_network: Option<String>, pub is_issuer_regulated: Option<bool>, pub is_debit_routed: Option<bool>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, // Coz FE sucks #[serde(rename = "time_bucket")] #[serde(with = "common_utils::custom_serde::iso8601custom")] pub start_time: time::PrimitiveDateTime, } impl PaymentMetricsBucketIdentifier { #[allow(clippy::too_many_arguments)] pub fn new( currency: Option<Currency>, status: Option<AttemptStatus>, connector: Option<String>, auth_type: Option<AuthenticationType>, payment_method: Option<String>, payment_method_type: Option<String>, client_source: Option<String>, client_version: Option<String>, profile_id: Option<String>, card_network: Option<String>, merchant_id: Option<String>, card_last_4: Option<String>, card_issuer: Option<String>, error_reason: Option<String>, routing_approach: Option<RoutingApproach>, signature_network: Option<String>, is_issuer_regulated: Option<bool>, is_debit_routed: Option<bool>, normalized_time_range: TimeRange, ) -> Self { Self { currency, status, connector, auth_type, payment_method, payment_method_type, client_source, client_version, profile_id, card_network, merchant_id, card_last_4, card_issuer, error_reason, routing_approach, signature_network, is_issuer_regulated, is_debit_routed, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } } impl Hash for PaymentMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.currency.hash(state); self.status.map(|i| i.to_string()).hash(state); self.connector.hash(state); self.auth_type.map(|i| i.to_string()).hash(state); self.payment_method.hash(state); self.payment_method_type.hash(state); self.client_source.hash(state); self.client_version.hash(state); self.profile_id.hash(state); self.card_network.hash(state); self.merchant_id.hash(state); self.card_last_4.hash(state); self.card_issuer.hash(state); self.error_reason.hash(state); self.routing_approach .clone() .map(|i| i.to_string()) .hash(state); self.signature_network.hash(state); self.is_issuer_regulated.hash(state); self.is_debit_routed.hash(state); self.time_bucket.hash(state); } } impl PartialEq for PaymentMetricsBucketIdentifier { fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } } #[derive(Debug, serde::Serialize)] pub struct PaymentMetricsBucketValue { pub payment_success_rate: Option<f64>, pub payment_count: Option<u64>, pub payment_success_count: Option<u64>, pub payment_processed_amount: Option<u64>, pub payment_processed_amount_in_usd: Option<u64>, pub payment_processed_count: Option<u64>, pub payment_processed_amount_without_smart_retries: Option<u64>, pub payment_processed_amount_without_smart_retries_usd: Option<u64>, pub payment_processed_count_without_smart_retries: Option<u64>, pub avg_ticket_size: Option<f64>, pub payment_error_message: Option<Vec<ErrorResult>>, pub retries_count: Option<u64>, pub retries_amount_processed: Option<u64>, pub connector_success_rate: Option<f64>, pub payments_success_rate_distribution: Option<f64>, pub payments_success_rate_distribution_without_smart_retries: Option<f64>, pub payments_success_rate_distribution_with_only_retries: Option<f64>, pub payments_failure_rate_distribution: Option<f64>, pub payments_failure_rate_distribution_without_smart_retries: Option<f64>, pub payments_failure_rate_distribution_with_only_retries: Option<f64>, pub failure_reason_count: Option<u64>, pub failure_reason_count_without_smart_retries: Option<u64>, pub debit_routed_transaction_count: Option<u64>, pub debit_routing_savings: Option<u64>, pub debit_routing_savings_in_usd: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct MetricsBucketResponse { #[serde(flatten)] pub values: PaymentMetricsBucketValue, #[serde(flatten)] pub dimensions: PaymentMetricsBucketIdentifier, }
crates/api_models/src/analytics/payments.rs
api_models::src::analytics::payments
2,364
true
// File: crates/api_models/src/analytics/auth_events.rs // Module: api_models::src::analytics::auth_events use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use common_enums::{ AuthenticationConnectors, AuthenticationStatus, Currency, DecoupledAuthenticationType, TransactionStatus, }; use super::{NameDescription, TimeRange}; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct AuthEventFilters { #[serde(default)] pub authentication_status: Vec<AuthenticationStatus>, #[serde(default)] pub trans_status: Vec<TransactionStatus>, #[serde(default)] pub authentication_type: Vec<DecoupledAuthenticationType>, #[serde(default)] pub error_message: Vec<String>, #[serde(default)] pub authentication_connector: Vec<AuthenticationConnectors>, #[serde(default)] pub message_version: Vec<String>, #[serde(default)] pub platform: Vec<String>, #[serde(default)] pub acs_reference_number: Vec<String>, #[serde(default)] pub mcc: Vec<String>, #[serde(default)] pub currency: Vec<Currency>, #[serde(default)] pub merchant_country: Vec<String>, #[serde(default)] pub billing_country: Vec<String>, #[serde(default)] pub shipping_country: Vec<String>, #[serde(default)] pub issuer_country: Vec<String>, #[serde(default)] pub earliest_supported_version: Vec<String>, #[serde(default)] pub latest_supported_version: Vec<String>, #[serde(default)] pub whitelist_decision: Vec<bool>, #[serde(default)] pub device_manufacturer: Vec<String>, #[serde(default)] pub device_type: Vec<String>, #[serde(default)] pub device_brand: Vec<String>, #[serde(default)] pub device_os: Vec<String>, #[serde(default)] pub device_display: Vec<String>, #[serde(default)] pub browser_name: Vec<String>, #[serde(default)] pub browser_version: Vec<String>, #[serde(default)] pub issuer_id: Vec<String>, #[serde(default)] pub scheme_name: Vec<String>, #[serde(default)] pub exemption_requested: Vec<bool>, #[serde(default)] pub exemption_accepted: Vec<bool>, } #[derive( Debug, serde::Serialize, serde::Deserialize, strum::AsRefStr, PartialEq, PartialOrd, Eq, Ord, strum::Display, strum::EnumIter, Clone, Copy, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum AuthEventDimensions { AuthenticationStatus, #[strum(serialize = "trans_status")] #[serde(rename = "trans_status")] TransactionStatus, AuthenticationType, ErrorMessage, AuthenticationConnector, MessageVersion, AcsReferenceNumber, Platform, Mcc, Currency, MerchantCountry, BillingCountry, ShippingCountry, IssuerCountry, EarliestSupportedVersion, LatestSupportedVersion, WhitelistDecision, DeviceManufacturer, DeviceType, DeviceBrand, DeviceOs, DeviceDisplay, BrowserName, BrowserVersion, IssuerId, SchemeName, ExemptionRequested, ExemptionAccepted, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum AuthEventMetrics { AuthenticationCount, AuthenticationAttemptCount, AuthenticationSuccessCount, ChallengeFlowCount, FrictionlessFlowCount, FrictionlessSuccessCount, ChallengeAttemptCount, ChallengeSuccessCount, AuthenticationErrorMessage, AuthenticationFunnel, AuthenticationExemptionApprovedCount, AuthenticationExemptionRequestedCount, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] pub enum AuthEventFlows { IncomingWebhookReceive, PaymentsExternalAuthentication, } pub mod metric_behaviour { pub struct AuthenticationCount; pub struct AuthenticationAttemptCount; pub struct AuthenticationSuccessCount; pub struct ChallengeFlowCount; pub struct FrictionlessFlowCount; pub struct FrictionlessSuccessCount; pub struct ChallengeAttemptCount; pub struct ChallengeSuccessCount; pub struct AuthenticationErrorMessage; pub struct AuthenticationFunnel; } impl From<AuthEventMetrics> for NameDescription { fn from(value: AuthEventMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } impl From<AuthEventDimensions> for NameDescription { fn from(value: AuthEventDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Debug, serde::Serialize, Eq)] pub struct AuthEventMetricsBucketIdentifier { pub authentication_status: Option<AuthenticationStatus>, pub trans_status: Option<TransactionStatus>, pub authentication_type: Option<DecoupledAuthenticationType>, pub error_message: Option<String>, pub authentication_connector: Option<AuthenticationConnectors>, pub message_version: Option<String>, pub acs_reference_number: Option<String>, pub mcc: Option<String>, pub currency: Option<Currency>, pub merchant_country: Option<String>, pub billing_country: Option<String>, pub shipping_country: Option<String>, pub issuer_country: Option<String>, pub earliest_supported_version: Option<String>, pub latest_supported_version: Option<String>, pub whitelist_decision: Option<bool>, pub device_manufacturer: Option<String>, pub device_type: Option<String>, pub device_brand: Option<String>, pub device_os: Option<String>, pub device_display: Option<String>, pub browser_name: Option<String>, pub browser_version: Option<String>, pub issuer_id: Option<String>, pub scheme_name: Option<String>, pub exemption_requested: Option<bool>, pub exemption_accepted: Option<bool>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] #[serde(with = "common_utils::custom_serde::iso8601custom")] pub start_time: time::PrimitiveDateTime, } impl AuthEventMetricsBucketIdentifier { #[allow(clippy::too_many_arguments)] pub fn new( authentication_status: Option<AuthenticationStatus>, trans_status: Option<TransactionStatus>, authentication_type: Option<DecoupledAuthenticationType>, error_message: Option<String>, authentication_connector: Option<AuthenticationConnectors>, message_version: Option<String>, acs_reference_number: Option<String>, mcc: Option<String>, currency: Option<Currency>, merchant_country: Option<String>, billing_country: Option<String>, shipping_country: Option<String>, issuer_country: Option<String>, earliest_supported_version: Option<String>, latest_supported_version: Option<String>, whitelist_decision: Option<bool>, device_manufacturer: Option<String>, device_type: Option<String>, device_brand: Option<String>, device_os: Option<String>, device_display: Option<String>, browser_name: Option<String>, browser_version: Option<String>, issuer_id: Option<String>, scheme_name: Option<String>, exemption_requested: Option<bool>, exemption_accepted: Option<bool>, normalized_time_range: TimeRange, ) -> Self { Self { authentication_status, trans_status, authentication_type, error_message, authentication_connector, message_version, acs_reference_number, mcc, currency, merchant_country, billing_country, shipping_country, issuer_country, earliest_supported_version, latest_supported_version, whitelist_decision, device_manufacturer, device_type, device_brand, device_os, device_display, browser_name, browser_version, issuer_id, scheme_name, exemption_requested, exemption_accepted, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } } impl Hash for AuthEventMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.authentication_status.hash(state); self.trans_status.hash(state); self.authentication_type.hash(state); self.authentication_connector.hash(state); self.message_version.hash(state); self.acs_reference_number.hash(state); self.error_message.hash(state); self.mcc.hash(state); self.currency.hash(state); self.merchant_country.hash(state); self.billing_country.hash(state); self.shipping_country.hash(state); self.issuer_country.hash(state); self.earliest_supported_version.hash(state); self.latest_supported_version.hash(state); self.whitelist_decision.hash(state); self.device_manufacturer.hash(state); self.device_type.hash(state); self.device_brand.hash(state); self.device_os.hash(state); self.device_display.hash(state); self.browser_name.hash(state); self.browser_version.hash(state); self.issuer_id.hash(state); self.scheme_name.hash(state); self.exemption_requested.hash(state); self.exemption_accepted.hash(state); self.time_bucket.hash(state); } } impl PartialEq for AuthEventMetricsBucketIdentifier { fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } } #[derive(Debug, serde::Serialize)] pub struct AuthEventMetricsBucketValue { pub authentication_count: Option<u64>, pub authentication_attempt_count: Option<u64>, pub authentication_success_count: Option<u64>, pub challenge_flow_count: Option<u64>, pub challenge_attempt_count: Option<u64>, pub challenge_success_count: Option<u64>, pub frictionless_flow_count: Option<u64>, pub frictionless_success_count: Option<u64>, pub error_message_count: Option<u64>, pub authentication_funnel: Option<u64>, pub authentication_exemption_approved_count: Option<u64>, pub authentication_exemption_requested_count: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct MetricsBucketResponse { #[serde(flatten)] pub values: AuthEventMetricsBucketValue, #[serde(flatten)] pub dimensions: AuthEventMetricsBucketIdentifier, }
crates/api_models/src/analytics/auth_events.rs
api_models::src::analytics::auth_events
2,280
true
// File: crates/api_models/src/analytics/disputes.rs // Module: api_models::src::analytics::disputes use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::{Currency, DisputeStage}; #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum DisputeMetrics { DisputeStatusMetric, TotalAmountDisputed, TotalDisputeLostAmount, SessionizedDisputeStatusMetric, SessionizedTotalAmountDisputed, SessionizedTotalDisputeLostAmount, } impl ForexMetric for DisputeMetrics { fn is_forex_metric(&self) -> bool { matches!( self, Self::TotalAmountDisputed | Self::TotalDisputeLostAmount ) } } #[derive( Debug, serde::Serialize, serde::Deserialize, strum::AsRefStr, PartialEq, PartialOrd, Eq, Ord, strum::Display, strum::EnumIter, Clone, Copy, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum DisputeDimensions { // Do not change the order of these enums // Consult the Dashboard FE folks since these also affects the order of metrics on FE Connector, DisputeStage, Currency, } impl From<DisputeDimensions> for NameDescription { fn from(value: DisputeDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } } impl From<DisputeMetrics> for NameDescription { fn from(value: DisputeMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct DisputeFilters { #[serde(default)] pub dispute_stage: Vec<DisputeStage>, #[serde(default)] pub connector: Vec<String>, #[serde(default)] pub currency: Vec<Currency>, } #[derive(Debug, serde::Serialize, Eq)] pub struct DisputeMetricsBucketIdentifier { pub dispute_stage: Option<DisputeStage>, pub connector: Option<String>, pub currency: Option<Currency>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] #[serde(with = "common_utils::custom_serde::iso8601custom")] pub start_time: time::PrimitiveDateTime, } impl Hash for DisputeMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.dispute_stage.hash(state); self.connector.hash(state); self.currency.hash(state); self.time_bucket.hash(state); } } impl PartialEq for DisputeMetricsBucketIdentifier { fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } } impl DisputeMetricsBucketIdentifier { pub fn new( dispute_stage: Option<DisputeStage>, connector: Option<String>, currency: Option<Currency>, normalized_time_range: TimeRange, ) -> Self { Self { dispute_stage, connector, currency, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } } #[derive(Debug, serde::Serialize)] pub struct DisputeMetricsBucketValue { pub disputes_challenged: Option<u64>, pub disputes_won: Option<u64>, pub disputes_lost: Option<u64>, pub disputed_amount: Option<u64>, pub dispute_lost_amount: Option<u64>, pub total_dispute: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct DisputeMetricsBucketResponse { #[serde(flatten)] pub values: DisputeMetricsBucketValue, #[serde(flatten)] pub dimensions: DisputeMetricsBucketIdentifier, }
crates/api_models/src/analytics/disputes.rs
api_models::src::analytics::disputes
962
true
// File: crates/api_models/src/analytics/frm.rs // Module: api_models::src::analytics::frm use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use common_enums::enums::FraudCheckStatus; #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmTransactionType { #[default] PreFrm, PostFrm, } use super::{NameDescription, TimeRange}; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct FrmFilters { #[serde(default)] pub frm_status: Vec<FraudCheckStatus>, #[serde(default)] pub frm_name: Vec<String>, #[serde(default)] pub frm_transaction_type: Vec<FrmTransactionType>, } #[derive( Debug, serde::Serialize, serde::Deserialize, strum::AsRefStr, PartialEq, PartialOrd, Eq, Ord, strum::Display, strum::EnumIter, Clone, Copy, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmDimensions { FrmStatus, FrmName, FrmTransactionType, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FrmMetrics { FrmTriggeredAttempts, FrmBlockedRate, } pub mod metric_behaviour { pub struct FrmTriggeredAttempts; pub struct FrmBlockRate; } impl From<FrmMetrics> for NameDescription { fn from(value: FrmMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } impl From<FrmDimensions> for NameDescription { fn from(value: FrmDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Debug, serde::Serialize, Eq)] pub struct FrmMetricsBucketIdentifier { pub frm_status: Option<String>, pub frm_name: Option<String>, pub frm_transaction_type: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] #[serde(with = "common_utils::custom_serde::iso8601custom")] pub start_time: time::PrimitiveDateTime, } impl Hash for FrmMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.frm_status.hash(state); self.frm_name.hash(state); self.frm_transaction_type.hash(state); self.time_bucket.hash(state); } } impl PartialEq for FrmMetricsBucketIdentifier { fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } } impl FrmMetricsBucketIdentifier { pub fn new( frm_status: Option<String>, frm_name: Option<String>, frm_transaction_type: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { frm_status, frm_name, frm_transaction_type, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } } #[derive(Debug, serde::Serialize)] pub struct FrmMetricsBucketValue { pub frm_triggered_attempts: Option<u64>, pub frm_blocked_rate: Option<f64>, } #[derive(Debug, serde::Serialize)] pub struct FrmMetricsBucketResponse { #[serde(flatten)] pub values: FrmMetricsBucketValue, #[serde(flatten)] pub dimensions: FrmMetricsBucketIdentifier, }
crates/api_models/src/analytics/frm.rs
api_models::src::analytics::frm
910
true
// File: crates/api_models/src/analytics/routing_events.rs // Module: api_models::src::analytics::routing_events #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingEventsRequest { pub payment_id: common_utils::id_type::PaymentId, pub refund_id: Option<String>, pub dispute_id: Option<String>, }
crates/api_models/src/analytics/routing_events.rs
api_models::src::analytics::routing_events
78
true
// File: crates/api_models/src/analytics/connector_events.rs // Module: api_models::src::analytics::connector_events #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ConnectorEventsRequest { pub payment_id: common_utils::id_type::PaymentId, pub refund_id: Option<String>, pub dispute_id: Option<String>, }
crates/api_models/src/analytics/connector_events.rs
api_models::src::analytics::connector_events
78
true
// File: crates/api_models/src/analytics/active_payments.rs // Module: api_models::src::analytics::active_payments use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use super::NameDescription; #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum ActivePaymentsMetrics { ActivePayments, } pub mod metric_behaviour { pub struct ActivePayments; } impl From<ActivePaymentsMetrics> for NameDescription { fn from(value: ActivePaymentsMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Debug, serde::Serialize, Eq)] pub struct ActivePaymentsMetricsBucketIdentifier { pub time_bucket: Option<String>, } impl ActivePaymentsMetricsBucketIdentifier { pub fn new(time_bucket: Option<String>) -> Self { Self { time_bucket } } } impl Hash for ActivePaymentsMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.time_bucket.hash(state); } } impl PartialEq for ActivePaymentsMetricsBucketIdentifier { fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } } #[derive(Debug, serde::Serialize)] pub struct ActivePaymentsMetricsBucketValue { pub active_payments: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct MetricsBucketResponse { #[serde(flatten)] pub values: ActivePaymentsMetricsBucketValue, #[serde(flatten)] pub dimensions: ActivePaymentsMetricsBucketIdentifier, }
crates/api_models/src/analytics/active_payments.rs
api_models::src::analytics::active_payments
430
true
// File: crates/api_models/src/analytics/search.rs // Module: api_models::src::analytics::search use common_utils::{hashing::HashedString, types::TimeRange}; use masking::WithType; use serde_json::Value; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct SearchFilters { pub payment_method: Option<Vec<String>>, pub currency: Option<Vec<String>>, pub status: Option<Vec<String>>, pub customer_email: Option<Vec<HashedString<common_utils::pii::EmailStrategy>>>, pub search_tags: Option<Vec<HashedString<WithType>>>, pub connector: Option<Vec<String>>, pub payment_method_type: Option<Vec<String>>, pub card_network: Option<Vec<String>>, pub card_last_4: Option<Vec<String>>, pub payment_id: Option<Vec<String>>, pub amount: Option<Vec<u64>>, pub customer_id: Option<Vec<String>>, } impl SearchFilters { pub fn is_all_none(&self) -> bool { self.payment_method.is_none() && self.currency.is_none() && self.status.is_none() && self.customer_email.is_none() && self.search_tags.is_none() && self.connector.is_none() && self.payment_method_type.is_none() && self.card_network.is_none() && self.card_last_4.is_none() && self.payment_id.is_none() && self.amount.is_none() && self.customer_id.is_none() } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetGlobalSearchRequest { pub query: String, #[serde(default)] pub filters: Option<SearchFilters>, #[serde(default)] pub time_range: Option<TimeRange>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetSearchRequest { pub offset: i64, pub count: i64, pub query: String, #[serde(default)] pub filters: Option<SearchFilters>, #[serde(default)] pub time_range: Option<TimeRange>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetSearchRequestWithIndex { pub index: SearchIndex, pub search_req: GetSearchRequest, } #[derive( Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy, Eq, PartialEq, )] #[serde(rename_all = "snake_case")] pub enum SearchIndex { PaymentAttempts, PaymentIntents, Refunds, Disputes, SessionizerPaymentAttempts, SessionizerPaymentIntents, SessionizerRefunds, SessionizerDisputes, } #[derive(Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize, Copy)] pub enum SearchStatus { Success, Failure, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetSearchResponse { pub count: u64, pub index: SearchIndex, pub hits: Vec<Value>, pub status: SearchStatus, } #[derive(Debug, serde::Deserialize)] pub struct OpenMsearchOutput { #[serde(default)] pub responses: Vec<OpensearchOutput>, pub error: Option<OpensearchErrorDetails>, } #[derive(Debug, serde::Deserialize)] #[serde(untagged)] pub enum OpensearchOutput { Success(OpensearchSuccess), Error(OpensearchError), } #[derive(Debug, serde::Deserialize)] pub struct OpensearchError { pub error: OpensearchErrorDetails, pub status: u16, } #[derive(Debug, serde::Deserialize)] pub struct OpensearchErrorDetails { #[serde(rename = "type")] pub error_type: String, pub reason: String, } #[derive(Debug, serde::Deserialize)] pub struct OpensearchSuccess { pub hits: OpensearchHits, } #[derive(Debug, serde::Deserialize)] pub struct OpensearchHits { pub total: OpensearchResultsTotal, pub hits: Vec<OpensearchHit>, } #[derive(Debug, serde::Deserialize)] pub struct OpensearchResultsTotal { pub value: u64, } #[derive(Debug, serde::Deserialize)] pub struct OpensearchHit { #[serde(rename = "_source")] pub source: Value, }
crates/api_models/src/analytics/search.rs
api_models::src::analytics::search
958
true
// File: crates/api_models/src/analytics/sdk_events.rs // Module: api_models::src::analytics::sdk_events use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use super::{NameDescription, TimeRange}; #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct SdkEventsRequest { pub payment_id: common_utils::id_type::PaymentId, pub time_range: TimeRange, } #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct SdkEventFilters { #[serde(default)] pub payment_method: Vec<String>, #[serde(default)] pub platform: Vec<String>, #[serde(default)] pub browser_name: Vec<String>, #[serde(default)] pub source: Vec<String>, #[serde(default)] pub component: Vec<String>, #[serde(default)] pub payment_experience: Vec<String>, } #[derive( Debug, serde::Serialize, serde::Deserialize, strum::AsRefStr, PartialEq, PartialOrd, Eq, Ord, strum::Display, strum::EnumIter, Clone, Copy, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum SdkEventDimensions { // Do not change the order of these enums // Consult the Dashboard FE folks since these also affects the order of metrics on FE PaymentMethod, Platform, BrowserName, Source, Component, PaymentExperience, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum SdkEventMetrics { PaymentAttempts, PaymentMethodsCallCount, SdkRenderedCount, SdkInitiatedCount, PaymentMethodSelectedCount, PaymentDataFilledCount, AveragePaymentTime, LoadTime, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SdkEventNames { OrcaElementsCalled, AppRendered, PaymentMethodChanged, PaymentDataFilled, PaymentAttempt, PaymentMethodsCall, ConfirmCall, SessionsCall, CustomerPaymentMethodsCall, RedirectingUser, DisplayBankTransferInfoPage, DisplayQrCodeInfoPage, AuthenticationCall, AuthenticationCallInit, ThreeDsMethodCall, ThreeDsMethodResult, ThreeDsMethod, LoaderChanged, DisplayThreeDsSdk, ThreeDsSdkInit, AreqParamsGeneration, ChallengePresented, ChallengeComplete, } pub mod metric_behaviour { pub struct PaymentAttempts; pub struct PaymentMethodsCallCount; pub struct SdkRenderedCount; pub struct SdkInitiatedCount; pub struct PaymentMethodSelectedCount; pub struct PaymentDataFilledCount; pub struct AveragePaymentTime; pub struct LoadTime; } impl From<SdkEventMetrics> for NameDescription { fn from(value: SdkEventMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } impl From<SdkEventDimensions> for NameDescription { fn from(value: SdkEventDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Debug, serde::Serialize, Eq)] pub struct SdkEventMetricsBucketIdentifier { pub payment_method: Option<String>, pub platform: Option<String>, pub browser_name: Option<String>, pub source: Option<String>, pub component: Option<String>, pub payment_experience: Option<String>, pub time_bucket: Option<String>, } impl SdkEventMetricsBucketIdentifier { pub fn new( payment_method: Option<String>, platform: Option<String>, browser_name: Option<String>, source: Option<String>, component: Option<String>, payment_experience: Option<String>, time_bucket: Option<String>, ) -> Self { Self { payment_method, platform, browser_name, source, component, payment_experience, time_bucket, } } } impl Hash for SdkEventMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.payment_method.hash(state); self.platform.hash(state); self.browser_name.hash(state); self.source.hash(state); self.component.hash(state); self.payment_experience.hash(state); self.time_bucket.hash(state); } } impl PartialEq for SdkEventMetricsBucketIdentifier { fn eq(&self, other: &Self) -> bool { let mut left = DefaultHasher::new(); self.hash(&mut left); let mut right = DefaultHasher::new(); other.hash(&mut right); left.finish() == right.finish() } } #[derive(Debug, serde::Serialize)] pub struct SdkEventMetricsBucketValue { pub payment_attempts: Option<u64>, pub payment_methods_call_count: Option<u64>, pub average_payment_time: Option<u64>, pub load_time: Option<u64>, pub sdk_rendered_count: Option<u64>, pub sdk_initiated_count: Option<u64>, pub payment_method_selected_count: Option<u64>, pub payment_data_filled_count: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct MetricsBucketResponse { #[serde(flatten)] pub values: SdkEventMetricsBucketValue, #[serde(flatten)] pub dimensions: SdkEventMetricsBucketIdentifier, }
crates/api_models/src/analytics/sdk_events.rs
api_models::src::analytics::sdk_events
1,311
true
// File: crates/router_env/build.rs // Module: router_env::build mod vergen { include!("src/vergen.rs"); } mod cargo_workspace { include!("src/cargo_workspace.rs"); } fn main() { vergen::generate_cargo_instructions(); cargo_workspace::verify_cargo_metadata_format(); cargo_workspace::set_cargo_workspace_members_env(); }
crates/router_env/build.rs
router_env::build
80
true
// File: crates/router_env/src/vergen.rs // Module: router_env::src::vergen /// Configures the [`vergen`][::vergen] crate to generate the `cargo` build instructions. /// /// This function should be typically called within build scripts to generate `cargo` build /// instructions for the corresponding crate. /// /// # Panics /// /// Panics if `vergen` fails to generate `cargo` build instructions. #[cfg(feature = "vergen")] #[allow(clippy::expect_used)] pub fn generate_cargo_instructions() { use std::io::Write; use vergen::EmitBuilder; EmitBuilder::builder() .cargo_debug() .cargo_opt_level() .cargo_target_triple() .git_commit_timestamp() .git_describe(true, true, None) .git_sha(true) .rustc_semver() .rustc_commit_hash() .emit() .expect("Failed to generate `cargo` build instructions"); writeln!( &mut std::io::stdout(), "cargo:rustc-env=CARGO_PROFILE={}", std::env::var("PROFILE").expect("Failed to obtain `cargo` profile") ) .expect("Failed to set `CARGO_PROFILE` environment variable"); } #[cfg(not(feature = "vergen"))] pub fn generate_cargo_instructions() {}
crates/router_env/src/vergen.rs
router_env::src::vergen
295
true
// File: crates/router_env/src/logger.rs // Module: router_env::src::logger //! Logger of the system. pub use tracing::{debug, error, event as log, info, warn}; pub use tracing_attributes::instrument; pub mod config; mod defaults; pub use crate::config::Config; // mod macros; pub mod types; pub use types::{Category, Flow, Level, Tag}; mod setup; pub use setup::{setup, TelemetryGuard}; pub mod formatter; pub use formatter::FormattingLayer; pub mod storage; pub use storage::{Storage, StorageSubscription};
crates/router_env/src/logger.rs
router_env::src::logger
121
true
// File: crates/router_env/src/env.rs // Module: router_env::src::env //! Information about the current environment. use std::path::PathBuf; use serde::{Deserialize, Serialize}; /// Environment variables accessed by the application. This module aims to be the source of truth /// containing all environment variable that the application accesses. pub mod vars { /// Parent directory where `Cargo.toml` is stored. pub const CARGO_MANIFEST_DIR: &str = "CARGO_MANIFEST_DIR"; /// Environment variable that sets development/sandbox/production environment. pub const RUN_ENV: &str = "RUN_ENV"; /// Directory of config TOML files. Default is `config`. pub const CONFIG_DIR: &str = "CONFIG_DIR"; } /// Current environment. #[derive( Debug, Default, Deserialize, Serialize, Clone, Copy, strum::Display, strum::EnumString, )] #[serde(rename_all = "lowercase")] #[strum(serialize_all = "lowercase")] pub enum Env { /// Development environment. #[default] Development, /// Sandbox environment. Sandbox, /// Production environment. Production, } /// Name of current environment. Either "development", "sandbox" or "production". pub fn which() -> Env { #[cfg(debug_assertions)] let default_env = Env::Development; #[cfg(not(debug_assertions))] let default_env = Env::Production; std::env::var(vars::RUN_ENV).map_or_else(|_| default_env, |v| v.parse().unwrap_or(default_env)) } /// Three letter (lowercase) prefix corresponding to the current environment. /// Either `dev`, `snd` or `prd`. pub fn prefix_for_env() -> &'static str { match which() { Env::Development => "dev", Env::Sandbox => "snd", Env::Production => "prd", } } /// Path to the root directory of the cargo workspace. /// It is recommended that this be used by the application as the base path to build other paths /// such as configuration and logs directories. pub fn workspace_path() -> PathBuf { if let Ok(manifest_dir) = std::env::var(vars::CARGO_MANIFEST_DIR) { let mut path = PathBuf::from(manifest_dir); path.pop(); path.pop(); path } else { PathBuf::from(".") } } /// Version of the crate containing the following information: /// /// - The latest git tag. If tags are not present in the repository, the short commit hash is used /// instead. /// - Short hash of the latest git commit. /// - Timestamp of the latest git commit. /// /// Example: `0.1.0-abcd012-2038-01-19T03:14:08Z`. #[cfg(feature = "vergen")] #[macro_export] macro_rules! version { () => { concat!( env!("VERGEN_GIT_DESCRIBE"), "-", env!("VERGEN_GIT_SHA"), "-", env!("VERGEN_GIT_COMMIT_TIMESTAMP"), ) }; } /// A string uniquely identifying the application build. /// /// Consists of a combination of: /// - Version defined in the crate file /// - Timestamp of commit /// - Hash of the commit /// - Version of rust compiler /// - Target triple /// /// Example: `0.1.0-f5f383e-2022-09-04T11:39:37Z-1.63.0-x86_64-unknown-linux-gnu` #[cfg(feature = "vergen")] #[macro_export] macro_rules! build { () => { concat!( env!("CARGO_PKG_VERSION"), "-", env!("VERGEN_GIT_SHA"), "-", env!("VERGEN_GIT_COMMIT_TIMESTAMP"), "-", env!("VERGEN_RUSTC_SEMVER"), "-", $crate::profile!(), "-", env!("VERGEN_CARGO_TARGET_TRIPLE"), ) }; } /// Short hash of the current commit. /// /// Example: `f5f383e`. #[cfg(feature = "vergen")] #[macro_export] macro_rules! commit { () => { env!("VERGEN_GIT_SHA") }; } // /// Information about the platform on which service was built, including: // /// - Information about OS // /// - Information about CPU // /// // /// Example: ``. // #[macro_export] // macro_rules! platform { // ( // ) => { // concat!( // env!("VERGEN_SYSINFO_OS_VERSION"), // " - ", // env!("VERGEN_SYSINFO_CPU_BRAND"), // ) // }; // } /// Service name deduced from name of the binary. /// This macro must be called within binaries only. /// /// Example: `router`. #[macro_export] macro_rules! service_name { () => { env!("CARGO_BIN_NAME") }; } /// Build profile, either debug or release. /// /// Example: `release`. #[macro_export] macro_rules! profile { () => { env!("CARGO_PROFILE") }; } /// The latest git tag. If tags are not present in the repository, the short commit hash is used /// instead. Refer to the [`git describe`](https://git-scm.com/docs/git-describe) documentation for /// more details. #[macro_export] macro_rules! git_tag { () => { env!("VERGEN_GIT_DESCRIBE") }; }
crates/router_env/src/env.rs
router_env::src::env
1,206
true
// File: crates/router_env/src/lib.rs // Module: router_env::src::lib #![warn(missing_debug_implementations)] //! Environment of payment router: logger, basic config, its environment awareness. #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))] /// Utilities to identify members of the current cargo workspace. pub mod cargo_workspace; pub mod env; pub mod logger; pub mod metrics; /// `cargo` build instructions generation for obtaining information about the application /// environment. #[cfg(feature = "vergen")] pub mod vergen; // pub use literally; #[doc(inline)] pub use logger::*; pub use opentelemetry; pub use tracing; #[cfg(feature = "actix_web")] pub use tracing_actix_web; pub use tracing_appender; #[doc(inline)] pub use self::env::*;
crates/router_env/src/lib.rs
router_env::src::lib
183
true
// File: crates/router_env/src/metrics.rs // Module: router_env::src::metrics //! Utilities to easily create opentelemetry contexts, meters and metrics. /// Create a global [`Meter`][Meter] with the specified name and an optional description. /// /// [Meter]: opentelemetry::metrics::Meter #[macro_export] macro_rules! global_meter { ($name:ident) => { static $name: ::std::sync::LazyLock<$crate::opentelemetry::metrics::Meter> = ::std::sync::LazyLock::new(|| $crate::opentelemetry::global::meter(stringify!($name))); }; ($meter:ident, $name:literal) => { static $meter: ::std::sync::LazyLock<$crate::opentelemetry::metrics::Meter> = ::std::sync::LazyLock::new(|| $crate::opentelemetry::global::meter(stringify!($name))); }; } /// Create a [`Counter`][Counter] metric with the specified name and an optional description, /// associated with the specified meter. Note that the meter must be a valid [`Meter`][Meter]. /// /// [Counter]: opentelemetry::metrics::Counter /// [Meter]: opentelemetry::metrics::Meter #[macro_export] macro_rules! counter_metric { ($name:ident, $meter:ident) => { pub(crate) static $name: ::std::sync::LazyLock< $crate::opentelemetry::metrics::Counter<u64>, > = ::std::sync::LazyLock::new(|| $meter.u64_counter(stringify!($name)).build()); }; ($name:ident, $meter:ident, description:literal) => { #[doc = $description] pub(crate) static $name: ::std::sync::LazyLock< $crate::opentelemetry::metrics::Counter<u64>, > = ::std::sync::LazyLock::new(|| { $meter .u64_counter(stringify!($name)) .with_description($description) .build() }); }; } /// Create a [`Histogram`][Histogram] f64 metric with the specified name and an optional description, /// associated with the specified meter. Note that the meter must be a valid [`Meter`][Meter]. /// /// [Histogram]: opentelemetry::metrics::Histogram /// [Meter]: opentelemetry::metrics::Meter #[macro_export] macro_rules! histogram_metric_f64 { ($name:ident, $meter:ident) => { pub(crate) static $name: ::std::sync::LazyLock< $crate::opentelemetry::metrics::Histogram<f64>, > = ::std::sync::LazyLock::new(|| { $meter .f64_histogram(stringify!($name)) .with_boundaries($crate::metrics::f64_histogram_buckets()) .build() }); }; ($name:ident, $meter:ident, $description:literal) => { #[doc = $description] pub(crate) static $name: ::std::sync::LazyLock< $crate::opentelemetry::metrics::Histogram<f64>, > = ::std::sync::LazyLock::new(|| { $meter .f64_histogram(stringify!($name)) .with_description($description) .with_boundaries($crate::metrics::f64_histogram_buckets()) .build() }); }; } /// Create a [`Histogram`][Histogram] u64 metric with the specified name and an optional description, /// associated with the specified meter. Note that the meter must be a valid [`Meter`][Meter]. /// /// [Histogram]: opentelemetry::metrics::Histogram /// [Meter]: opentelemetry::metrics::Meter #[macro_export] macro_rules! histogram_metric_u64 { ($name:ident, $meter:ident) => { pub(crate) static $name: ::std::sync::LazyLock< $crate::opentelemetry::metrics::Histogram<u64>, > = ::std::sync::LazyLock::new(|| { $meter .u64_histogram(stringify!($name)) .with_boundaries($crate::metrics::f64_histogram_buckets()) .build() }); }; ($name:ident, $meter:ident, $description:literal) => { #[doc = $description] pub(crate) static $name: ::std::sync::LazyLock< $crate::opentelemetry::metrics::Histogram<u64>, > = ::std::sync::LazyLock::new(|| { $meter .u64_histogram(stringify!($name)) .with_description($description) .with_boundaries($crate::metrics::f64_histogram_buckets()) .build() }); }; } /// Create a [`Gauge`][Gauge] metric with the specified name and an optional description, /// associated with the specified meter. Note that the meter must be a valid [`Meter`][Meter]. /// /// [Gauge]: opentelemetry::metrics::Gauge /// [Meter]: opentelemetry::metrics::Meter #[macro_export] macro_rules! gauge_metric { ($name:ident, $meter:ident) => { pub(crate) static $name: ::std::sync::LazyLock<$crate::opentelemetry::metrics::Gauge<u64>> = ::std::sync::LazyLock::new(|| $meter.u64_gauge(stringify!($name)).build()); }; ($name:ident, $meter:ident, description:literal) => { #[doc = $description] pub(crate) static $name: ::std::sync::LazyLock<$crate::opentelemetry::metrics::Gauge<u64>> = ::std::sync::LazyLock::new(|| { $meter .u64_gauge(stringify!($name)) .with_description($description) .build() }); }; } /// Create attributes to associate with a metric from key-value pairs. #[macro_export] macro_rules! metric_attributes { ($(($key:expr, $value:expr $(,)?)),+ $(,)?) => { &[$($crate::opentelemetry::KeyValue::new($key, $value)),+] }; } pub use helpers::f64_histogram_buckets; mod helpers { /// Returns the buckets to be used for a f64 histogram #[inline(always)] pub fn f64_histogram_buckets() -> Vec<f64> { let mut init = 0.01; let mut buckets: [f64; 15] = [0.0; 15]; for bucket in &mut buckets { init *= 2.0; *bucket = init; } Vec::from(buckets) } }
crates/router_env/src/metrics.rs
router_env::src::metrics
1,483
true
// File: crates/router_env/src/cargo_workspace.rs // Module: router_env::src::cargo_workspace /// Sets the `CARGO_WORKSPACE_MEMBERS` environment variable to include a comma-separated list of /// names of all crates in the current cargo workspace. /// /// This function should be typically called within build scripts, so that the environment variable /// is available to the corresponding crate at compile time. /// /// # Panics /// /// Panics if running the `cargo metadata` command fails. #[allow(clippy::expect_used)] pub fn set_cargo_workspace_members_env() { use std::io::Write; let metadata = cargo_metadata::MetadataCommand::new() .exec() .expect("Failed to obtain cargo metadata"); let workspace_members = metadata .workspace_packages() .iter() .map(|package| package.name.as_str()) .collect::<Vec<_>>() .join(","); writeln!( &mut std::io::stdout(), "cargo:rustc-env=CARGO_WORKSPACE_MEMBERS={workspace_members}" ) .expect("Failed to set `CARGO_WORKSPACE_MEMBERS` environment variable"); } /// Verify that the cargo metadata workspace packages format matches that expected by /// [`set_cargo_workspace_members_env`] to set the `CARGO_WORKSPACE_MEMBERS` environment variable. /// /// This function should be typically called within build scripts, before the /// [`set_cargo_workspace_members_env`] function is called. /// /// # Panics /// /// Panics if running the `cargo metadata` command fails, or if the workspace member package names /// cannot be determined. pub fn verify_cargo_metadata_format() { #[allow(clippy::expect_used)] let metadata = cargo_metadata::MetadataCommand::new() .exec() .expect("Failed to obtain cargo metadata"); assert!( metadata .workspace_packages() .iter() .any(|package| package.name == env!("CARGO_PKG_NAME")), "Unable to determine workspace member package names from `cargo metadata`" ); } /// Obtain the crates in the current cargo workspace as a `HashSet`. /// /// This macro requires that [`set_cargo_workspace_members_env()`] function be called in the /// build script of the crate where this macro is being called. /// /// # Errors /// /// Causes a compilation error if the `CARGO_WORKSPACE_MEMBERS` environment variable is unset. #[macro_export] macro_rules! cargo_workspace_members { () => { std::env!("CARGO_WORKSPACE_MEMBERS") .split(',') .collect::<std::collections::HashSet<&'static str>>() }; }
crates/router_env/src/cargo_workspace.rs
router_env::src::cargo_workspace
561
true
// File: crates/router_env/src/logger/types.rs // Module: router_env::src::logger::types //! Types. use serde::Deserialize; use strum::{Display, EnumString}; pub use tracing::{ field::{Field, Visit}, Level, Value, }; /// Category and tag of log event. /// /// Don't hesitate to add your variant if it is missing here. #[derive(Debug, Default, Deserialize, Clone, Display, EnumString)] pub enum Tag { /// General. #[default] General, /// Redis: get. RedisGet, /// Redis: set. RedisSet, /// API: incoming web request. ApiIncomingRequest, /// API: outgoing web request. ApiOutgoingRequest, /// Data base: create. DbCreate, /// Data base: read. DbRead, /// Data base: updare. DbUpdate, /// Data base: delete. DbDelete, /// Begin Request BeginRequest, /// End Request EndRequest, /// Call initiated to connector. InitiatedToConnector, /// Event: general. Event, /// Compatibility Layer Request CompatibilityLayerRequest, } /// API Flow #[derive(Debug, Display, Clone, PartialEq, Eq)] pub enum Flow { /// Health check HealthCheck, /// Deep health Check DeepHealthCheck, /// Organization create flow OrganizationCreate, /// Organization retrieve flow OrganizationRetrieve, /// Organization update flow OrganizationUpdate, /// Merchants account create flow. MerchantsAccountCreate, /// Merchants account retrieve flow. MerchantsAccountRetrieve, /// Merchants account update flow. MerchantsAccountUpdate, /// Merchants account delete flow. MerchantsAccountDelete, /// Merchant Connectors create flow. MerchantConnectorsCreate, /// Merchant Connectors retrieve flow. MerchantConnectorsRetrieve, /// Merchant account list MerchantAccountList, /// Merchant Connectors update flow. MerchantConnectorsUpdate, /// Merchant Connectors delete flow. MerchantConnectorsDelete, /// Merchant Connectors list flow. MerchantConnectorsList, /// Merchant Transfer Keys MerchantTransferKey, /// ConfigKey create flow. ConfigKeyCreate, /// ConfigKey fetch flow. ConfigKeyFetch, /// Enable platform account flow. EnablePlatformAccount, /// ConfigKey Update flow. ConfigKeyUpdate, /// ConfigKey Delete flow. ConfigKeyDelete, /// Customers create flow. CustomersCreate, /// Customers retrieve flow. CustomersRetrieve, /// Customers update flow. CustomersUpdate, /// Customers delete flow. CustomersDelete, /// Customers get mandates flow. CustomersGetMandates, /// Create an Ephemeral Key. EphemeralKeyCreate, /// Delete an Ephemeral Key. EphemeralKeyDelete, /// Mandates retrieve flow. MandatesRetrieve, /// Mandates revoke flow. MandatesRevoke, /// Mandates list flow. MandatesList, /// Payment methods create flow. PaymentMethodsCreate, /// Payment methods migrate flow. PaymentMethodsMigrate, /// Payment methods batch update flow. PaymentMethodsBatchUpdate, /// Payment methods list flow. PaymentMethodsList, /// Payment method save flow PaymentMethodSave, /// Customer payment methods list flow. CustomerPaymentMethodsList, /// Payment methods token data get flow. GetPaymentMethodTokenData, /// List Customers for a merchant CustomersList, ///List Customers for a merchant with constraints. CustomersListWithConstraints, /// Retrieve countries and currencies for connector and payment method ListCountriesCurrencies, /// Payment method create collect link flow. PaymentMethodCollectLink, /// Payment methods retrieve flow. PaymentMethodsRetrieve, /// Payment methods update flow. PaymentMethodsUpdate, /// Payment methods delete flow. PaymentMethodsDelete, /// Network token status check flow. NetworkTokenStatusCheck, /// Default Payment method flow. DefaultPaymentMethodsSet, /// Payments create flow. PaymentsCreate, /// Payments Retrieve flow. PaymentsRetrieve, /// Payments Retrieve force sync flow. PaymentsRetrieveForceSync, /// Payments Retrieve using merchant reference id PaymentsRetrieveUsingMerchantReferenceId, /// Payments update flow. PaymentsUpdate, /// Payments confirm flow. PaymentsConfirm, /// Payments capture flow. PaymentsCapture, /// Payments cancel flow. PaymentsCancel, /// Payments cancel post capture flow. PaymentsCancelPostCapture, /// Payments approve flow. PaymentsApprove, /// Payments reject flow. PaymentsReject, /// Payments Session Token flow PaymentsSessionToken, /// Payments start flow. PaymentsStart, /// Payments list flow. PaymentsList, /// Payments filters flow PaymentsFilters, /// Payments aggregates flow PaymentsAggregate, /// Payments Create Intent flow PaymentsCreateIntent, /// Payments Get Intent flow PaymentsGetIntent, /// Payments Update Intent flow PaymentsUpdateIntent, /// Payments confirm intent flow PaymentsConfirmIntent, /// Payments create and confirm intent flow PaymentsCreateAndConfirmIntent, /// Payment attempt list flow PaymentAttemptsList, #[cfg(feature = "payouts")] /// Payouts create flow PayoutsCreate, #[cfg(feature = "payouts")] /// Payouts retrieve flow. PayoutsRetrieve, #[cfg(feature = "payouts")] /// Payouts update flow. PayoutsUpdate, /// Payouts confirm flow. PayoutsConfirm, #[cfg(feature = "payouts")] /// Payouts cancel flow. PayoutsCancel, #[cfg(feature = "payouts")] /// Payouts fulfill flow. PayoutsFulfill, #[cfg(feature = "payouts")] /// Payouts list flow. PayoutsList, #[cfg(feature = "payouts")] /// Payouts filter flow. PayoutsFilter, /// Payouts accounts flow. PayoutsAccounts, /// Payout link initiate flow PayoutLinkInitiate, /// Payments Redirect flow PaymentsRedirect, /// Payemnts Complete Authorize Flow PaymentsCompleteAuthorize, /// Refunds create flow. RefundsCreate, /// Refunds retrieve flow. RefundsRetrieve, /// Refunds retrieve force sync flow. RefundsRetrieveForceSync, /// Refunds update flow. RefundsUpdate, /// Refunds list flow. RefundsList, /// Refunds filters flow RefundsFilters, /// Refunds aggregates flow RefundsAggregate, // Retrieve forex flow. RetrieveForexFlow, /// Toggles recon service for a merchant. ReconMerchantUpdate, /// Recon token request flow. ReconTokenRequest, /// Initial request for recon service. ReconServiceRequest, /// Recon token verification flow ReconVerifyToken, /// Routing create flow, RoutingCreateConfig, /// Routing link config RoutingLinkConfig, /// Routing link config RoutingUnlinkConfig, /// Routing retrieve config RoutingRetrieveConfig, /// Routing retrieve active config RoutingRetrieveActiveConfig, /// Routing retrieve default config RoutingRetrieveDefaultConfig, /// Routing retrieve dictionary RoutingRetrieveDictionary, /// Rule migration for decision-engine DecisionEngineRuleMigration, /// Routing update config RoutingUpdateConfig, /// Routing update default config RoutingUpdateDefaultConfig, /// Routing delete config RoutingDeleteConfig, /// Subscription create flow, CreateSubscription, /// Subscription get plans flow, GetPlansForSubscription, /// Subscription confirm flow, ConfirmSubscription, /// Subscription create and confirm flow, CreateAndConfirmSubscription, /// Get Subscription flow GetSubscription, /// Update Subscription flow UpdateSubscription, /// Get Subscription estimate flow GetSubscriptionEstimate, /// Create dynamic routing CreateDynamicRoutingConfig, /// Toggle dynamic routing ToggleDynamicRouting, /// Update dynamic routing config UpdateDynamicRoutingConfigs, /// Add record to blocklist AddToBlocklist, /// Delete record from blocklist DeleteFromBlocklist, /// List entries from blocklist ListBlocklist, /// Toggle blocklist for merchant ToggleBlocklistGuard, /// Incoming Webhook Receive IncomingWebhookReceive, /// Recovery incoming webhook receive RecoveryIncomingWebhookReceive, /// Validate payment method flow ValidatePaymentMethod, /// API Key create flow ApiKeyCreate, /// API Key retrieve flow ApiKeyRetrieve, /// API Key update flow ApiKeyUpdate, /// API Key revoke flow ApiKeyRevoke, /// API Key list flow ApiKeyList, /// Dispute Retrieve flow DisputesRetrieve, /// Dispute List flow DisputesList, /// Dispute Filters flow DisputesFilters, /// Cards Info flow CardsInfo, /// Create File flow CreateFile, /// Delete File flow DeleteFile, /// Retrieve File flow RetrieveFile, /// Dispute Evidence submission flow DisputesEvidenceSubmit, /// Create Config Key flow CreateConfigKey, /// Attach Dispute Evidence flow AttachDisputeEvidence, /// Delete Dispute Evidence flow DeleteDisputeEvidence, /// Disputes aggregate flow DisputesAggregate, /// Retrieve Dispute Evidence flow RetrieveDisputeEvidence, /// Invalidate cache flow CacheInvalidate, /// Payment Link Retrieve flow PaymentLinkRetrieve, /// payment Link Initiate flow PaymentLinkInitiate, /// payment Link Initiate flow PaymentSecureLinkInitiate, /// Payment Link List flow PaymentLinkList, /// Payment Link Status PaymentLinkStatus, /// Create a profile ProfileCreate, /// Update a profile ProfileUpdate, /// Retrieve a profile ProfileRetrieve, /// Delete a profile ProfileDelete, /// List all the profiles for a merchant ProfileList, /// Different verification flows Verification, /// Rust locker migration RustLockerMigration, /// Gsm Rule Creation flow GsmRuleCreate, /// Gsm Rule Retrieve flow GsmRuleRetrieve, /// Gsm Rule Update flow GsmRuleUpdate, /// Apple pay certificates migration ApplePayCertificatesMigration, /// Gsm Rule Delete flow GsmRuleDelete, /// Get data from embedded flow GetDataFromHyperswitchAiFlow, // List all chat interactions ListAllChatInteractions, /// User Sign Up UserSignUp, /// User Sign Up UserSignUpWithMerchantId, /// User Sign In UserSignIn, /// User transfer key UserTransferKey, /// User connect account UserConnectAccount, /// Upsert Decision Manager Config DecisionManagerUpsertConfig, /// Delete Decision Manager Config DecisionManagerDeleteConfig, /// Retrieve Decision Manager Config DecisionManagerRetrieveConfig, /// Manual payment fulfillment acknowledgement FrmFulfillment, /// Get connectors feature matrix FeatureMatrix, /// Change password flow ChangePassword, /// Signout flow Signout, /// Set Dashboard Metadata flow SetDashboardMetadata, /// Get Multiple Dashboard Metadata flow GetMultipleDashboardMetadata, /// Payment Connector Verify VerifyPaymentConnector, /// Internal user signup InternalUserSignup, /// Create tenant level user TenantUserCreate, /// Switch org SwitchOrg, /// Switch merchant v2 SwitchMerchantV2, /// Switch profile SwitchProfile, /// Get permission info GetAuthorizationInfo, /// Get Roles info GetRolesInfo, /// Get Parent Group Info GetParentGroupInfo, /// List roles v2 ListRolesV2, /// List invitable roles at entity level ListInvitableRolesAtEntityLevel, /// List updatable roles at entity level ListUpdatableRolesAtEntityLevel, /// Get role GetRole, /// Get parent info for role GetRoleV2, /// Get role from token GetRoleFromToken, /// Get resources and groups for role from token GetRoleFromTokenV2, /// Get parent groups info for role from token GetParentGroupsInfoForRoleFromToken, /// Update user role UpdateUserRole, /// Create merchant account for user in a org UserMerchantAccountCreate, /// Create Platform CreatePlatformAccount, /// Create Org in a given tenancy UserOrgMerchantCreate, /// Generate Sample Data GenerateSampleData, /// Delete Sample Data DeleteSampleData, /// Get details of a user GetUserDetails, /// Get details of a user role in a merchant account GetUserRoleDetails, /// PaymentMethodAuth Link token create PmAuthLinkTokenCreate, /// PaymentMethodAuth Exchange token create PmAuthExchangeToken, /// Get reset password link ForgotPassword, /// Reset password using link ResetPassword, /// Force set or force change password RotatePassword, /// Invite multiple users InviteMultipleUser, /// Reinvite user ReInviteUser, /// Accept invite from email AcceptInviteFromEmail, /// Delete user role DeleteUserRole, /// Incremental Authorization flow PaymentsIncrementalAuthorization, /// Extend Authorization flow PaymentsExtendAuthorization, /// Get action URL for connector onboarding GetActionUrl, /// Sync connector onboarding status SyncOnboardingStatus, /// Reset tracking id ResetTrackingId, /// Verify email Token VerifyEmail, /// Send verify email VerifyEmailRequest, /// Update user account details UpdateUserAccountDetails, /// Accept user invitation using entities AcceptInvitationsV2, /// Accept user invitation using entities before user login AcceptInvitationsPreAuth, /// Initiate external authentication for a payment PaymentsExternalAuthentication, /// Authorize the payment after external 3ds authentication PaymentsAuthorize, /// Create Role CreateRole, /// Create Role V2 CreateRoleV2, /// Update Role UpdateRole, /// User email flow start UserFromEmail, /// Begin TOTP TotpBegin, /// Reset TOTP TotpReset, /// Verify TOTP TotpVerify, /// Update TOTP secret TotpUpdate, /// Verify Access Code RecoveryCodeVerify, /// Generate or Regenerate recovery codes RecoveryCodesGenerate, /// Terminate two factor authentication TerminateTwoFactorAuth, /// Check 2FA status TwoFactorAuthStatus, /// Create user authentication method CreateUserAuthenticationMethod, /// Update user authentication method UpdateUserAuthenticationMethod, /// List user authentication methods ListUserAuthenticationMethods, /// Get sso auth url GetSsoAuthUrl, /// Signin with SSO SignInWithSso, /// Auth Select AuthSelect, /// List Orgs for user ListOrgForUser, /// List Merchants for user in org ListMerchantsForUserInOrg, /// List Profile for user in org and merchant ListProfileForUserInOrgAndMerchant, /// List Users in Org ListUsersInLineage, /// List invitations for user ListInvitationsForUser, /// Get theme using lineage GetThemeUsingLineage, /// Get theme using theme id GetThemeUsingThemeId, /// Upload file to theme storage UploadFileToThemeStorage, /// Create theme CreateTheme, /// Update theme UpdateTheme, /// Delete theme DeleteTheme, /// Create user theme CreateUserTheme, /// Update user theme UpdateUserTheme, /// Delete user theme DeleteUserTheme, /// Upload file to user theme storage UploadFileToUserThemeStorage, /// Get user theme using theme id GetUserThemeUsingThemeId, ///List All Themes In Lineage ListAllThemesInLineage, /// Get user theme using lineage GetUserThemeUsingLineage, /// List initial webhook delivery attempts WebhookEventInitialDeliveryAttemptList, /// List delivery attempts for a webhook event WebhookEventDeliveryAttemptList, /// Manually retry the delivery for a webhook event WebhookEventDeliveryRetry, /// Retrieve status of the Poll RetrievePollStatus, /// Toggles the extended card info feature in profile level ToggleExtendedCardInfo, /// Toggles the extended card info feature in profile level ToggleConnectorAgnosticMit, /// Get the extended card info associated to a payment_id GetExtendedCardInfo, /// Manually update the refund details like status, error code, error message etc. RefundsManualUpdate, /// Manually update the payment details like status, error code, error message etc. PaymentsManualUpdate, /// Dynamic Tax Calcultion SessionUpdateTaxCalculation, ProxyConfirmIntent, /// Payments post session tokens flow PaymentsPostSessionTokens, /// Payments Update Metadata PaymentsUpdateMetadata, /// Payments start redirection flow PaymentStartRedirection, /// Volume split on the routing type VolumeSplitOnRoutingType, /// Routing evaluate rule flow RoutingEvaluateRule, /// Relay flow Relay, /// Relay retrieve flow RelayRetrieve, /// Card tokenization flow TokenizeCard, /// Card tokenization using payment method flow TokenizeCardUsingPaymentMethodId, /// Cards batch tokenization flow TokenizeCardBatch, /// Incoming Relay Webhook Receive IncomingRelayWebhookReceive, /// Generate Hypersense Token HypersenseTokenRequest, /// Verify Hypersense Token HypersenseVerifyToken, /// Signout Hypersense Token HypersenseSignoutToken, /// Payment Method Session Create PaymentMethodSessionCreate, /// Payment Method Session Retrieve PaymentMethodSessionRetrieve, // Payment Method Session Update PaymentMethodSessionUpdate, /// Update a saved payment method using the payment methods session PaymentMethodSessionUpdateSavedPaymentMethod, /// Delete a saved payment method using the payment methods session PaymentMethodSessionDeleteSavedPaymentMethod, /// Confirm a payment method session with payment method data PaymentMethodSessionConfirm, /// Create Cards Info flow CardsInfoCreate, /// Update Cards Info flow CardsInfoUpdate, /// Cards Info migrate flow CardsInfoMigrate, ///Total payment method count for merchant TotalPaymentMethodCount, /// Process Tracker Revenue Recovery Workflow Retrieve RevenueRecoveryRetrieve, /// Process Tracker Revenue Recovery Workflow Resume RevenueRecoveryResume, /// Tokenization flow TokenizationCreate, /// Tokenization retrieve flow TokenizationRetrieve, /// Clone Connector flow CloneConnector, /// Authentication Create flow AuthenticationCreate, /// Authentication Eligibility flow AuthenticationEligibility, /// Authentication Sync flow AuthenticationSync, /// Authentication Sync Post Update flow AuthenticationSyncPostUpdate, /// Authentication Authenticate flow AuthenticationAuthenticate, ///Proxy Flow Proxy, /// Profile Acquirer Create flow ProfileAcquirerCreate, /// Profile Acquirer Update flow ProfileAcquirerUpdate, /// ThreeDs Decision Rule Execute flow ThreeDsDecisionRuleExecute, /// Incoming Network Token Webhook Receive IncomingNetworkTokenWebhookReceive, /// Decision Engine Decide Gateway Call DecisionEngineDecideGatewayCall, /// Decision Engine Gateway Feedback Call DecisionEngineGatewayFeedbackCall, /// Recovery payments create flow. RecoveryPaymentsCreate, /// Tokenization delete flow TokenizationDelete, /// Payment method data backfill flow RecoveryDataBackfill, /// Revenue recovery Redis operations flow RevenueRecoveryRedis, /// Gift card balance check flow GiftCardBalanceCheck, /// Payments Submit Eligibility flow PaymentsSubmitEligibility, } /// Trait for providing generic behaviour to flow metric pub trait FlowMetric: ToString + std::fmt::Debug + Clone {} impl FlowMetric for Flow {} /// Category of log event. #[derive(Debug)] pub enum Category { /// Redis: general. Redis, /// API: general. Api, /// Database: general. Store, /// Event: general. Event, /// General: general. General, }
crates/router_env/src/logger/types.rs
router_env::src::logger::types
4,504
true
// File: crates/router_env/src/logger/config.rs // Module: router_env::src::logger::config //! Logger-specific config. use std::path::PathBuf; use serde::Deserialize; /// Config settings. #[derive(Debug, Deserialize, Clone)] pub struct Config { /// Logging to a file. pub log: Log, } /// Log config settings. #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct Log { /// Logging to a file. pub file: LogFile, /// Logging to a console. pub console: LogConsole, /// Telemetry / tracing. pub telemetry: LogTelemetry, } /// Logging to a file. #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct LogFile { /// Whether you want to store log in log files. pub enabled: bool, /// Where to store log files. pub path: String, /// Name of log file without suffix. pub file_name: String, /// What gets into log files. pub level: Level, /// Directive which sets the log level for one or more crates/modules. pub filtering_directive: Option<String>, // pub do_async: bool, // is not used // pub rotation: u16, } /// Describes the level of verbosity of a span or event. #[derive(Debug, Clone, Copy)] pub struct Level(pub(super) tracing::Level); impl Level { /// Returns the most verbose [`tracing::Level`] pub fn into_level(self) -> tracing::Level { self.0 } } impl<'de> Deserialize<'de> for Level { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { use std::str::FromStr as _; let s = String::deserialize(deserializer)?; tracing::Level::from_str(&s) .map(Level) .map_err(serde::de::Error::custom) } } /// Logging to a console. #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct LogConsole { /// Whether you want to see log in your terminal. pub enabled: bool, /// What you see in your terminal. pub level: Level, /// Log format #[serde(default)] pub log_format: LogFormat, /// Directive which sets the log level for one or more crates/modules. pub filtering_directive: Option<String>, } /// Telemetry / tracing. #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct LogTelemetry { /// Whether the traces pipeline is enabled. pub traces_enabled: bool, /// Whether the metrics pipeline is enabled. pub metrics_enabled: bool, /// Whether errors in setting up traces or metrics pipelines must be ignored. pub ignore_errors: bool, /// Sampling rate for traces pub sampling_rate: Option<f64>, /// Base endpoint URL to send metrics and traces to. Can optionally include the port number. pub otel_exporter_otlp_endpoint: Option<String>, /// Timeout (in milliseconds) for sending metrics and traces. pub otel_exporter_otlp_timeout: Option<u64>, /// Whether to use xray ID generator, (enable this if you plan to use AWS-XRAY) pub use_xray_generator: bool, /// Route Based Tracing pub route_to_trace: Option<Vec<String>>, /// Interval for collecting the metrics (such as gauge) in background thread pub bg_metrics_collection_interval_in_secs: Option<u16>, } /// Telemetry / tracing. #[derive(Default, Debug, Deserialize, Clone, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum LogFormat { /// Default pretty log format Default, /// JSON based structured logging #[default] Json, /// JSON based structured logging with pretty print PrettyJson, } impl Config { /// Default constructor. pub fn new() -> Result<Self, config::ConfigError> { Self::new_with_config_path(None) } /// Constructor expecting config path set explicitly. pub fn new_with_config_path( explicit_config_path: Option<PathBuf>, ) -> Result<Self, config::ConfigError> { // 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 = crate::env::which(); let config_path = Self::config_path(&environment.to_string(), explicit_config_path); let config = Self::builder(&environment.to_string())? .add_source(config::File::from(config_path).required(false)) .add_source(config::Environment::with_prefix("ROUTER").separator("__")) .build()?; // The logger may not yet be initialized when constructing the application configuration #[allow(clippy::print_stderr)] serde_path_to_error::deserialize(config).map_err(|error| { crate::error!(%error, "Unable to deserialize configuration"); eprintln!("Unable to deserialize application configuration: {error}"); error.into_inner() }) } /// Construct config builder extending it by fall-back defaults and setting config file to load. pub fn builder( environment: &str, ) -> Result<config::ConfigBuilder<config::builder::DefaultState>, config::ConfigError> { config::Config::builder() // Here, it should be `set_override()` not `set_default()`. // "env" can't be altered by config field. // Should be single source of truth. .set_override("env", environment) } /// Config path. pub fn config_path(environment: &str, explicit_config_path: Option<PathBuf>) -> PathBuf { let mut config_path = PathBuf::new(); if let Some(explicit_config_path_val) = explicit_config_path { config_path.push(explicit_config_path_val); } else { let config_file_name = match environment { "production" => "production.toml", "sandbox" => "sandbox.toml", _ => "development.toml", }; let config_directory = Self::get_config_directory(); config_path.push(config_directory); config_path.push(config_file_name); } config_path } /// Get the Directory for the config file /// Read the env variable `CONFIG_DIR` or fallback to `config` pub fn get_config_directory() -> PathBuf { let mut config_path = PathBuf::new(); let config_directory = std::env::var(crate::env::vars::CONFIG_DIR).unwrap_or_else(|_| "config".into()); config_path.push(crate::env::workspace_path()); config_path.push(config_directory); config_path } }
crates/router_env/src/logger/config.rs
router_env::src::logger::config
1,593
true
// File: crates/router_env/src/logger/formatter.rs // Module: router_env::src::logger::formatter //! Formatting [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router. use std::{ collections::{HashMap, HashSet}, fmt, io::Write, sync::LazyLock, }; use config::ConfigError; use serde::ser::{SerializeMap, Serializer}; use serde_json::{ser::Formatter, Value}; // use time::format_description::well_known::Rfc3339; use time::format_description::well_known::Iso8601; use tracing::{Event, Metadata, Subscriber}; use tracing_subscriber::{ fmt::MakeWriter, layer::Context, registry::{LookupSpan, SpanRef}, Layer, }; use crate::Storage; // TODO: Documentation coverage for this crate // Implicit keys const MESSAGE: &str = "message"; const HOSTNAME: &str = "hostname"; const PID: &str = "pid"; const ENV: &str = "env"; const VERSION: &str = "version"; const BUILD: &str = "build"; const LEVEL: &str = "level"; const TARGET: &str = "target"; const SERVICE: &str = "service"; const LINE: &str = "line"; const FILE: &str = "file"; const FN: &str = "fn"; const FULL_NAME: &str = "full_name"; const TIME: &str = "time"; // Extra implicit keys. Keys that are provided during runtime but should be treated as // implicit in the logs const FLOW: &str = "flow"; const MERCHANT_AUTH: &str = "merchant_authentication"; const MERCHANT_ID: &str = "merchant_id"; const REQUEST_METHOD: &str = "request_method"; const REQUEST_URL_PATH: &str = "request_url_path"; const REQUEST_ID: &str = "request_id"; const WORKFLOW_ID: &str = "workflow_id"; const GLOBAL_ID: &str = "global_id"; const SESSION_ID: &str = "session_id"; /// Set of predefined implicit keys. pub static IMPLICIT_KEYS: LazyLock<rustc_hash::FxHashSet<&str>> = LazyLock::new(|| { let mut set = rustc_hash::FxHashSet::default(); set.insert(HOSTNAME); set.insert(PID); set.insert(ENV); set.insert(VERSION); set.insert(BUILD); set.insert(LEVEL); set.insert(TARGET); set.insert(SERVICE); set.insert(LINE); set.insert(FILE); set.insert(FN); set.insert(FULL_NAME); set.insert(TIME); set }); /// Extra implicit keys. Keys that are not purely implicit but need to be logged alongside /// other implicit keys in the log json. pub static EXTRA_IMPLICIT_KEYS: LazyLock<rustc_hash::FxHashSet<&str>> = LazyLock::new(|| { let mut set = rustc_hash::FxHashSet::default(); set.insert(MESSAGE); set.insert(FLOW); set.insert(MERCHANT_AUTH); set.insert(MERCHANT_ID); set.insert(REQUEST_METHOD); set.insert(REQUEST_URL_PATH); set.insert(REQUEST_ID); set.insert(GLOBAL_ID); set.insert(SESSION_ID); set.insert(WORKFLOW_ID); set }); /// Describe type of record: entering a span, exiting a span, an event. #[derive(Clone, Debug)] pub enum RecordType { /// Entering a span. EnterSpan, /// Exiting a span. ExitSpan, /// Event. Event, } impl fmt::Display for RecordType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let repr = match self { Self::EnterSpan => "START", Self::ExitSpan => "END", Self::Event => "EVENT", }; write!(f, "{repr}") } } /// Format log records. /// `FormattingLayer` relies on the `tracing_bunyan_formatter::JsonStorageLayer` which is storage of entries. #[derive(Debug)] pub struct FormattingLayer<W, F> where W: for<'a> MakeWriter<'a> + 'static, F: Formatter + Clone, { dst_writer: W, pid: u32, hostname: String, env: String, service: String, #[cfg(feature = "vergen")] version: String, #[cfg(feature = "vergen")] build: String, default_fields: HashMap<String, Value>, formatter: F, } impl<W, F> FormattingLayer<W, F> where W: for<'a> MakeWriter<'a> + 'static, F: Formatter + Clone, { /// Constructor of `FormattingLayer`. /// /// A `name` will be attached to all records during formatting. /// A `dst_writer` to forward all records. /// /// ## Example /// ```rust /// let formatting_layer = router_env::FormattingLayer::new("my_service", std::io::stdout, serde_json::ser::CompactFormatter); /// ``` pub fn new( service: &str, dst_writer: W, formatter: F, ) -> error_stack::Result<Self, ConfigError> { Self::new_with_implicit_entries(service, dst_writer, HashMap::new(), formatter) } /// Construct of `FormattingLayer with implicit default entries. pub fn new_with_implicit_entries( service: &str, dst_writer: W, default_fields: HashMap<String, Value>, formatter: F, ) -> error_stack::Result<Self, ConfigError> { let pid = std::process::id(); let hostname = gethostname::gethostname().to_string_lossy().into_owned(); let service = service.to_string(); #[cfg(feature = "vergen")] let version = crate::version!().to_string(); #[cfg(feature = "vergen")] let build = crate::build!().to_string(); let env = crate::env::which().to_string(); for key in default_fields.keys() { if IMPLICIT_KEYS.contains(key.as_str()) { return Err(ConfigError::Message(format!( "A reserved key `{key}` was included in `default_fields` in the log formatting layer" )) .into()); } } Ok(Self { dst_writer, pid, hostname, env, service, #[cfg(feature = "vergen")] version, #[cfg(feature = "vergen")] build, default_fields, formatter, }) } /// Serialize common for both span and event entries. fn common_serialize<S>( &self, map_serializer: &mut impl SerializeMap<Error = serde_json::Error>, metadata: &Metadata<'_>, span: Option<&SpanRef<'_, S>>, storage: &Storage<'_>, name: &str, ) -> Result<(), std::io::Error> where S: Subscriber + for<'a> LookupSpan<'a>, { let is_extra = |s: &str| !IMPLICIT_KEYS.contains(s); let is_extra_implicit = |s: &str| is_extra(s) && EXTRA_IMPLICIT_KEYS.contains(s); map_serializer.serialize_entry(HOSTNAME, &self.hostname)?; map_serializer.serialize_entry(PID, &self.pid)?; map_serializer.serialize_entry(ENV, &self.env)?; #[cfg(feature = "vergen")] map_serializer.serialize_entry(VERSION, &self.version)?; #[cfg(feature = "vergen")] map_serializer.serialize_entry(BUILD, &self.build)?; map_serializer.serialize_entry(LEVEL, &format_args!("{}", metadata.level()))?; map_serializer.serialize_entry(TARGET, metadata.target())?; map_serializer.serialize_entry(SERVICE, &self.service)?; map_serializer.serialize_entry(LINE, &metadata.line())?; map_serializer.serialize_entry(FILE, &metadata.file())?; map_serializer.serialize_entry(FN, name)?; map_serializer .serialize_entry(FULL_NAME, &format_args!("{}::{}", metadata.target(), name))?; if let Ok(time) = &time::OffsetDateTime::now_utc().format(&Iso8601::DEFAULT) { map_serializer.serialize_entry(TIME, time)?; } // Write down implicit default entries. for (key, value) in self.default_fields.iter() { map_serializer.serialize_entry(key, value)?; } #[cfg(feature = "log_custom_entries_to_extra")] let mut extra = serde_json::Map::default(); let mut explicit_entries_set: HashSet<&str> = HashSet::default(); // Write down explicit event's entries. for (key, value) in storage.values.iter() { if is_extra_implicit(key) { #[cfg(feature = "log_extra_implicit_fields")] map_serializer.serialize_entry(key, value)?; explicit_entries_set.insert(key); } else if is_extra(key) { #[cfg(feature = "log_custom_entries_to_extra")] extra.insert(key.to_string(), value.clone()); #[cfg(not(feature = "log_custom_entries_to_extra"))] map_serializer.serialize_entry(key, value)?; explicit_entries_set.insert(key); } else { tracing::warn!( ?key, ?value, "Attempting to log a reserved entry. It won't be added to the logs" ); } } // Write down entries from the span, if it exists. if let Some(span) = &span { let extensions = span.extensions(); if let Some(visitor) = extensions.get::<Storage<'_>>() { for (key, value) in &visitor.values { if is_extra_implicit(key) && !explicit_entries_set.contains(key) { #[cfg(feature = "log_extra_implicit_fields")] map_serializer.serialize_entry(key, value)?; } else if is_extra(key) && !explicit_entries_set.contains(key) { #[cfg(feature = "log_custom_entries_to_extra")] extra.insert(key.to_string(), value.clone()); #[cfg(not(feature = "log_custom_entries_to_extra"))] map_serializer.serialize_entry(key, value)?; } else { tracing::warn!( ?key, ?value, "Attempting to log a reserved entry. It won't be added to the logs" ); } } } } #[cfg(feature = "log_custom_entries_to_extra")] map_serializer.serialize_entry("extra", &extra)?; Ok(()) } /// Flush memory buffer into an output stream trailing it with next line. /// /// Should be done by single `write_all` call to avoid fragmentation of log because of mutlithreading. fn flush(&self, mut buffer: Vec<u8>) -> Result<(), std::io::Error> { buffer.write_all(b"\n")?; self.dst_writer.make_writer().write_all(&buffer) } /// Serialize entries of span. fn span_serialize<S>( &self, span: &SpanRef<'_, S>, ty: RecordType, ) -> Result<Vec<u8>, std::io::Error> where S: Subscriber + for<'a> LookupSpan<'a>, { let mut buffer = Vec::new(); let mut serializer = serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone()); let mut map_serializer = serializer.serialize_map(None)?; let message = Self::span_message(span, ty); let mut storage = Storage::default(); storage.record_value("message", message.into()); self.common_serialize( &mut map_serializer, span.metadata(), Some(span), &storage, span.name(), )?; map_serializer.end()?; Ok(buffer) } /// Serialize event into a buffer of bytes using parent span. pub fn event_serialize<S>( &self, span: Option<&SpanRef<'_, S>>, event: &Event<'_>, ) -> std::io::Result<Vec<u8>> where S: Subscriber + for<'a> LookupSpan<'a>, { let mut buffer = Vec::new(); let mut serializer = serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone()); let mut map_serializer = serializer.serialize_map(None)?; let mut storage = Storage::default(); event.record(&mut storage); let name = span.map_or("?", SpanRef::name); Self::event_message(span, event, &mut storage); self.common_serialize(&mut map_serializer, event.metadata(), span, &storage, name)?; map_serializer.end()?; Ok(buffer) } /// Format message of a span. /// /// Example: "[FN_WITHOUT_COLON - START]" fn span_message<S>(span: &SpanRef<'_, S>, ty: RecordType) -> String where S: Subscriber + for<'a> LookupSpan<'a>, { format!("[{} - {}]", span.metadata().name().to_uppercase(), ty) } /// Format message of an event. /// /// Examples: "[FN_WITHOUT_COLON - EVENT] Message" fn event_message<S>(span: Option<&SpanRef<'_, S>>, event: &Event<'_>, storage: &mut Storage<'_>) where S: Subscriber + for<'a> LookupSpan<'a>, { // Get value of kept "message" or "target" if does not exist. let message = storage .values .entry("message") .or_insert_with(|| event.metadata().target().into()); // Prepend the span name to the message if span exists. if let (Some(span), Value::String(a)) = (span, message) { *a = format!("{} {}", Self::span_message(span, RecordType::Event), a,); } } } #[allow(clippy::expect_used)] impl<S, W, F> Layer<S> for FormattingLayer<W, F> where S: Subscriber + for<'a> LookupSpan<'a>, W: for<'a> MakeWriter<'a> + 'static, F: Formatter + Clone + 'static, { fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) { // Event could have no span. let span = ctx.lookup_current(); let result: std::io::Result<Vec<u8>> = self.event_serialize(span.as_ref(), event); if let Ok(formatted) = result { let _ = self.flush(formatted); } } #[cfg(feature = "log_active_span_json")] fn on_enter(&self, id: &tracing::Id, ctx: Context<'_, S>) { let span = ctx.span(id).expect("No span"); if let Ok(serialized) = self.span_serialize(&span, RecordType::EnterSpan) { let _ = self.flush(serialized); } } #[cfg(not(feature = "log_active_span_json"))] fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) { let span = ctx.span(&id).expect("No span"); if span.parent().is_none() { if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) { let _ = self.flush(serialized); } } } #[cfg(feature = "log_active_span_json")] fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) { let span = ctx.span(&id).expect("No span"); if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) { let _ = self.flush(serialized); } } }
crates/router_env/src/logger/formatter.rs
router_env::src::logger::formatter
3,393
true
// File: crates/router_env/src/logger/storage.rs // Module: router_env::src::logger::storage //! Storing [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router. use std::{collections::HashMap, fmt, time::Instant}; use tracing::{ field::{Field, Visit}, span::{Attributes, Record}, Id, Subscriber, }; use tracing_subscriber::{layer::Context, Layer}; /// Storage to store key value pairs of spans. #[derive(Clone, Debug)] pub struct StorageSubscription; /// Storage to store key value pairs of spans. /// When new entry is crated it stores it in [HashMap] which is owned by `extensions`. #[derive(Clone, Debug)] pub struct Storage<'a> { /// Hash map to store values. pub values: HashMap<&'a str, serde_json::Value>, } impl<'a> Storage<'a> { /// Default constructor. pub fn new() -> Self { Self::default() } pub fn record_value(&mut self, key: &'a str, value: serde_json::Value) { if super::formatter::IMPLICIT_KEYS.contains(key) { tracing::warn!(value =? value, "{} is a reserved entry. Skipping it.", key); } else { self.values.insert(key, value); } } } /// Default constructor. impl Default for Storage<'_> { fn default() -> Self { Self { values: HashMap::new(), } } } /// Visitor to store entry. impl Visit for Storage<'_> { /// A i64. fn record_i64(&mut self, field: &Field, value: i64) { self.record_value(field.name(), serde_json::Value::from(value)); } /// A u64. fn record_u64(&mut self, field: &Field, value: u64) { self.record_value(field.name(), serde_json::Value::from(value)); } /// A 64-bit floating point. fn record_f64(&mut self, field: &Field, value: f64) { self.record_value(field.name(), serde_json::Value::from(value)); } /// A boolean. fn record_bool(&mut self, field: &Field, value: bool) { self.record_value(field.name(), serde_json::Value::from(value)); } /// A string. fn record_str(&mut self, field: &Field, value: &str) { self.record_value(field.name(), serde_json::Value::from(value)); } /// Otherwise. fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) { match field.name() { // Skip fields which are already handled name if name.starts_with("log.") => (), name if name.starts_with("r#") => { self.record_value( #[allow(clippy::expect_used)] name.get(2..) .expect("field name must have a minimum of two characters"), serde_json::Value::from(format!("{value:?}")), ); } name => { self.record_value(name, serde_json::Value::from(format!("{value:?}"))); } }; } } const PERSISTENT_KEYS: [&str; 6] = [ "payment_id", "connector_name", "merchant_id", "flow", "payment_method", "status_code", ]; impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer<S> for StorageSubscription { /// On new span. fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) { #[allow(clippy::expect_used)] let span = ctx.span(id).expect("No span"); let mut extensions = span.extensions_mut(); let mut visitor = if let Some(parent_span) = span.parent() { let mut extensions = parent_span.extensions_mut(); extensions .get_mut::<Storage<'_>>() .map(|v| v.to_owned()) .unwrap_or_default() } else { Storage::default() }; attrs.record(&mut visitor); extensions.insert(visitor); } /// On additional key value pairs store it. fn on_record(&self, span: &Id, values: &Record<'_>, ctx: Context<'_, S>) { #[allow(clippy::expect_used)] let span = ctx.span(span).expect("No span"); let mut extensions = span.extensions_mut(); #[allow(clippy::expect_used)] let visitor = extensions .get_mut::<Storage<'_>>() .expect("The span does not have storage"); values.record(visitor); } /// On enter store time. fn on_enter(&self, span: &Id, ctx: Context<'_, S>) { #[allow(clippy::expect_used)] let span = ctx.span(span).expect("No span"); let mut extensions = span.extensions_mut(); if extensions.get_mut::<Instant>().is_none() { extensions.insert(Instant::now()); } } /// On close create an entry about how long did it take. fn on_close(&self, span: Id, ctx: Context<'_, S>) { #[allow(clippy::expect_used)] let span = ctx.span(&span).expect("No span"); let elapsed_milliseconds = { let extensions = span.extensions(); extensions .get::<Instant>() .map(|i| i.elapsed().as_millis()) .unwrap_or(0) }; if let Some(s) = span.extensions().get::<Storage<'_>>() { s.values.iter().for_each(|(k, v)| { if PERSISTENT_KEYS.contains(k) { span.parent().and_then(|p| { p.extensions_mut() .get_mut::<Storage<'_>>() .map(|s| s.record_value(k, v.to_owned())) }); } }) }; let mut extensions_mut = span.extensions_mut(); #[allow(clippy::expect_used)] let visitor = extensions_mut .get_mut::<Storage<'_>>() .expect("No visitor in extensions"); if let Ok(elapsed) = serde_json::to_value(elapsed_milliseconds) { visitor.record_value("elapsed_milliseconds", elapsed); } } }
crates/router_env/src/logger/storage.rs
router_env::src::logger::storage
1,393
true
// File: crates/router_env/src/logger/defaults.rs // Module: router_env::src::logger::defaults impl Default for super::config::LogFile { fn default() -> Self { Self { enabled: true, path: "logs".into(), file_name: "debug.log".into(), level: super::config::Level(tracing::Level::DEBUG), filtering_directive: None, } } } impl Default for super::config::LogConsole { fn default() -> Self { Self { enabled: false, level: super::config::Level(tracing::Level::INFO), log_format: super::config::LogFormat::Json, filtering_directive: None, } } }
crates/router_env/src/logger/defaults.rs
router_env::src::logger::defaults
158
true
// File: crates/router_env/src/logger/setup.rs // Module: router_env::src::logger::setup //! Setup logging subsystem. use std::time::Duration; use ::config::ConfigError; use serde_json::ser::{CompactFormatter, PrettyFormatter}; use tracing_appender::non_blocking::WorkerGuard; use tracing_subscriber::{fmt, prelude::*, util::SubscriberInitExt, EnvFilter, Layer}; use crate::{config, FormattingLayer, StorageSubscription}; /// Contains guards necessary for logging and metrics collection. #[derive(Debug)] pub struct TelemetryGuard { _log_guards: Vec<WorkerGuard>, } /// Setup logging sub-system specifying the logging configuration, service (binary) name, and a /// list of external crates for which a more verbose logging must be enabled. All crates within the /// current cargo workspace are automatically considered for verbose logging. #[allow(clippy::print_stdout)] // The logger hasn't been initialized yet pub fn setup( config: &config::Log, service_name: &str, crates_to_filter: impl AsRef<[&'static str]>, ) -> error_stack::Result<TelemetryGuard, ConfigError> { let mut guards = Vec::new(); // Setup OpenTelemetry traces and metrics let traces_layer = if config.telemetry.traces_enabled { setup_tracing_pipeline(&config.telemetry, service_name) } else { None }; if config.telemetry.metrics_enabled { setup_metrics_pipeline(&config.telemetry) }; // Setup file logging let file_writer = if config.file.enabled { let mut path = crate::env::workspace_path(); // Using an absolute path for file log path would replace workspace path with absolute path, // which is the intended behavior for us. path.push(&config.file.path); let file_appender = tracing_appender::rolling::hourly(&path, &config.file.file_name); let (file_writer, guard) = tracing_appender::non_blocking(file_appender); guards.push(guard); let file_filter = get_envfilter( config.file.filtering_directive.as_ref(), config::Level(tracing::Level::WARN), config.file.level, &crates_to_filter, ); println!("Using file logging filter: {file_filter}"); let layer = FormattingLayer::new(service_name, file_writer, CompactFormatter)? .with_filter(file_filter); Some(layer) } else { None }; let subscriber = tracing_subscriber::registry() .with(traces_layer) .with(StorageSubscription) .with(file_writer); // Setup console logging if config.console.enabled { let (console_writer, guard) = tracing_appender::non_blocking(std::io::stdout()); guards.push(guard); let console_filter = get_envfilter( config.console.filtering_directive.as_ref(), config::Level(tracing::Level::WARN), config.console.level, &crates_to_filter, ); println!("Using console logging filter: {console_filter}"); match config.console.log_format { config::LogFormat::Default => { let logging_layer = fmt::layer() .with_timer(fmt::time::time()) .pretty() .with_writer(console_writer) .with_filter(console_filter); subscriber.with(logging_layer).init(); } config::LogFormat::Json => { error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None); subscriber .with( FormattingLayer::new(service_name, console_writer, CompactFormatter)? .with_filter(console_filter), ) .init(); } config::LogFormat::PrettyJson => { error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None); subscriber .with( FormattingLayer::new(service_name, console_writer, PrettyFormatter::new())? .with_filter(console_filter), ) .init(); } } } else { subscriber.init(); }; // Returning the TelemetryGuard for logs to be printed and metrics to be collected until it is // dropped Ok(TelemetryGuard { _log_guards: guards, }) } fn get_opentelemetry_exporter_config( config: &config::LogTelemetry, ) -> opentelemetry_otlp::ExportConfig { let mut exporter_config = opentelemetry_otlp::ExportConfig { protocol: opentelemetry_otlp::Protocol::Grpc, endpoint: config.otel_exporter_otlp_endpoint.clone(), ..Default::default() }; if let Some(timeout) = config.otel_exporter_otlp_timeout { exporter_config.timeout = Duration::from_millis(timeout); } exporter_config } #[derive(Debug, Clone)] enum TraceUrlAssert { Match(String), EndsWith(String), } impl TraceUrlAssert { fn compare_url(&self, url: &str) -> bool { match self { Self::Match(value) => url == value, Self::EndsWith(end) => url.ends_with(end), } } } impl From<String> for TraceUrlAssert { fn from(value: String) -> Self { match value { url if url.starts_with('*') => Self::EndsWith(url.trim_start_matches('*').to_string()), url => Self::Match(url), } } } #[derive(Debug, Clone)] struct TraceAssertion { clauses: Option<Vec<TraceUrlAssert>>, /// default behaviour for tracing if no condition is provided default: bool, } impl TraceAssertion { /// Should the provided url be traced fn should_trace_url(&self, url: &str) -> bool { match &self.clauses { Some(clauses) => clauses.iter().all(|cur| cur.compare_url(url)), None => self.default, } } } /// Conditional Sampler for providing control on url based tracing #[derive(Clone, Debug)] struct ConditionalSampler<T: opentelemetry_sdk::trace::ShouldSample + Clone + 'static>( TraceAssertion, T, ); impl<T: opentelemetry_sdk::trace::ShouldSample + Clone + 'static> opentelemetry_sdk::trace::ShouldSample for ConditionalSampler<T> { fn should_sample( &self, parent_context: Option<&opentelemetry::Context>, trace_id: opentelemetry::trace::TraceId, name: &str, span_kind: &opentelemetry::trace::SpanKind, attributes: &[opentelemetry::KeyValue], links: &[opentelemetry::trace::Link], ) -> opentelemetry::trace::SamplingResult { use opentelemetry::trace::TraceContextExt; match attributes .iter() .find(|&kv| kv.key == opentelemetry::Key::new("http.route")) .map_or(self.0.default, |inner| { self.0.should_trace_url(&inner.value.as_str()) }) { true => { self.1 .should_sample(parent_context, trace_id, name, span_kind, attributes, links) } false => opentelemetry::trace::SamplingResult { decision: opentelemetry::trace::SamplingDecision::Drop, attributes: Vec::new(), trace_state: match parent_context { Some(ctx) => ctx.span().span_context().trace_state().clone(), None => opentelemetry::trace::TraceState::default(), }, }, } } } fn setup_tracing_pipeline( config: &config::LogTelemetry, service_name: &str, ) -> Option< tracing_opentelemetry::OpenTelemetryLayer< tracing_subscriber::Registry, opentelemetry_sdk::trace::Tracer, >, > { use opentelemetry::trace::TracerProvider; use opentelemetry_otlp::WithExportConfig; use opentelemetry_sdk::trace; opentelemetry::global::set_text_map_propagator( opentelemetry_sdk::propagation::TraceContextPropagator::new(), ); // Set the export interval to 1 second let batch_config = trace::BatchConfigBuilder::default() .with_scheduled_delay(Duration::from_millis(1000)) .build(); let exporter_result = opentelemetry_otlp::SpanExporter::builder() .with_tonic() .with_export_config(get_opentelemetry_exporter_config(config)) .build(); let exporter = if config.ignore_errors { #[allow(clippy::print_stderr)] // The logger hasn't been initialized yet exporter_result .inspect_err(|error| eprintln!("Failed to build traces exporter: {error:?}")) .ok()? } else { // Safety: This is conditional, there is an option to avoid this behavior at runtime. #[allow(clippy::expect_used)] exporter_result.expect("Failed to build traces exporter") }; let mut provider_builder = trace::TracerProvider::builder() .with_span_processor( trace::BatchSpanProcessor::builder( exporter, // The runtime would have to be updated if a different web framework is used opentelemetry_sdk::runtime::TokioCurrentThread, ) .with_batch_config(batch_config) .build(), ) .with_sampler(trace::Sampler::ParentBased(Box::new(ConditionalSampler( TraceAssertion { clauses: config .route_to_trace .clone() .map(|inner| inner.into_iter().map(TraceUrlAssert::from).collect()), default: false, }, trace::Sampler::TraceIdRatioBased(config.sampling_rate.unwrap_or(1.0)), )))) .with_resource(opentelemetry_sdk::Resource::new(vec![ opentelemetry::KeyValue::new("service.name", service_name.to_owned()), ])); if config.use_xray_generator { provider_builder = provider_builder .with_id_generator(opentelemetry_aws::trace::XrayIdGenerator::default()); } Some( tracing_opentelemetry::layer() .with_tracer(provider_builder.build().tracer(service_name.to_owned())), ) } fn setup_metrics_pipeline(config: &config::LogTelemetry) { use opentelemetry_otlp::WithExportConfig; let exporter_result = opentelemetry_otlp::MetricExporter::builder() .with_tonic() .with_temporality(opentelemetry_sdk::metrics::Temporality::Cumulative) .with_export_config(get_opentelemetry_exporter_config(config)) .build(); let exporter = if config.ignore_errors { #[allow(clippy::print_stderr)] // The logger hasn't been initialized yet exporter_result .inspect_err(|error| eprintln!("Failed to build metrics exporter: {error:?}")) .ok(); return; } else { // Safety: This is conditional, there is an option to avoid this behavior at runtime. #[allow(clippy::expect_used)] exporter_result.expect("Failed to build metrics exporter") }; let reader = opentelemetry_sdk::metrics::PeriodicReader::builder( exporter, // The runtime would have to be updated if a different web framework is used opentelemetry_sdk::runtime::TokioCurrentThread, ) .with_interval(Duration::from_secs(3)) .with_timeout(Duration::from_secs(10)) .build(); let provider = opentelemetry_sdk::metrics::SdkMeterProvider::builder() .with_reader(reader) .with_resource(opentelemetry_sdk::Resource::new([ opentelemetry::KeyValue::new( "pod", std::env::var("POD_NAME").unwrap_or(String::from("hyperswitch-server-default")), ), ])) .build(); opentelemetry::global::set_meter_provider(provider); } fn get_envfilter( filtering_directive: Option<&String>, default_log_level: config::Level, filter_log_level: config::Level, crates_to_filter: impl AsRef<[&'static str]>, ) -> EnvFilter { filtering_directive .map(|filter| { // Try to create target filter from specified filtering directive, if set // Safety: If user is overriding the default filtering directive, then we need to panic // for invalid directives. #[allow(clippy::expect_used)] EnvFilter::builder() .with_default_directive(default_log_level.into_level().into()) .parse(filter) .expect("Invalid EnvFilter filtering directive") }) .unwrap_or_else(|| { // Construct a default target filter otherwise let mut workspace_members = crate::cargo_workspace_members!(); workspace_members.extend(crates_to_filter.as_ref()); workspace_members .drain() .zip(std::iter::repeat(filter_log_level.into_level())) .fold( EnvFilter::default().add_directive(default_log_level.into_level().into()), |env_filter, (target, level)| { // Safety: This is a hardcoded basic filtering directive. If even the basic // filter is wrong, it's better to panic. #[allow(clippy::expect_used)] env_filter.add_directive( format!("{target}={level}") .parse() .expect("Invalid EnvFilter directive format"), ) }, ) }) }
crates/router_env/src/logger/setup.rs
router_env::src::logger::setup
2,860
true
// File: crates/redis_interface/src/types.rs // Module: redis_interface::src::types //! Data types and type conversions //! from `fred`'s internal data-types to custom data-types use common_utils::errors::CustomResult; use fred::types::RedisValue as FredRedisValue; use crate::{errors, RedisConnectionPool}; pub struct RedisValue { inner: FredRedisValue, } impl std::ops::Deref for RedisValue { type Target = FredRedisValue; fn deref(&self) -> &Self::Target { &self.inner } } impl RedisValue { pub fn new(value: FredRedisValue) -> Self { Self { inner: value } } pub fn into_inner(self) -> FredRedisValue { self.inner } pub fn from_bytes(val: Vec<u8>) -> Self { Self { inner: FredRedisValue::Bytes(val.into()), } } pub fn from_string(value: String) -> Self { Self { inner: FredRedisValue::String(value.into()), } } } impl From<RedisValue> for FredRedisValue { fn from(v: RedisValue) -> Self { v.inner } } #[derive(Debug, serde::Deserialize, Clone)] #[serde(default)] pub struct RedisSettings { pub host: String, pub port: u16, pub cluster_enabled: bool, pub cluster_urls: Vec<String>, pub use_legacy_version: bool, pub pool_size: usize, pub reconnect_max_attempts: u32, /// Reconnect delay in milliseconds pub reconnect_delay: u32, /// TTL in seconds pub default_ttl: u32, /// TTL for hash-tables in seconds pub default_hash_ttl: u32, pub stream_read_count: u64, pub auto_pipeline: bool, pub disable_auto_backpressure: bool, pub max_in_flight_commands: u64, pub default_command_timeout: u64, pub max_feed_count: u64, pub unresponsive_timeout: u64, } impl RedisSettings { /// Validates the Redis configuration provided. pub fn validate(&self) -> CustomResult<(), errors::RedisError> { use common_utils::{ext_traits::ConfigExt, fp_utils::when}; when(self.host.is_default_or_empty(), || { Err(errors::RedisError::InvalidConfiguration( "Redis `host` must be specified".into(), )) })?; when(self.cluster_enabled && self.cluster_urls.is_empty(), || { Err(errors::RedisError::InvalidConfiguration( "Redis `cluster_urls` must be specified if `cluster_enabled` is `true`".into(), )) })?; when( self.default_command_timeout < self.unresponsive_timeout, || { Err(errors::RedisError::InvalidConfiguration( "Unresponsive timeout cannot be greater than the command timeout".into(), ) .into()) }, ) } } impl Default for RedisSettings { fn default() -> Self { Self { host: "127.0.0.1".to_string(), port: 6379, cluster_enabled: false, cluster_urls: vec![], use_legacy_version: false, pool_size: 5, reconnect_max_attempts: 5, reconnect_delay: 5, default_ttl: 300, stream_read_count: 1, default_hash_ttl: 900, auto_pipeline: true, disable_auto_backpressure: false, max_in_flight_commands: 5000, default_command_timeout: 30, max_feed_count: 200, unresponsive_timeout: 10, } } } #[derive(Debug)] pub enum RedisEntryId { UserSpecifiedID { milliseconds: String, sequence_number: String, }, AutoGeneratedID, AfterLastID, /// Applicable only with consumer groups UndeliveredEntryID, } impl From<RedisEntryId> for fred::types::XID { fn from(id: RedisEntryId) -> Self { match id { RedisEntryId::UserSpecifiedID { milliseconds, sequence_number, } => Self::Manual(fred::bytes_utils::format_bytes!( "{milliseconds}-{sequence_number}" )), RedisEntryId::AutoGeneratedID => Self::Auto, RedisEntryId::AfterLastID => Self::Max, RedisEntryId::UndeliveredEntryID => Self::NewInGroup, } } } impl From<&RedisEntryId> for fred::types::XID { fn from(id: &RedisEntryId) -> Self { match id { RedisEntryId::UserSpecifiedID { milliseconds, sequence_number, } => Self::Manual(fred::bytes_utils::format_bytes!( "{milliseconds}-{sequence_number}" )), RedisEntryId::AutoGeneratedID => Self::Auto, RedisEntryId::AfterLastID => Self::Max, RedisEntryId::UndeliveredEntryID => Self::NewInGroup, } } } #[derive(Eq, PartialEq)] pub enum SetnxReply { KeySet, KeyNotSet, // Existing key } impl fred::types::FromRedis for SetnxReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { // Returns String ( "OK" ) in case of success fred::types::RedisValue::String(_) => Ok(Self::KeySet), // Return Null in case of failure fred::types::RedisValue::Null => Ok(Self::KeyNotSet), // Unexpected behaviour _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected SETNX command reply", )), } } } #[derive(Eq, PartialEq)] pub enum HsetnxReply { KeySet, KeyNotSet, // Existing key } impl fred::types::FromRedis for HsetnxReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeySet), fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected HSETNX command reply", )), } } } #[derive(Eq, PartialEq)] pub enum MsetnxReply { KeysSet, KeysNotSet, // At least one existing key } impl fred::types::FromRedis for MsetnxReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeysSet), fred::types::RedisValue::Integer(0) => Ok(Self::KeysNotSet), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected MSETNX command reply", )), } } } #[derive(Debug)] pub enum StreamCapKind { MinID, MaxLen, } impl From<StreamCapKind> for fred::types::XCapKind { fn from(item: StreamCapKind) -> Self { match item { StreamCapKind::MaxLen => Self::MaxLen, StreamCapKind::MinID => Self::MinID, } } } #[derive(Debug)] pub enum StreamCapTrim { Exact, AlmostExact, } impl From<StreamCapTrim> for fred::types::XCapTrim { fn from(item: StreamCapTrim) -> Self { match item { StreamCapTrim::Exact => Self::Exact, StreamCapTrim::AlmostExact => Self::AlmostExact, } } } #[derive(Debug)] pub enum DelReply { KeyDeleted, KeyNotDeleted, // Key not found } impl DelReply { pub fn is_key_deleted(&self) -> bool { matches!(self, Self::KeyDeleted) } pub fn is_key_not_deleted(&self) -> bool { matches!(self, Self::KeyNotDeleted) } } impl fred::types::FromRedis for DelReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeyDeleted), fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotDeleted), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected del command reply", )), } } } #[derive(Debug)] pub enum SaddReply { KeySet, KeyNotSet, } impl fred::types::FromRedis for SaddReply { fn from_value(value: fred::types::RedisValue) -> Result<Self, fred::error::RedisError> { match value { fred::types::RedisValue::Integer(1) => Ok(Self::KeySet), fred::types::RedisValue::Integer(0) => Ok(Self::KeyNotSet), _ => Err(fred::error::RedisError::new( fred::error::RedisErrorKind::Unknown, "Unexpected sadd command reply", )), } } } #[derive(Debug)] pub enum SetGetReply<T> { ValueSet(T), // Value was set and this is the value that was set ValueExists(T), // Value already existed and this is the existing value } impl<T> SetGetReply<T> { pub fn get_value(&self) -> &T { match self { Self::ValueSet(value) => value, Self::ValueExists(value) => value, } } } #[derive(Debug)] pub struct RedisKey(String); impl RedisKey { pub fn tenant_aware_key(&self, pool: &RedisConnectionPool) -> String { pool.add_prefix(&self.0) } pub fn tenant_unaware_key(&self, _pool: &RedisConnectionPool) -> String { self.0.clone() } } impl<T: AsRef<str>> From<T> for RedisKey { fn from(value: T) -> Self { let value = value.as_ref(); Self(value.to_string()) } }
crates/redis_interface/src/types.rs
redis_interface::src::types
2,294
true
// File: crates/redis_interface/src/lib.rs // Module: redis_interface::src::lib //! Intermediate module for encapsulate all the redis related functionality //! //! Provides structs to represent redis connection and all functions that redis provides and //! are used in the `router` crate. Abstractions for creating a new connection while also facilitating //! redis connection pool and configuration based types. //! //! # Examples //! ``` //! use redis_interface::{types::RedisSettings, RedisConnectionPool}; //! //! #[tokio::main] //! async fn main() { //! let redis_conn = RedisConnectionPool::new(&RedisSettings::default()).await; //! // ... redis_conn ready to use //! } //! ``` pub mod commands; pub mod errors; pub mod types; use std::sync::{atomic, Arc}; use common_utils::errors::CustomResult; use error_stack::ResultExt; pub use fred::interfaces::PubsubInterface; use fred::{ clients::Transaction, interfaces::ClientLike, prelude::{EventInterface, TransactionInterface}, }; pub use self::types::*; pub struct RedisConnectionPool { pub pool: Arc<fred::prelude::RedisPool>, pub key_prefix: String, pub config: Arc<RedisConfig>, pub subscriber: Arc<SubscriberClient>, pub publisher: Arc<RedisClient>, pub is_redis_available: Arc<atomic::AtomicBool>, } pub struct RedisClient { inner: fred::prelude::RedisClient, } impl std::ops::Deref for RedisClient { type Target = fred::prelude::RedisClient; fn deref(&self) -> &Self::Target { &self.inner } } impl RedisClient { pub async fn new( config: fred::types::RedisConfig, reconnect_policy: fred::types::ReconnectPolicy, perf: fred::types::PerformanceConfig, ) -> CustomResult<Self, errors::RedisError> { let client = fred::prelude::RedisClient::new(config, Some(perf), None, Some(reconnect_policy)); client.connect(); client .wait_for_connect() .await .change_context(errors::RedisError::RedisConnectionError)?; Ok(Self { inner: client }) } } pub struct SubscriberClient { inner: fred::clients::SubscriberClient, pub is_subscriber_handler_spawned: Arc<atomic::AtomicBool>, } impl SubscriberClient { pub async fn new( config: fred::types::RedisConfig, reconnect_policy: fred::types::ReconnectPolicy, perf: fred::types::PerformanceConfig, ) -> CustomResult<Self, errors::RedisError> { let client = fred::clients::SubscriberClient::new(config, Some(perf), None, Some(reconnect_policy)); client.connect(); client .wait_for_connect() .await .change_context(errors::RedisError::RedisConnectionError)?; Ok(Self { inner: client, is_subscriber_handler_spawned: Arc::new(atomic::AtomicBool::new(false)), }) } } impl std::ops::Deref for SubscriberClient { type Target = fred::clients::SubscriberClient; fn deref(&self) -> &Self::Target { &self.inner } } impl RedisConnectionPool { /// Create a new Redis connection pub async fn new(conf: &RedisSettings) -> CustomResult<Self, errors::RedisError> { let redis_connection_url = match conf.cluster_enabled { // Fred relies on this format for specifying cluster where the host port is ignored & only query parameters are used for node addresses // redis-cluster://username:password@host:port?node=bar.com:30002&node=baz.com:30003 true => format!( "redis-cluster://{}:{}?{}", conf.host, conf.port, conf.cluster_urls .iter() .flat_map(|url| vec!["&", url]) .skip(1) .collect::<String>() ), false => format!( "redis://{}:{}", //URI Schema conf.host, conf.port, ), }; let mut config = fred::types::RedisConfig::from_url(&redis_connection_url) .change_context(errors::RedisError::RedisConnectionError)?; let perf = fred::types::PerformanceConfig { auto_pipeline: conf.auto_pipeline, default_command_timeout: std::time::Duration::from_secs(conf.default_command_timeout), max_feed_count: conf.max_feed_count, backpressure: fred::types::BackpressureConfig { disable_auto_backpressure: conf.disable_auto_backpressure, max_in_flight_commands: conf.max_in_flight_commands, policy: fred::types::BackpressurePolicy::Drain, }, }; let connection_config = fred::types::ConnectionConfig { unresponsive_timeout: std::time::Duration::from_secs(conf.unresponsive_timeout), ..fred::types::ConnectionConfig::default() }; if !conf.use_legacy_version { config.version = fred::types::RespVersion::RESP3; } config.tracing = fred::types::TracingConfig::new(true); config.blocking = fred::types::Blocking::Error; let reconnect_policy = fred::types::ReconnectPolicy::new_constant( conf.reconnect_max_attempts, conf.reconnect_delay, ); let subscriber = SubscriberClient::new(config.clone(), reconnect_policy.clone(), perf.clone()).await?; let publisher = RedisClient::new(config.clone(), reconnect_policy.clone(), perf.clone()).await?; let pool = fred::prelude::RedisPool::new( config, Some(perf), Some(connection_config), Some(reconnect_policy), conf.pool_size, ) .change_context(errors::RedisError::RedisConnectionError)?; pool.connect(); pool.wait_for_connect() .await .change_context(errors::RedisError::RedisConnectionError)?; let config = RedisConfig::from(conf); Ok(Self { pool: Arc::new(pool), config: Arc::new(config), is_redis_available: Arc::new(atomic::AtomicBool::new(true)), subscriber: Arc::new(subscriber), publisher: Arc::new(publisher), key_prefix: String::default(), }) } pub fn clone(&self, key_prefix: &str) -> Self { Self { pool: Arc::clone(&self.pool), key_prefix: key_prefix.to_string(), config: Arc::clone(&self.config), subscriber: Arc::clone(&self.subscriber), publisher: Arc::clone(&self.publisher), is_redis_available: Arc::clone(&self.is_redis_available), } } pub async fn on_error(&self, tx: tokio::sync::oneshot::Sender<()>) { use futures::StreamExt; use tokio_stream::wrappers::BroadcastStream; let error_rxs: Vec<BroadcastStream<fred::error::RedisError>> = self .pool .clients() .iter() .map(|client| BroadcastStream::new(client.error_rx())) .collect(); let mut error_rx = futures::stream::select_all(error_rxs); loop { if let Some(Ok(error)) = error_rx.next().await { tracing::error!(?error, "Redis protocol or connection error"); if self.pool.state() == fred::types::ClientState::Disconnected { if tx.send(()).is_err() { tracing::error!("The redis shutdown signal sender failed to signal"); } self.is_redis_available .store(false, atomic::Ordering::SeqCst); break; } } } } pub async fn on_unresponsive(&self) { let _ = self.pool.clients().iter().map(|client| { client.on_unresponsive(|server| { tracing::warn!(redis_server =?server.host, "Redis server is unresponsive"); Ok(()) }) }); } pub fn get_transaction(&self) -> Transaction { self.pool.next().multi() } } pub struct RedisConfig { default_ttl: u32, default_stream_read_count: u64, default_hash_ttl: u32, cluster_enabled: bool, } impl From<&RedisSettings> for RedisConfig { fn from(config: &RedisSettings) -> Self { Self { default_ttl: config.default_ttl, default_stream_read_count: config.stream_read_count, default_hash_ttl: config.default_hash_ttl, cluster_enabled: config.cluster_enabled, } } } #[cfg(test)] mod test { use super::*; #[test] fn test_redis_error() { let x = errors::RedisError::ConsumerGroupClaimFailed.to_string(); assert_eq!(x, "Failed to set Redis stream message owner".to_string()) } }
crates/redis_interface/src/lib.rs
redis_interface::src::lib
1,904
true
// File: crates/redis_interface/src/commands.rs // Module: redis_interface::src::commands //! An interface to abstract the `fred` commands //! //! The folder provides generic functions for providing serialization //! and deserialization while calling redis. //! It also includes instruments to provide tracing. use std::fmt::Debug; use common_utils::{ errors::CustomResult, ext_traits::{AsyncExt, ByteSliceExt, Encode, StringExt}, fp_utils, }; use error_stack::{report, ResultExt}; use fred::{ interfaces::{HashesInterface, KeysInterface, ListInterface, SetsInterface, StreamsInterface}, prelude::{LuaInterface, RedisErrorKind}, types::{ Expiration, FromRedis, MultipleIDs, MultipleKeys, MultipleOrderedPairs, MultipleStrings, MultipleValues, RedisMap, RedisValue, ScanType, Scanner, SetOptions, XCap, XReadResponse, }, }; use futures::StreamExt; use tracing::instrument; use crate::{ errors, types::{ DelReply, HsetnxReply, MsetnxReply, RedisEntryId, RedisKey, SaddReply, SetGetReply, SetnxReply, }, }; impl super::RedisConnectionPool { pub fn add_prefix(&self, key: &str) -> String { if self.key_prefix.is_empty() { key.to_string() } else { format!("{}:{}", self.key_prefix, key) } } #[instrument(level = "DEBUG", skip(self))] pub async fn set_key<V>(&self, key: &RedisKey, value: V) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .set( key.tenant_aware_key(self), value, Some(Expiration::EX(self.config.default_ttl.into())), None, false, ) .await .change_context(errors::RedisError::SetFailed) } pub async fn set_key_without_modifying_ttl<V>( &self, key: &RedisKey, value: V, ) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .set( key.tenant_aware_key(self), value, Some(Expiration::KEEPTTL), None, false, ) .await .change_context(errors::RedisError::SetFailed) } pub async fn set_multiple_keys_if_not_exist<V>( &self, value: V, ) -> CustomResult<MsetnxReply, errors::RedisError> where V: TryInto<RedisMap> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .msetnx(value) .await .change_context(errors::RedisError::SetFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key_if_not_exist<V>( &self, key: &RedisKey, value: V, ttl: Option<i64>, ) -> CustomResult<SetnxReply, errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_key_if_not_exists_with_expiry(key, serialized.as_slice(), ttl) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key<V>( &self, key: &RedisKey, value: V, ) -> CustomResult<(), errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_key(key, serialized.as_slice()).await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key_without_modifying_ttl<V>( &self, key: &RedisKey, value: V, ) -> CustomResult<(), errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_key_without_modifying_ttl(key, serialized.as_slice()) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key_with_expiry<V>( &self, key: &RedisKey, value: V, seconds: i64, ) -> CustomResult<(), errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.pool .set( key.tenant_aware_key(self), serialized.as_slice(), Some(Expiration::EX(seconds)), None, false, ) .await .change_context(errors::RedisError::SetExFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_key<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { match self .pool .get(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } #[cfg(feature = "multitenancy_fallback")] { self.pool .get(key.tenant_unaware_key(self)) .await .change_context(errors::RedisError::GetFailed) } } } } #[instrument(level = "DEBUG", skip(self))] async fn get_multiple_keys_with_mget<V>( &self, keys: &[RedisKey], ) -> CustomResult<Vec<Option<V>>, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { if keys.is_empty() { return Ok(Vec::new()); } let tenant_aware_keys: Vec<String> = keys.iter().map(|key| key.tenant_aware_key(self)).collect(); self.pool .mget(tenant_aware_keys) .await .change_context(errors::RedisError::GetFailed) } #[instrument(level = "DEBUG", skip(self))] async fn get_multiple_keys_with_parallel_get<V>( &self, keys: &[RedisKey], ) -> CustomResult<Vec<Option<V>>, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { if keys.is_empty() { return Ok(Vec::new()); } let tenant_aware_keys: Vec<String> = keys.iter().map(|key| key.tenant_aware_key(self)).collect(); let futures = tenant_aware_keys .iter() .map(|redis_key| self.pool.get::<Option<V>, _>(redis_key)); let results = futures::future::try_join_all(futures) .await .change_context(errors::RedisError::GetFailed) .attach_printable("Failed to get keys in cluster mode")?; Ok(results) } /// Helper method to encapsulate the logic for choosing between cluster and non-cluster modes #[instrument(level = "DEBUG", skip(self))] async fn get_keys_by_mode<V>( &self, keys: &[RedisKey], ) -> CustomResult<Vec<Option<V>>, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { if self.config.cluster_enabled { // Use individual GET commands for cluster mode to avoid CROSSSLOT errors self.get_multiple_keys_with_parallel_get(keys).await } else { // Use MGET for non-cluster mode for better performance self.get_multiple_keys_with_mget(keys).await } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_multiple_keys<V>( &self, keys: &[RedisKey], ) -> CustomResult<Vec<Option<V>>, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { if keys.is_empty() { return Ok(Vec::new()); } match self.get_keys_by_mode(keys).await { Ok(values) => Ok(values), Err(_err) => { #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } #[cfg(feature = "multitenancy_fallback")] { let tenant_unaware_keys: Vec<RedisKey> = keys .iter() .map(|key| key.tenant_unaware_key(self).into()) .collect(); self.get_keys_by_mode(&tenant_unaware_keys).await } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn exists<V>(&self, key: &RedisKey) -> CustomResult<bool, errors::RedisError> where V: Into<MultipleKeys> + Unpin + Send + 'static, { match self .pool .exists(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } #[cfg(feature = "multitenancy_fallback")] { self.pool .exists(key.tenant_unaware_key(self)) .await .change_context(errors::RedisError::GetFailed) } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_and_deserialize_key<T>( &self, key: &RedisKey, type_name: &'static str, ) -> CustomResult<T, errors::RedisError> where T: serde::de::DeserializeOwned, { let value_bytes = self.get_key::<Vec<u8>>(key).await?; fp_utils::when(value_bytes.is_empty(), || Err(errors::RedisError::NotFound))?; value_bytes .parse_struct(type_name) .change_context(errors::RedisError::JsonDeserializationFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_and_deserialize_multiple_keys<T>( &self, keys: &[RedisKey], type_name: &'static str, ) -> CustomResult<Vec<Option<T>>, errors::RedisError> where T: serde::de::DeserializeOwned, { let value_bytes_vec = self.get_multiple_keys::<Vec<u8>>(keys).await?; let mut results = Vec::with_capacity(value_bytes_vec.len()); for value_bytes_opt in value_bytes_vec { match value_bytes_opt { Some(value_bytes) => { if value_bytes.is_empty() { results.push(None); } else { let parsed = value_bytes .parse_struct(type_name) .change_context(errors::RedisError::JsonDeserializationFailed)?; results.push(Some(parsed)); } } None => results.push(None), } } Ok(results) } #[instrument(level = "DEBUG", skip(self))] pub async fn delete_key(&self, key: &RedisKey) -> CustomResult<DelReply, errors::RedisError> { match self .pool .del(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::DeleteFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } #[cfg(feature = "multitenancy_fallback")] { self.pool .del(key.tenant_unaware_key(self)) .await .change_context(errors::RedisError::DeleteFailed) } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn delete_multiple_keys( &self, keys: &[RedisKey], ) -> CustomResult<Vec<DelReply>, errors::RedisError> { let futures = keys.iter().map(|key| self.delete_key(key)); let del_result = futures::future::try_join_all(futures) .await .change_context(errors::RedisError::DeleteFailed)?; Ok(del_result) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_key_with_expiry<V>( &self, key: &RedisKey, value: V, seconds: i64, ) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .set( key.tenant_aware_key(self), value, Some(Expiration::EX(seconds)), None, false, ) .await .change_context(errors::RedisError::SetExFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_key_if_not_exists_with_expiry<V>( &self, key: &RedisKey, value: V, seconds: Option<i64>, ) -> CustomResult<SetnxReply, errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .set( key.tenant_aware_key(self), value, Some(Expiration::EX( seconds.unwrap_or(self.config.default_ttl.into()), )), Some(SetOptions::NX), false, ) .await .change_context(errors::RedisError::SetFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_expiry( &self, key: &RedisKey, seconds: i64, ) -> CustomResult<(), errors::RedisError> { self.pool .expire(key.tenant_aware_key(self), seconds) .await .change_context(errors::RedisError::SetExpiryFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_expire_at( &self, key: &RedisKey, timestamp: i64, ) -> CustomResult<(), errors::RedisError> { self.pool .expire_at(key.tenant_aware_key(self), timestamp) .await .change_context(errors::RedisError::SetExpiryFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_ttl(&self, key: &RedisKey) -> CustomResult<i64, errors::RedisError> { self.pool .ttl(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_hash_fields<V>( &self, key: &RedisKey, values: V, ttl: Option<i64>, ) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisMap> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { let output: Result<(), _> = self .pool .hset(key.tenant_aware_key(self), values) .await .change_context(errors::RedisError::SetHashFailed); // setting expiry for the key output .async_and_then(|_| { self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl.into())) }) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn set_hash_field_if_not_exist<V>( &self, key: &RedisKey, field: &str, value: V, ttl: Option<u32>, ) -> CustomResult<HsetnxReply, errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { let output: Result<HsetnxReply, _> = self .pool .hsetnx(key.tenant_aware_key(self), field, value) .await .change_context(errors::RedisError::SetHashFieldFailed); output .async_and_then(|inner| async { self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl).into()) .await?; Ok(inner) }) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_hash_field_if_not_exist<V>( &self, key: &RedisKey, field: &str, value: V, ttl: Option<u32>, ) -> CustomResult<HsetnxReply, errors::RedisError> where V: serde::Serialize + Debug, { let serialized = value .encode_to_vec() .change_context(errors::RedisError::JsonSerializationFailed)?; self.set_hash_field_if_not_exist(key, field, serialized.as_slice(), ttl) .await } #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_multiple_hash_field_if_not_exist<V>( &self, kv: &[(&RedisKey, V)], field: &str, ttl: Option<u32>, ) -> CustomResult<Vec<HsetnxReply>, errors::RedisError> where V: serde::Serialize + Debug, { let mut hsetnx: Vec<HsetnxReply> = Vec::with_capacity(kv.len()); for (key, val) in kv { hsetnx.push( self.serialize_and_set_hash_field_if_not_exist(key, field, val, ttl) .await?, ); } Ok(hsetnx) } #[instrument(level = "DEBUG", skip(self))] pub async fn increment_fields_in_hash<T>( &self, key: &RedisKey, fields_to_increment: &[(T, i64)], ) -> CustomResult<Vec<usize>, errors::RedisError> where T: Debug + ToString, { let mut values_after_increment = Vec::with_capacity(fields_to_increment.len()); for (field, increment) in fields_to_increment.iter() { values_after_increment.push( self.pool .hincrby(key.tenant_aware_key(self), field.to_string(), *increment) .await .change_context(errors::RedisError::IncrementHashFieldFailed)?, ) } Ok(values_after_increment) } #[instrument(level = "DEBUG", skip(self))] pub async fn hscan( &self, key: &RedisKey, pattern: &str, count: Option<u32>, ) -> CustomResult<Vec<String>, errors::RedisError> { Ok(self .pool .next() .hscan::<&str, &str>(&key.tenant_aware_key(self), pattern, count) .filter_map(|value| async move { match value { Ok(mut v) => { let v = v.take_results()?; let v: Vec<String> = v.iter().filter_map(|(_, val)| val.as_string()).collect(); Some(futures::stream::iter(v)) } Err(err) => { tracing::error!(redis_err=?err, "Redis error while executing hscan command"); None } } }) .flatten() .collect::<Vec<_>>() .await) } #[instrument(level = "DEBUG", skip(self))] pub async fn scan( &self, pattern: &RedisKey, count: Option<u32>, scan_type: Option<ScanType>, ) -> CustomResult<Vec<String>, errors::RedisError> { Ok(self .pool .next() .scan(pattern.tenant_aware_key(self), count, scan_type) .filter_map(|value| async move { match value { Ok(mut v) => { let v = v.take_results()?; let v: Vec<String> = v.into_iter().filter_map(|val| val.into_string()).collect(); Some(futures::stream::iter(v)) } Err(err) => { tracing::error!(redis_err=?err, "Redis error while executing scan command"); None } } }) .flatten() .collect::<Vec<_>>() .await) } #[instrument(level = "DEBUG", skip(self))] pub async fn hscan_and_deserialize<T>( &self, key: &RedisKey, pattern: &str, count: Option<u32>, ) -> CustomResult<Vec<T>, errors::RedisError> where T: serde::de::DeserializeOwned, { let redis_results = self.hscan(key, pattern, count).await?; Ok(redis_results .iter() .filter_map(|v| { let r: T = v.parse_struct(std::any::type_name::<T>()).ok()?; Some(r) }) .collect()) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_hash_field<V>( &self, key: &RedisKey, field: &str, ) -> CustomResult<V, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { match self .pool .hget(key.tenant_aware_key(self), field) .await .change_context(errors::RedisError::GetHashFieldFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(feature = "multitenancy_fallback")] { self.pool .hget(key.tenant_unaware_key(self), field) .await .change_context(errors::RedisError::GetHashFieldFailed) } #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_hash_fields<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { match self .pool .hgetall(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetHashFieldFailed) { Ok(v) => Ok(v), Err(_err) => { #[cfg(feature = "multitenancy_fallback")] { self.pool .hgetall(key.tenant_unaware_key(self)) .await .change_context(errors::RedisError::GetHashFieldFailed) } #[cfg(not(feature = "multitenancy_fallback"))] { Err(_err) } } } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_hash_field_and_deserialize<V>( &self, key: &RedisKey, field: &str, type_name: &'static str, ) -> CustomResult<V, errors::RedisError> where V: serde::de::DeserializeOwned, { let value_bytes = self.get_hash_field::<Vec<u8>>(key, field).await?; if value_bytes.is_empty() { return Err(errors::RedisError::NotFound.into()); } value_bytes .parse_struct(type_name) .change_context(errors::RedisError::JsonDeserializationFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn sadd<V>( &self, key: &RedisKey, members: V, ) -> CustomResult<SaddReply, errors::RedisError> where V: TryInto<MultipleValues> + Debug + Send, V::Error: Into<fred::error::RedisError> + Send, { self.pool .sadd(key.tenant_aware_key(self), members) .await .change_context(errors::RedisError::SetAddMembersFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_append_entry<F>( &self, stream: &RedisKey, entry_id: &RedisEntryId, fields: F, ) -> CustomResult<(), errors::RedisError> where F: TryInto<MultipleOrderedPairs> + Debug + Send + Sync, F::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .xadd(stream.tenant_aware_key(self), false, None, entry_id, fields) .await .change_context(errors::RedisError::StreamAppendFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_delete_entries<Ids>( &self, stream: &RedisKey, ids: Ids, ) -> CustomResult<usize, errors::RedisError> where Ids: Into<MultipleStrings> + Debug + Send + Sync, { self.pool .xdel(stream.tenant_aware_key(self), ids) .await .change_context(errors::RedisError::StreamDeleteFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_trim_entries<C>( &self, stream: &RedisKey, xcap: C, ) -> CustomResult<usize, errors::RedisError> where C: TryInto<XCap> + Debug + Send + Sync, C::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .xtrim(stream.tenant_aware_key(self), xcap) .await .change_context(errors::RedisError::StreamTrimFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_acknowledge_entries<Ids>( &self, stream: &RedisKey, group: &str, ids: Ids, ) -> CustomResult<usize, errors::RedisError> where Ids: Into<MultipleIDs> + Debug + Send + Sync, { self.pool .xack(stream.tenant_aware_key(self), group, ids) .await .change_context(errors::RedisError::StreamAcknowledgeFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_get_length( &self, stream: &RedisKey, ) -> CustomResult<usize, errors::RedisError> { self.pool .xlen(stream.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetLengthFailed) } pub fn get_keys_with_prefix<K>(&self, keys: K) -> MultipleKeys where K: Into<MultipleKeys> + Debug + Send + Sync, { let multiple_keys: MultipleKeys = keys.into(); let res = multiple_keys .inner() .iter() .filter_map(|key| key.as_str().map(RedisKey::from)) .map(|k: RedisKey| k.tenant_aware_key(self)) .collect::<Vec<_>>(); MultipleKeys::from(res) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_read_entries<K, Ids>( &self, streams: K, ids: Ids, read_count: Option<u64>, ) -> CustomResult<XReadResponse<String, String, String, String>, errors::RedisError> where K: Into<MultipleKeys> + Debug + Send + Sync, Ids: Into<MultipleIDs> + Debug + Send + Sync, { let strms = self.get_keys_with_prefix(streams); self.pool .xread_map( Some(read_count.unwrap_or(self.config.default_stream_read_count)), None, strms, ids, ) .await .map_err(|err| match err.kind() { RedisErrorKind::NotFound | RedisErrorKind::Parse => { report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable) } _ => report!(err).change_context(errors::RedisError::StreamReadFailed), }) } #[instrument(level = "DEBUG", skip(self))] pub async fn stream_read_with_options<K, Ids>( &self, streams: K, ids: Ids, count: Option<u64>, block: Option<u64>, // timeout in milliseconds group: Option<(&str, &str)>, // (group_name, consumer_name) ) -> CustomResult<XReadResponse<String, String, String, Option<String>>, errors::RedisError> where K: Into<MultipleKeys> + Debug + Send + Sync, Ids: Into<MultipleIDs> + Debug + Send + Sync, { match group { Some((group_name, consumer_name)) => { self.pool .xreadgroup_map( group_name, consumer_name, count, block, false, self.get_keys_with_prefix(streams), ids, ) .await } None => { self.pool .xread_map(count, block, self.get_keys_with_prefix(streams), ids) .await } } .map_err(|err| match err.kind() { RedisErrorKind::NotFound | RedisErrorKind::Parse => { report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable) } _ => report!(err).change_context(errors::RedisError::StreamReadFailed), }) } #[instrument(level = "DEBUG", skip(self))] pub async fn append_elements_to_list<V>( &self, key: &RedisKey, elements: V, ) -> CustomResult<(), errors::RedisError> where V: TryInto<MultipleValues> + Debug + Send, V::Error: Into<fred::error::RedisError> + Send, { self.pool .rpush(key.tenant_aware_key(self), elements) .await .change_context(errors::RedisError::AppendElementsToListFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_list_elements( &self, key: &RedisKey, start: i64, stop: i64, ) -> CustomResult<Vec<String>, errors::RedisError> { self.pool .lrange(key.tenant_aware_key(self), start, stop) .await .change_context(errors::RedisError::GetListElementsFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn get_list_length(&self, key: &RedisKey) -> CustomResult<usize, errors::RedisError> { self.pool .llen(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetListLengthFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn lpop_list_elements( &self, key: &RedisKey, count: Option<usize>, ) -> CustomResult<Vec<String>, errors::RedisError> { self.pool .lpop(key.tenant_aware_key(self), count) .await .change_context(errors::RedisError::PopListElementsFailed) } // Consumer Group API #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_create( &self, stream: &RedisKey, group: &str, id: &RedisEntryId, ) -> CustomResult<(), errors::RedisError> { if matches!( id, RedisEntryId::AutoGeneratedID | RedisEntryId::UndeliveredEntryID ) { // FIXME: Replace with utils::when Err(errors::RedisError::InvalidRedisEntryId)?; } self.pool .xgroup_create(stream.tenant_aware_key(self), group, id, true) .await .change_context(errors::RedisError::ConsumerGroupCreateFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_destroy( &self, stream: &RedisKey, group: &str, ) -> CustomResult<usize, errors::RedisError> { self.pool .xgroup_destroy(stream.tenant_aware_key(self), group) .await .change_context(errors::RedisError::ConsumerGroupDestroyFailed) } // the number of pending messages that the consumer had before it was deleted #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_delete_consumer( &self, stream: &RedisKey, group: &str, consumer: &str, ) -> CustomResult<usize, errors::RedisError> { self.pool .xgroup_delconsumer(stream.tenant_aware_key(self), group, consumer) .await .change_context(errors::RedisError::ConsumerGroupRemoveConsumerFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_set_last_id( &self, stream: &RedisKey, group: &str, id: &RedisEntryId, ) -> CustomResult<String, errors::RedisError> { self.pool .xgroup_setid(stream.tenant_aware_key(self), group, id) .await .change_context(errors::RedisError::ConsumerGroupSetIdFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_set_message_owner<Ids, R>( &self, stream: &RedisKey, group: &str, consumer: &str, min_idle_time: u64, ids: Ids, ) -> CustomResult<R, errors::RedisError> where Ids: Into<MultipleIDs> + Debug + Send + Sync, R: FromRedis + Unpin + Send + 'static, { self.pool .xclaim( stream.tenant_aware_key(self), group, consumer, min_idle_time, ids, None, None, None, false, false, ) .await .change_context(errors::RedisError::ConsumerGroupClaimFailed) } #[instrument(level = "DEBUG", skip(self))] pub async fn evaluate_redis_script<V, T>( &self, lua_script: &'static str, key: Vec<String>, values: V, ) -> CustomResult<T, errors::RedisError> where V: TryInto<MultipleValues> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, T: serde::de::DeserializeOwned + FromRedis, { let val: T = self .pool .eval(lua_script, key, values) .await .change_context(errors::RedisError::IncrementHashFieldFailed)?; Ok(val) } #[instrument(level = "DEBUG", skip(self))] pub async fn set_multiple_keys_if_not_exists_and_get_values<V>( &self, keys: &[(RedisKey, V)], ttl: Option<i64>, ) -> CustomResult<Vec<SetGetReply<V>>, errors::RedisError> where V: TryInto<RedisValue> + Debug + FromRedis + ToOwned<Owned = V> + Send + Sync + serde::de::DeserializeOwned, V::Error: Into<fred::error::RedisError> + Send + Sync, { let futures = keys.iter().map(|(key, value)| { self.set_key_if_not_exists_and_get_value(key, (*value).to_owned(), ttl) }); let del_result = futures::future::try_join_all(futures) .await .change_context(errors::RedisError::SetFailed)?; Ok(del_result) } /// Sets a value in Redis if not already present, and returns the value (either existing or newly set). /// This operation is atomic using Redis transactions. #[instrument(level = "DEBUG", skip(self))] pub async fn set_key_if_not_exists_and_get_value<V>( &self, key: &RedisKey, value: V, ttl: Option<i64>, ) -> CustomResult<SetGetReply<V>, errors::RedisError> where V: TryInto<RedisValue> + Debug + FromRedis + Send + Sync + serde::de::DeserializeOwned, V::Error: Into<fred::error::RedisError> + Send + Sync, { let redis_key = key.tenant_aware_key(self); let ttl_seconds = ttl.unwrap_or(self.config.default_ttl.into()); // Get a client from the pool and start transaction let trx = self.get_transaction(); // Try to set if not exists with expiry - queue the command trx.set::<(), _, _>( &redis_key, value, Some(Expiration::EX(ttl_seconds)), Some(SetOptions::NX), false, ) .await .change_context(errors::RedisError::SetFailed) .attach_printable("Failed to queue set command")?; // Always get the value after the SET attempt - queue the command trx.get::<V, _>(&redis_key) .await .change_context(errors::RedisError::GetFailed) .attach_printable("Failed to queue get command")?; // Execute transaction let mut results: Vec<RedisValue> = trx .exec(true) .await .change_context(errors::RedisError::SetFailed) .attach_printable("Failed to execute the redis transaction")?; let msg = "Got unexpected number of results from transaction"; let get_result = results .pop() .ok_or(errors::RedisError::SetFailed) .attach_printable(msg)?; let set_result = results .pop() .ok_or(errors::RedisError::SetFailed) .attach_printable(msg)?; // Parse the GET result to get the actual value let actual_value: V = FromRedis::from_value(get_result) .change_context(errors::RedisError::SetFailed) .attach_printable("Failed to convert from redis value")?; // Check if SET NX succeeded or failed match set_result { // SET NX returns "OK" if key was set RedisValue::String(_) => Ok(SetGetReply::ValueSet(actual_value)), // SET NX returns null if key already exists RedisValue::Null => Ok(SetGetReply::ValueExists(actual_value)), _ => Err(report!(errors::RedisError::SetFailed)) .attach_printable("Unexpected result from SET NX operation"), } } } #[cfg(test)] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used)] use std::collections::HashMap; use crate::{errors::RedisError, RedisConnectionPool, RedisEntryId, RedisSettings}; #[tokio::test] async fn test_consumer_group_create() { let is_invalid_redis_entry_error = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let redis_conn = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); // Act let result1 = redis_conn .consumer_group_create(&"TEST1".into(), "GTEST", &RedisEntryId::AutoGeneratedID) .await; let result2 = redis_conn .consumer_group_create( &"TEST3".into(), "GTEST", &RedisEntryId::UndeliveredEntryID, ) .await; // Assert Setup *result1.unwrap_err().current_context() == RedisError::InvalidRedisEntryId && *result2.unwrap_err().current_context() == RedisError::InvalidRedisEntryId }) }) .await .expect("Spawn block failure"); assert!(is_invalid_redis_entry_error); } #[tokio::test] async fn test_delete_existing_key_success() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let _ = pool.set_key(&"key".into(), "value".to_string()).await; // Act let result = pool.delete_key(&"key".into()).await; // Assert setup result.is_ok() }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_delete_non_existing_key_success() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); // Act let result = pool.delete_key(&"key not exists".into()).await; // Assert Setup result.is_ok() }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_setting_keys_using_scripts() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let lua_script = r#" for i = 1, #KEYS do redis.call("INCRBY", KEYS[i], ARGV[i]) end return "#; let mut keys_and_values = HashMap::new(); for i in 0..10 { keys_and_values.insert(format!("key{i}"), i); } let key = keys_and_values.keys().cloned().collect::<Vec<_>>(); let values = keys_and_values .values() .map(|val| val.to_string()) .collect::<Vec<String>>(); // Act let result = pool .evaluate_redis_script::<_, ()>(lua_script, key, values) .await; // Assert Setup result.is_ok() }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_getting_keys_using_scripts() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); // First set some keys for i in 0..3 { let key = format!("script_test_key{i}").into(); let _ = pool.set_key(&key, format!("value{i}")).await; } let lua_script = r#" local results = {} for i = 1, #KEYS do results[i] = redis.call("GET", KEYS[i]) end return results "#; let keys = vec![ "script_test_key0".to_string(), "script_test_key1".to_string(), "script_test_key2".to_string(), ]; // Act let result = pool .evaluate_redis_script::<_, Vec<String>>(lua_script, keys, vec![""]) .await; // Assert Setup result.is_ok() }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_set_key_if_not_exists_and_get_value_new_key() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let key = "test_new_key_string".into(); let value = "test_value".to_string(); // Act let result = pool .set_key_if_not_exists_and_get_value(&key, value.clone(), Some(30)) .await; // Assert match result { Ok(crate::types::SetGetReply::ValueSet(returned_value)) => { returned_value == value } _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_set_key_if_not_exists_and_get_value_existing_key() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let key = "test_existing_key_string".into(); let initial_value = "initial_value".to_string(); let new_value = "new_value".to_string(); // First, set an initial value using regular set_key let _ = pool.set_key(&key, initial_value.clone()).await; // Act - try to set a new value (should fail and return existing value) let result = pool .set_key_if_not_exists_and_get_value(&key, new_value, Some(30)) .await; // Assert match result { Ok(crate::types::SetGetReply::ValueExists(returned_value)) => { returned_value == initial_value } _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_set_key_if_not_exists_and_get_value_with_default_ttl() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let key = "test_default_ttl_key_string".into(); let value = "test_value".to_string(); // Act - use None for TTL to test default behavior let result = pool .set_key_if_not_exists_and_get_value(&key, value.clone(), None) .await; // Assert match result { Ok(crate::types::SetGetReply::ValueSet(returned_value)) => { returned_value == value } _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_set_key_if_not_exists_and_get_value_concurrent_access() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let key_name = "test_concurrent_key_string"; let value1 = "value1".to_string(); let value2 = "value2".to_string(); // Act - simulate concurrent access let pool1 = pool.clone(""); let pool2 = pool.clone(""); let key1 = key_name.into(); let key2 = key_name.into(); let (result1, result2) = tokio::join!( pool1.set_key_if_not_exists_and_get_value(&key1, value1, Some(30)), pool2.set_key_if_not_exists_and_get_value(&key2, value2, Some(30)) ); // Assert - one should succeed with ValueSet, one should fail with ValueExists let result1_is_set = matches!(result1, Ok(crate::types::SetGetReply::ValueSet(_))); let result2_is_set = matches!(result2, Ok(crate::types::SetGetReply::ValueSet(_))); let result1_is_exists = matches!(result1, Ok(crate::types::SetGetReply::ValueExists(_))); let result2_is_exists = matches!(result2, Ok(crate::types::SetGetReply::ValueExists(_))); // Exactly one should be ValueSet and one should be ValueExists (result1_is_set && result2_is_exists) || (result1_is_exists && result2_is_set) }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_get_multiple_keys_success() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); // Set up test data let keys = vec![ "multi_test_key1".into(), "multi_test_key2".into(), "multi_test_key3".into(), ]; let values = ["value1", "value2", "value3"]; // Set the keys for (key, value) in keys.iter().zip(values.iter()) { let _ = pool.set_key(key, value.to_string()).await; } // Act let result = pool.get_multiple_keys::<String>(&keys).await; // Assert match result { Ok(retrieved_values) => { retrieved_values.len() == 3 && retrieved_values.first() == Some(&Some("value1".to_string())) && retrieved_values.get(1) == Some(&Some("value2".to_string())) && retrieved_values.get(2) == Some(&Some("value3".to_string())) } _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_get_multiple_keys_with_missing_keys() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let keys = vec![ "existing_key".into(), "non_existing_key".into(), "another_existing_key".into(), ]; // Set only some keys let _ = pool .set_key( keys.first().expect("should not be none"), "value1".to_string(), ) .await; let _ = pool .set_key( keys.get(2).expect("should not be none"), "value3".to_string(), ) .await; // Act let result = pool.get_multiple_keys::<String>(&keys).await; // Assert match result { Ok(retrieved_values) => { retrieved_values.len() == 3 && *retrieved_values.first().expect("should not be none") == Some("value1".to_string()) && retrieved_values.get(1).is_some_and(|v| v.is_none()) && *retrieved_values.get(2).expect("should not be none") == Some("value3".to_string()) } _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_get_multiple_keys_empty_input() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); let keys: Vec<crate::types::RedisKey> = vec![]; // Act let result = pool.get_multiple_keys::<String>(&keys).await; // Assert match result { Ok(retrieved_values) => retrieved_values.is_empty(), _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } #[tokio::test] async fn test_get_and_deserialize_multiple_keys() { let is_success = tokio::task::spawn_blocking(move || { futures::executor::block_on(async { // Arrange let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug, Clone)] struct TestData { id: u32, name: String, } let test_data = [ TestData { id: 1, name: "test1".to_string(), }, TestData { id: 2, name: "test2".to_string(), }, ]; let keys = vec![ "serialize_test_key1".into(), "serialize_test_key2".into(), "non_existing_serialize_key".into(), ]; // Set serialized data for first two keys for (i, data) in test_data.iter().enumerate() { let _ = pool .serialize_and_set_key(keys.get(i).expect("should not be none"), data) .await; } // Act let result = pool .get_and_deserialize_multiple_keys::<TestData>(&keys, "TestData") .await; // Assert match result { Ok(retrieved_data) => { retrieved_data.len() == 3 && retrieved_data.first() == Some(&Some(test_data[0].clone())) && retrieved_data.get(1) == Some(&Some(test_data[1].clone())) && retrieved_data.get(2) == Some(&None) } _ => false, } }) }) .await .expect("Spawn block failure"); assert!(is_success); } }
crates/redis_interface/src/commands.rs
redis_interface::src::commands
12,074
true
// File: crates/redis_interface/src/errors.rs // Module: redis_interface::src::errors //! Errors specific to this custom redis interface #[derive(Debug, thiserror::Error, PartialEq)] pub enum RedisError { #[error("Invalid Redis configuration: {0}")] InvalidConfiguration(String), #[error("Failed to set key value in Redis")] SetFailed, #[error("Failed to set key value in Redis. Duplicate value")] SetNxFailed, #[error("Failed to set key value with expiry in Redis")] SetExFailed, #[error("Failed to set expiry for key value in Redis")] SetExpiryFailed, #[error("Failed to get key value in Redis")] GetFailed, #[error("Failed to delete key value in Redis")] DeleteFailed, #[error("Failed to append entry to Redis stream")] StreamAppendFailed, #[error("Failed to read entries from Redis stream")] StreamReadFailed, #[error("Failed to get stream length")] GetLengthFailed, #[error("Failed to delete entries from Redis stream")] StreamDeleteFailed, #[error("Failed to trim entries from Redis stream")] StreamTrimFailed, #[error("Failed to acknowledge Redis stream entry")] StreamAcknowledgeFailed, #[error("Stream is either empty or not available")] StreamEmptyOrNotAvailable, #[error("Failed to create Redis consumer group")] ConsumerGroupCreateFailed, #[error("Failed to destroy Redis consumer group")] ConsumerGroupDestroyFailed, #[error("Failed to delete consumer from consumer group")] ConsumerGroupRemoveConsumerFailed, #[error("Failed to set last ID on consumer group")] ConsumerGroupSetIdFailed, #[error("Failed to set Redis stream message owner")] ConsumerGroupClaimFailed, #[error("Failed to serialize application type to JSON")] JsonSerializationFailed, #[error("Failed to deserialize application type from JSON")] JsonDeserializationFailed, #[error("Failed to set hash in Redis")] SetHashFailed, #[error("Failed to set hash field in Redis")] SetHashFieldFailed, #[error("Failed to add members to set in Redis")] SetAddMembersFailed, #[error("Failed to get hash field in Redis")] GetHashFieldFailed, #[error("The requested value was not found in Redis")] NotFound, #[error("Invalid RedisEntryId provided")] InvalidRedisEntryId, #[error("Failed to establish Redis connection")] RedisConnectionError, #[error("Failed to subscribe to a channel")] SubscribeError, #[error("Failed to publish to a channel")] PublishError, #[error("Failed while receiving message from publisher")] OnMessageError, #[error("Got an unknown result from redis")] UnknownResult, #[error("Failed to append elements to list in Redis")] AppendElementsToListFailed, #[error("Failed to get list elements in Redis")] GetListElementsFailed, #[error("Failed to get length of list")] GetListLengthFailed, #[error("Failed to pop list elements in Redis")] PopListElementsFailed, #[error("Failed to increment hash field in Redis")] IncrementHashFieldFailed, }
crates/redis_interface/src/errors.rs
redis_interface::src::errors
684
true
// File: crates/events/src/lib.rs // Module: events::src::lib #![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide))] #![cfg_attr(docsrs, doc(cfg_hide(doc)))] #![warn(missing_docs)] //! A generic event handler system. //! This library consists of 4 parts: //! Event Sink: A trait that defines how events are published. This could be a simple logger, a message queue, or a database. //! EventContext: A struct that holds the event sink and metadata about the event. This is used to create events. This can be used to add metadata to all events, such as the user who triggered the event. //! EventInfo: A trait that defines the metadata that is sent with the event. It works with the EventContext to add metadata to all events. //! Event: A trait that defines the event itself. This trait is used to define the data that is sent with the event and defines the event's type & identifier. mod actix; use std::{collections::HashMap, sync::Arc}; use error_stack::{Result, ResultExt}; use masking::{ErasedMaskSerialize, Serialize}; use router_env::logger; use serde::Serializer; use serde_json::Value; use time::PrimitiveDateTime; /// Errors that can occur when working with events. #[derive(Debug, Clone, thiserror::Error)] pub enum EventsError { /// An error occurred when publishing the event. #[error("Generic Error")] GenericError, /// An error occurred when serializing the event. #[error("Event serialization error")] SerializationError, /// An error occurred when publishing/producing the event. #[error("Event publishing error")] PublishError, } /// An event that can be published. pub trait Event: EventInfo { /// The type of the event. type EventType; /// The timestamp of the event. fn timestamp(&self) -> PrimitiveDateTime; /// The (unique) identifier of the event. fn identifier(&self) -> String; /// The class/type of the event. This is used to group/categorize events together. fn class(&self) -> Self::EventType; /// Metadata associated with the event fn metadata(&self) -> HashMap<String, String> { HashMap::new() } } /// Hold the context information for any events #[derive(Clone)] pub struct EventContext<T, A> where A: MessagingInterface<MessageClass = T>, { message_sink: Arc<A>, metadata: HashMap<String, Value>, } /// intermediary structure to build events with in-place info. #[must_use = "make sure to call `emit` or `try_emit` to actually emit the event"] pub struct EventBuilder<T, A, E, D> where A: MessagingInterface<MessageClass = T>, E: Event<EventType = T, Data = D>, { message_sink: Arc<A>, metadata: HashMap<String, Value>, event: E, } /// A flattened event that flattens the context provided to it along with the actual event. struct FlatMapEvent<T, A: Event<EventType = T>>(HashMap<String, Value>, A); impl<T, A, E, D> EventBuilder<T, A, E, D> where A: MessagingInterface<MessageClass = T>, E: Event<EventType = T, Data = D>, { /// Add metadata to the event. pub fn with<F: ErasedMaskSerialize, G: EventInfo<Data = F> + 'static>( mut self, info: G, ) -> Self { info.data() .and_then(|i| { i.masked_serialize() .change_context(EventsError::SerializationError) }) .map_err(|e| { logger::error!("Error adding event info: {:?}", e); }) .ok() .and_then(|data| self.metadata.insert(info.key(), data)); self } /// Emit the event and log any errors. pub fn emit(self) { self.try_emit() .map_err(|e| { logger::error!("Error emitting event: {:?}", e); }) .ok(); } /// Emit the event. pub fn try_emit(self) -> Result<(), EventsError> { let ts = self.event.timestamp(); let metadata = self.event.metadata(); self.message_sink .send_message(FlatMapEvent(self.metadata, self.event), metadata, ts) } } impl<T, A> Serialize for FlatMapEvent<T, A> where A: Event<EventType = T>, { fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error> where S: Serializer, { let mut serialize_map: HashMap<_, _> = self .0 .iter() .filter_map(|(k, v)| Some((k.clone(), v.masked_serialize().ok()?))) .collect(); match self.1.data().map(|i| i.masked_serialize()) { Ok(Ok(Value::Object(map))) => { for (k, v) in map.into_iter() { serialize_map.insert(k, v); } } Ok(Ok(i)) => { serialize_map.insert(self.1.key(), i); } i => { logger::error!("Error serializing event: {:?}", i); } }; serialize_map.serialize(serializer) } } impl<T, A> EventContext<T, A> where A: MessagingInterface<MessageClass = T>, { /// Create a new event context. pub fn new(message_sink: A) -> Self { Self { message_sink: Arc::new(message_sink), metadata: HashMap::new(), } } /// Add metadata to the event context. #[track_caller] pub fn record_info<G: ErasedMaskSerialize, E: EventInfo<Data = G> + 'static>( &mut self, info: E, ) { match info.data().and_then(|i| { i.masked_serialize() .change_context(EventsError::SerializationError) }) { Ok(data) => { self.metadata.insert(info.key(), data); } Err(e) => { logger::error!("Error recording event info: {:?}", e); } } } /// Emit an event. pub fn try_emit<E: Event<EventType = T>>(&self, event: E) -> Result<(), EventsError> { EventBuilder { message_sink: self.message_sink.clone(), metadata: self.metadata.clone(), event, } .try_emit() } /// Emit an event. pub fn emit<D, E: Event<EventType = T, Data = D>>(&self, event: E) { EventBuilder { message_sink: self.message_sink.clone(), metadata: self.metadata.clone(), event, } .emit() } /// Create an event builder. pub fn event<D, E: Event<EventType = T, Data = D>>( &self, event: E, ) -> EventBuilder<T, A, E, D> { EventBuilder { message_sink: self.message_sink.clone(), metadata: self.metadata.clone(), event, } } } /// Add information/metadata to the current context of an event. pub trait EventInfo { /// The data that is sent with the event. type Data: ErasedMaskSerialize; /// The data that is sent with the event. fn data(&self) -> Result<Self::Data, EventsError>; /// The key identifying the data for an event. fn key(&self) -> String; } impl EventInfo for (String, String) { type Data = String; fn data(&self) -> Result<String, EventsError> { Ok(self.1.clone()) } fn key(&self) -> String { self.0.clone() } } /// A messaging interface for sending messages/events. /// This can be implemented for any messaging system, such as a message queue, a logger, or a database. pub trait MessagingInterface { /// The type of the event used for categorization by the event publisher. type MessageClass; /// Send a message that follows the defined message class. fn send_message<T>( &self, data: T, metadata: HashMap<String, String>, timestamp: PrimitiveDateTime, ) -> Result<(), EventsError> where T: Message<Class = Self::MessageClass> + ErasedMaskSerialize; } /// A message that can be sent. pub trait Message { /// The type of the event used for categorization by the event publisher. type Class; /// The type of the event used for categorization by the event publisher. fn get_message_class(&self) -> Self::Class; /// The (unique) identifier of the event. fn identifier(&self) -> String; } impl<T, A> Message for FlatMapEvent<T, A> where A: Event<EventType = T>, { type Class = T; fn get_message_class(&self) -> Self::Class { self.1.class() } fn identifier(&self) -> String { self.1.identifier() } }
crates/events/src/lib.rs
events::src::lib
1,977
true
// File: crates/events/src/actix.rs // Module: events::src::actix use router_env::tracing_actix_web::RequestId; use crate::EventInfo; impl EventInfo for RequestId { type Data = String; fn data(&self) -> error_stack::Result<String, crate::EventsError> { Ok(self.as_hyphenated().to_string()) } fn key(&self) -> String { "request_id".to_string() } }
crates/events/src/actix.rs
events::src::actix
105
true
// File: crates/payment_methods/src/core.rs // Module: payment_methods::src::core pub mod errors; pub mod migration;
crates/payment_methods/src/core.rs
payment_methods::src::core
28
true
// File: crates/payment_methods/src/controller.rs // Module: payment_methods::src::controller use std::fmt::Debug; #[cfg(feature = "payouts")] use api_models::payouts; use api_models::{enums as api_enums, payment_methods as api}; #[cfg(feature = "v1")] use common_enums::enums as common_enums; #[cfg(feature = "v2")] use common_utils::encryption; use common_utils::{crypto, ext_traits, id_type, type_name, types::keymanager}; use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::payment_methods::PaymentMethodVaultSourceDetails; use hyperswitch_domain_models::{merchant_key_store, payment_methods, type_encryption}; use masking::{PeekInterface, Secret}; #[cfg(feature = "v1")] use scheduler::errors as sch_errors; use serde::{Deserialize, Serialize}; use storage_impl::{errors as storage_errors, payment_method}; use crate::core::errors; #[derive(Debug, Deserialize, Serialize)] pub struct DeleteCardResp { pub status: String, pub error_message: Option<String>, pub error_code: Option<String>, } #[derive(Debug, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum DataDuplicationCheck { Duplicated, MetaDataChanged, } #[async_trait::async_trait] pub trait PaymentMethodsController { #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn create_payment_method( &self, req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, payment_method_id: &str, locker_id: Option<String>, merchant_id: &id_type::MerchantId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, payment_method_data: crypto::OptionalEncryptableValue, connector_mandate_details: Option<serde_json::Value>, status: Option<common_enums::PaymentMethodStatus>, network_transaction_id: Option<String>, payment_method_billing_address: crypto::OptionalEncryptableValue, card_scheme: Option<String>, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, vault_source_details: Option<PaymentMethodVaultSourceDetails>, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn insert_payment_method( &self, resp: &api::PaymentMethodResponse, req: &api::PaymentMethodCreate, key_store: &merchant_key_store::MerchantKeyStore, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, connector_mandate_details: Option<serde_json::Value>, network_transaction_id: Option<String>, payment_method_billing_address: crypto::OptionalEncryptableValue, network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: crypto::OptionalEncryptableValue, vault_source_details: Option<PaymentMethodVaultSourceDetails>, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn insert_payment_method( &self, resp: &api::PaymentMethodResponse, req: &api::PaymentMethodCreate, key_store: &merchant_key_store::MerchantKeyStore, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, pm_metadata: Option<serde_json::Value>, customer_acceptance: Option<serde_json::Value>, locker_id: Option<String>, connector_mandate_details: Option<serde_json::Value>, network_transaction_id: Option<String>, payment_method_billing_address: Option<encryption::Encryption>, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v1")] async fn add_payment_method( &self, req: &api::PaymentMethodCreate, ) -> errors::PmResponse<api::PaymentMethodResponse>; #[cfg(feature = "v1")] async fn retrieve_payment_method( &self, pm: api::PaymentMethodId, ) -> errors::PmResponse<api::PaymentMethodResponse>; #[cfg(feature = "v1")] async fn delete_payment_method( &self, pm_id: api::PaymentMethodId, ) -> errors::PmResponse<api::PaymentMethodDeleteResponse>; async fn add_card_hs( &self, req: api::PaymentMethodCreate, card: &api::CardDetail, customer_id: &id_type::CustomerId, locker_choice: api_enums::LockerChoice, card_reference: Option<&str>, ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>; /// The response will be the tuple of PaymentMethodResponse and the duplication check of payment_method async fn add_card_to_locker( &self, req: api::PaymentMethodCreate, card: &api::CardDetail, customer_id: &id_type::CustomerId, card_reference: Option<&str>, ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>; #[cfg(feature = "payouts")] async fn add_bank_to_locker( &self, req: api::PaymentMethodCreate, key_store: &merchant_key_store::MerchantKeyStore, bank: &payouts::Bank, customer_id: &id_type::CustomerId, ) -> errors::VaultResult<(api::PaymentMethodResponse, Option<DataDuplicationCheck>)>; #[cfg(feature = "v1")] async fn get_or_insert_payment_method( &self, req: api::PaymentMethodCreate, resp: &mut api::PaymentMethodResponse, customer_id: &id_type::CustomerId, key_store: &merchant_key_store::MerchantKeyStore, ) -> errors::PmResult<payment_methods::PaymentMethod>; #[cfg(feature = "v2")] async fn get_or_insert_payment_method( &self, _req: api::PaymentMethodCreate, _resp: &mut api::PaymentMethodResponse, _customer_id: &id_type::CustomerId, _key_store: &merchant_key_store::MerchantKeyStore, ) -> errors::PmResult<payment_methods::PaymentMethod> { todo!() } #[cfg(feature = "v1")] async fn get_card_details_with_locker_fallback( &self, pm: &payment_methods::PaymentMethod, ) -> errors::PmResult<Option<api::CardDetailFromLocker>>; #[cfg(feature = "v1")] async fn get_card_details_without_locker_fallback( &self, pm: &payment_methods::PaymentMethod, ) -> errors::PmResult<api::CardDetailFromLocker>; async fn delete_card_from_locker( &self, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &str, ) -> errors::PmResult<DeleteCardResp>; #[cfg(feature = "v1")] fn store_default_payment_method( &self, req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> (api::PaymentMethodResponse, Option<DataDuplicationCheck>); #[cfg(feature = "v2")] fn store_default_payment_method( &self, req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, ) -> (api::PaymentMethodResponse, Option<DataDuplicationCheck>); #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn save_network_token_and_update_payment_method( &self, req: &api::PaymentMethodMigrate, key_store: &merchant_key_store::MerchantKeyStore, network_token_data: &api_models::payment_methods::MigrateNetworkTokenData, network_token_requestor_ref_id: String, pm_id: String, ) -> errors::PmResult<bool>; #[cfg(feature = "v1")] async fn set_default_payment_method( &self, merchant_id: &id_type::MerchantId, customer_id: &id_type::CustomerId, payment_method_id: String, ) -> errors::PmResponse<api_models::payment_methods::CustomerDefaultPaymentMethodResponse>; #[cfg(feature = "v1")] async fn add_payment_method_status_update_task( &self, payment_method: &payment_methods::PaymentMethod, prev_status: common_enums::PaymentMethodStatus, curr_status: common_enums::PaymentMethodStatus, merchant_id: &id_type::MerchantId, ) -> Result<(), sch_errors::ProcessTrackerError>; #[cfg(feature = "v1")] async fn validate_merchant_connector_ids_in_connector_mandate_details( &self, key_store: &merchant_key_store::MerchantKeyStore, connector_mandate_details: &api_models::payment_methods::CommonMandateReference, merchant_id: &id_type::MerchantId, card_network: Option<common_enums::CardNetwork>, ) -> errors::PmResult<()>; #[cfg(feature = "v1")] async fn get_card_details_from_locker( &self, pm: &payment_methods::PaymentMethod, ) -> errors::PmResult<api::CardDetailFromLocker>; } pub async fn create_encrypted_data<T>( key_manager_state: &keymanager::KeyManagerState, key_store: &merchant_key_store::MerchantKeyStore, data: T, ) -> Result< crypto::Encryptable<Secret<serde_json::Value>>, error_stack::Report<storage_errors::StorageError>, > where T: Debug + Serialize, { let key = key_store.key.get_inner().peek(); let identifier = keymanager::Identifier::Merchant(key_store.merchant_id.clone()); let encoded_data = ext_traits::Encode::encode_to_value(&data) .change_context(storage_errors::StorageError::SerializationFailed) .attach_printable("Unable to encode data")?; let secret_data = Secret::<_, masking::WithType>::new(encoded_data); let encrypted_data = type_encryption::crypto_operation( key_manager_state, type_name!(payment_method::PaymentMethod), type_encryption::CryptoOperation::Encrypt(secret_data), identifier.clone(), key, ) .await .and_then(|val| val.try_into_operation()) .change_context(storage_errors::StorageError::EncryptionError) .attach_printable("Unable to encrypt data")?; Ok(encrypted_data) }
crates/payment_methods/src/controller.rs
payment_methods::src::controller
2,416
true
// File: crates/payment_methods/src/configs.rs // Module: payment_methods::src::configs pub mod payment_connector_required_fields; pub mod settings;
crates/payment_methods/src/configs.rs
payment_methods::src::configs
32
true
// File: crates/payment_methods/src/lib.rs // Module: payment_methods::src::lib pub mod configs; pub mod controller; pub mod core; pub mod helpers; pub mod state;
crates/payment_methods/src/lib.rs
payment_methods::src::lib
40
true
// File: crates/payment_methods/src/helpers.rs // Module: payment_methods::src::helpers use api_models::{enums as api_enums, payment_methods as api}; #[cfg(feature = "v1")] use common_utils::ext_traits::AsyncExt; pub use hyperswitch_domain_models::{errors::api_error_response, payment_methods as domain}; #[cfg(feature = "v1")] use router_env::logger; use crate::state; #[cfg(feature = "v1")] pub async fn populate_bin_details_for_payment_method_create( card_details: api_models::payment_methods::CardDetail, db: Box<dyn state::PaymentMethodsStorageInterface>, ) -> api_models::payment_methods::CardDetail { let card_isin: Option<_> = Some(card_details.card_number.get_card_isin()); if card_details.card_issuer.is_some() && card_details.card_network.is_some() && card_details.card_type.is_some() && card_details.card_issuing_country.is_some() { api::CardDetail { card_issuer: card_details.card_issuer.to_owned(), card_network: card_details.card_network.clone(), card_type: card_details.card_type.to_owned(), card_issuing_country: card_details.card_issuing_country.to_owned(), card_exp_month: card_details.card_exp_month.clone(), card_exp_year: card_details.card_exp_year.clone(), card_holder_name: card_details.card_holder_name.clone(), card_number: card_details.card_number.clone(), nick_name: card_details.nick_name.clone(), } } else { let card_info = card_isin .clone() .async_and_then(|card_isin| async move { db.get_card_info(&card_isin) .await .map_err(|error| logger::error!(card_info_error=?error)) .ok() }) .await .flatten() .map(|card_info| api::CardDetail { card_issuer: card_info.card_issuer, card_network: card_info.card_network.clone(), card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country, card_exp_month: card_details.card_exp_month.clone(), card_exp_year: card_details.card_exp_year.clone(), card_holder_name: card_details.card_holder_name.clone(), card_number: card_details.card_number.clone(), nick_name: card_details.nick_name.clone(), }); card_info.unwrap_or_else(|| api::CardDetail { card_issuer: None, card_network: None, card_type: None, card_issuing_country: None, card_exp_month: card_details.card_exp_month.clone(), card_exp_year: card_details.card_exp_year.clone(), card_holder_name: card_details.card_holder_name.clone(), card_number: card_details.card_number.clone(), nick_name: card_details.nick_name.clone(), }) } } #[cfg(feature = "v2")] pub async fn populate_bin_details_for_payment_method_create( _card_details: api_models::payment_methods::CardDetail, _db: &dyn state::PaymentMethodsStorageInterface, ) -> api_models::payment_methods::CardDetail { todo!() } pub fn validate_payment_method_type_against_payment_method( payment_method: api_enums::PaymentMethod, payment_method_type: api_enums::PaymentMethodType, ) -> bool { match payment_method { #[cfg(feature = "v1")] api_enums::PaymentMethod::Card => matches!( payment_method_type, api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit ), #[cfg(feature = "v2")] api_enums::PaymentMethod::Card => matches!( payment_method_type, api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit | api_enums::PaymentMethodType::Card ), api_enums::PaymentMethod::PayLater => matches!( payment_method_type, api_enums::PaymentMethodType::Affirm | api_enums::PaymentMethodType::Alma | api_enums::PaymentMethodType::AfterpayClearpay | api_enums::PaymentMethodType::Klarna | api_enums::PaymentMethodType::PayBright | api_enums::PaymentMethodType::Atome | api_enums::PaymentMethodType::Walley | api_enums::PaymentMethodType::Breadpay | api_enums::PaymentMethodType::Flexiti ), api_enums::PaymentMethod::Wallet => matches!( payment_method_type, api_enums::PaymentMethodType::AmazonPay | api_enums::PaymentMethodType::Bluecode | api_enums::PaymentMethodType::Paysera | api_enums::PaymentMethodType::Skrill | api_enums::PaymentMethodType::ApplePay | api_enums::PaymentMethodType::GooglePay | api_enums::PaymentMethodType::Paypal | api_enums::PaymentMethodType::AliPay | api_enums::PaymentMethodType::AliPayHk | api_enums::PaymentMethodType::Dana | api_enums::PaymentMethodType::MbWay | api_enums::PaymentMethodType::MobilePay | api_enums::PaymentMethodType::SamsungPay | api_enums::PaymentMethodType::Twint | api_enums::PaymentMethodType::Vipps | api_enums::PaymentMethodType::TouchNGo | api_enums::PaymentMethodType::Swish | api_enums::PaymentMethodType::WeChatPay | api_enums::PaymentMethodType::GoPay | api_enums::PaymentMethodType::Gcash | api_enums::PaymentMethodType::Momo | api_enums::PaymentMethodType::KakaoPay | api_enums::PaymentMethodType::Cashapp | api_enums::PaymentMethodType::Mifinity | api_enums::PaymentMethodType::Paze | api_enums::PaymentMethodType::RevolutPay ), api_enums::PaymentMethod::BankRedirect => matches!( payment_method_type, api_enums::PaymentMethodType::Giropay | api_enums::PaymentMethodType::Ideal | api_enums::PaymentMethodType::Sofort | api_enums::PaymentMethodType::Eft | api_enums::PaymentMethodType::Eps | api_enums::PaymentMethodType::BancontactCard | api_enums::PaymentMethodType::Blik | api_enums::PaymentMethodType::LocalBankRedirect | api_enums::PaymentMethodType::OnlineBankingThailand | api_enums::PaymentMethodType::OnlineBankingCzechRepublic | api_enums::PaymentMethodType::OnlineBankingFinland | api_enums::PaymentMethodType::OnlineBankingFpx | api_enums::PaymentMethodType::OnlineBankingPoland | api_enums::PaymentMethodType::OnlineBankingSlovakia | api_enums::PaymentMethodType::Przelewy24 | api_enums::PaymentMethodType::Trustly | api_enums::PaymentMethodType::Bizum | api_enums::PaymentMethodType::Interac | api_enums::PaymentMethodType::OpenBankingUk | api_enums::PaymentMethodType::OpenBankingPIS ), api_enums::PaymentMethod::BankTransfer => matches!( payment_method_type, api_enums::PaymentMethodType::Ach | api_enums::PaymentMethodType::SepaBankTransfer | api_enums::PaymentMethodType::Bacs | api_enums::PaymentMethodType::Multibanco | api_enums::PaymentMethodType::Pix | api_enums::PaymentMethodType::Pse | api_enums::PaymentMethodType::PermataBankTransfer | api_enums::PaymentMethodType::BcaBankTransfer | api_enums::PaymentMethodType::BniVa | api_enums::PaymentMethodType::BriVa | api_enums::PaymentMethodType::CimbVa | api_enums::PaymentMethodType::DanamonVa | api_enums::PaymentMethodType::MandiriVa | api_enums::PaymentMethodType::LocalBankTransfer | api_enums::PaymentMethodType::InstantBankTransfer | api_enums::PaymentMethodType::InstantBankTransferFinland | api_enums::PaymentMethodType::InstantBankTransferPoland | api_enums::PaymentMethodType::IndonesianBankTransfer ), api_enums::PaymentMethod::BankDebit => matches!( payment_method_type, api_enums::PaymentMethodType::Ach | api_enums::PaymentMethodType::Sepa | api_enums::PaymentMethodType::SepaGuarenteedDebit | api_enums::PaymentMethodType::Bacs | api_enums::PaymentMethodType::Becs ), api_enums::PaymentMethod::Crypto => matches!( payment_method_type, api_enums::PaymentMethodType::CryptoCurrency ), api_enums::PaymentMethod::Reward => matches!( payment_method_type, api_enums::PaymentMethodType::Evoucher | api_enums::PaymentMethodType::ClassicReward ), api_enums::PaymentMethod::RealTimePayment => matches!( payment_method_type, api_enums::PaymentMethodType::Fps | api_enums::PaymentMethodType::DuitNow | api_enums::PaymentMethodType::PromptPay | api_enums::PaymentMethodType::VietQr ), api_enums::PaymentMethod::Upi => matches!( payment_method_type, api_enums::PaymentMethodType::UpiCollect | api_enums::PaymentMethodType::UpiIntent | api_enums::PaymentMethodType::UpiQr ), api_enums::PaymentMethod::Voucher => matches!( payment_method_type, api_enums::PaymentMethodType::Boleto | api_enums::PaymentMethodType::Efecty | api_enums::PaymentMethodType::PagoEfectivo | api_enums::PaymentMethodType::RedCompra | api_enums::PaymentMethodType::RedPagos | api_enums::PaymentMethodType::Indomaret | api_enums::PaymentMethodType::Alfamart | api_enums::PaymentMethodType::Oxxo | api_enums::PaymentMethodType::SevenEleven | api_enums::PaymentMethodType::Lawson | api_enums::PaymentMethodType::MiniStop | api_enums::PaymentMethodType::FamilyMart | api_enums::PaymentMethodType::Seicomart | api_enums::PaymentMethodType::PayEasy ), api_enums::PaymentMethod::GiftCard => { matches!( payment_method_type, api_enums::PaymentMethodType::Givex | api_enums::PaymentMethodType::PaySafeCard ) } api_enums::PaymentMethod::CardRedirect => matches!( payment_method_type, api_enums::PaymentMethodType::Knet | api_enums::PaymentMethodType::Benefit | api_enums::PaymentMethodType::MomoAtm | api_enums::PaymentMethodType::CardRedirect ), api_enums::PaymentMethod::OpenBanking => matches!( payment_method_type, api_enums::PaymentMethodType::OpenBankingPIS ), api_enums::PaymentMethod::MobilePayment => matches!( payment_method_type, api_enums::PaymentMethodType::DirectCarrierBilling ), } } pub trait ForeignFrom<F> { fn foreign_from(from: F) -> Self; } /// Trait for converting from one foreign type to another pub trait ForeignTryFrom<F>: Sized { /// Custom error for conversion failure type Error; /// Convert from a foreign type to the current type and return an error if the conversion fails fn foreign_try_from(from: F) -> Result<Self, Self::Error>; } #[cfg(feature = "v1")] impl ForeignFrom<(Option<api::CardDetailFromLocker>, domain::PaymentMethod)> for api::PaymentMethodResponse { fn foreign_from( (card_details, item): (Option<api::CardDetailFromLocker>, domain::PaymentMethod), ) -> Self { Self { merchant_id: item.merchant_id.to_owned(), customer_id: Some(item.customer_id.to_owned()), payment_method_id: item.get_id().clone(), payment_method: item.get_payment_method_type(), payment_method_type: item.get_payment_method_subtype(), card: card_details, recurring_enabled: Some(false), installment_payment_enabled: Some(false), payment_experience: None, metadata: item.metadata, created: Some(item.created_at), #[cfg(feature = "payouts")] bank_transfer: None, last_used_at: None, client_secret: item.client_secret, } } } #[cfg(feature = "v2")] impl ForeignFrom<(Option<api::CardDetailFromLocker>, domain::PaymentMethod)> for api::PaymentMethodResponse { fn foreign_from( (_card_details, _item): (Option<api::CardDetailFromLocker>, domain::PaymentMethod), ) -> Self { todo!() } } pub trait StorageErrorExt<T, E> { #[track_caller] fn to_not_found_response(self, not_found_response: E) -> error_stack::Result<T, E>; #[track_caller] fn to_duplicate_response(self, duplicate_response: E) -> error_stack::Result<T, E>; } impl<T> StorageErrorExt<T, api_error_response::ApiErrorResponse> for error_stack::Result<T, storage_impl::StorageError> { #[track_caller] fn to_not_found_response( self, not_found_response: api_error_response::ApiErrorResponse, ) -> error_stack::Result<T, api_error_response::ApiErrorResponse> { self.map_err(|err| { let new_err = match err.current_context() { storage_impl::StorageError::ValueNotFound(_) => not_found_response, storage_impl::StorageError::CustomerRedacted => { api_error_response::ApiErrorResponse::CustomerRedacted } _ => api_error_response::ApiErrorResponse::InternalServerError, }; err.change_context(new_err) }) } #[track_caller] fn to_duplicate_response( self, duplicate_response: api_error_response::ApiErrorResponse, ) -> error_stack::Result<T, api_error_response::ApiErrorResponse> { self.map_err(|err| { let new_err = match err.current_context() { storage_impl::StorageError::DuplicateValue { .. } => duplicate_response, _ => api_error_response::ApiErrorResponse::InternalServerError, }; err.change_context(new_err) }) } }
crates/payment_methods/src/helpers.rs
payment_methods::src::helpers
3,329
true
// File: crates/payment_methods/src/state.rs // Module: payment_methods::src::state #[cfg(feature = "v1")] use common_utils::errors::CustomResult; use common_utils::types::keymanager; #[cfg(feature = "v1")] use hyperswitch_domain_models::merchant_account; use hyperswitch_domain_models::{ cards_info, customer, merchant_key_store, payment_methods as pm_domain, }; use storage_impl::{errors, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore}; #[async_trait::async_trait] pub trait PaymentMethodsStorageInterface: Send + Sync + dyn_clone::DynClone + pm_domain::PaymentMethodInterface<Error = errors::StorageError> + cards_info::CardsInfoInterface<Error = errors::StorageError> + customer::CustomerInterface<Error = errors::StorageError> + 'static { } dyn_clone::clone_trait_object!(PaymentMethodsStorageInterface); #[async_trait::async_trait] impl PaymentMethodsStorageInterface for MockDb {} #[async_trait::async_trait] impl<T: DatabaseStore + 'static> PaymentMethodsStorageInterface for RouterStore<T> {} #[async_trait::async_trait] impl<T: DatabaseStore + 'static> PaymentMethodsStorageInterface for KVRouterStore<T> {} #[derive(Clone)] pub struct PaymentMethodsState { pub store: Box<dyn PaymentMethodsStorageInterface>, pub key_store: Option<merchant_key_store::MerchantKeyStore>, pub key_manager_state: keymanager::KeyManagerState, } impl From<&PaymentMethodsState> for keymanager::KeyManagerState { fn from(state: &PaymentMethodsState) -> Self { state.key_manager_state.clone() } } #[cfg(feature = "v1")] impl PaymentMethodsState { pub async fn find_payment_method( &self, key_store: &merchant_key_store::MerchantKeyStore, merchant_account: &merchant_account::MerchantAccount, payment_method_id: String, ) -> CustomResult<pm_domain::PaymentMethod, errors::StorageError> { let db = &*self.store; let key_manager_state = &(self.key_manager_state).clone(); match db .find_payment_method( key_manager_state, key_store, &payment_method_id, merchant_account.storage_scheme, ) .await { Err(err) if err.current_context().is_db_not_found() => { db.find_payment_method_by_locker_id( key_manager_state, key_store, &payment_method_id, merchant_account.storage_scheme, ) .await } Ok(pm) => Ok(pm), Err(err) => Err(err), } } }
crates/payment_methods/src/state.rs
payment_methods::src::state
572
true
// File: crates/payment_methods/src/core/errors.rs // Module: payment_methods::src::core::errors pub use common_utils::errors::{CustomResult, ParsingError, ValidationError}; pub use hyperswitch_domain_models::{ api, errors::api_error_response::{self, *}, }; pub type PmResult<T> = CustomResult<T, ApiErrorResponse>; pub type PmResponse<T> = CustomResult<api::ApplicationResponse<T>, ApiErrorResponse>; pub type VaultResult<T> = CustomResult<T, VaultError>; #[derive(Debug, thiserror::Error)] pub enum VaultError { #[error("Failed to save card in card vault")] SaveCardFailed, #[error("Failed to fetch card details from card vault")] FetchCardFailed, #[error("Failed to delete card in card vault")] DeleteCardFailed, #[error("Failed to encode card vault request")] RequestEncodingFailed, #[error("Failed to deserialize card vault response")] ResponseDeserializationFailed, #[error("Failed to create payment method")] PaymentMethodCreationFailed, #[error("The given payment method is currently not supported in vault")] PaymentMethodNotSupported, #[error("The given payout method is currently not supported in vault")] PayoutMethodNotSupported, #[error("Missing required field: {field_name}")] MissingRequiredField { field_name: &'static str }, #[error("The card vault returned an unexpected response: {0:?}")] UnexpectedResponseError(bytes::Bytes), #[error("Failed to update in PMD table")] UpdateInPaymentMethodDataTableFailed, #[error("Failed to fetch payment method in vault")] FetchPaymentMethodFailed, #[error("Failed to save payment method in vault")] SavePaymentMethodFailed, #[error("Failed to generate fingerprint")] GenerateFingerprintFailed, #[error("Failed to encrypt vault request")] RequestEncryptionFailed, #[error("Failed to decrypt vault response")] ResponseDecryptionFailed, #[error("Failed to call vault")] VaultAPIError, #[error("Failed while calling locker API")] ApiError, }
crates/payment_methods/src/core/errors.rs
payment_methods::src::core::errors
446
true
// File: crates/payment_methods/src/core/migration.rs // Module: payment_methods::src::core::migration use actix_multipart::form::{self, bytes, text}; use api_models::payment_methods as pm_api; use csv::Reader; use error_stack::ResultExt; #[cfg(feature = "v1")] use hyperswitch_domain_models::{api, merchant_context}; use masking::PeekInterface; use rdkafka::message::ToBytes; use router_env::{instrument, tracing}; use crate::core::errors; #[cfg(feature = "v1")] use crate::{controller as pm, state}; pub mod payment_methods; pub use payment_methods::migrate_payment_method; #[cfg(feature = "v1")] type PmMigrationResult<T> = errors::CustomResult<api::ApplicationResponse<T>, errors::ApiErrorResponse>; #[cfg(feature = "v1")] pub async fn migrate_payment_methods( state: &state::PaymentMethodsState, payment_methods: Vec<pm_api::PaymentMethodRecord>, merchant_id: &common_utils::id_type::MerchantId, merchant_context: &merchant_context::MerchantContext, mca_ids: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, controller: &dyn pm::PaymentMethodsController, ) -> PmMigrationResult<Vec<pm_api::PaymentMethodMigrationResponse>> { let mut result = Vec::with_capacity(payment_methods.len()); for record in payment_methods { let req = pm_api::PaymentMethodMigrate::try_from(( &record, merchant_id.clone(), mca_ids.as_ref(), )) .map_err(|err| errors::ApiErrorResponse::InvalidRequestData { message: format!("error: {err:?}"), }) .attach_printable("record deserialization failed"); let res = match req { Ok(migrate_request) => { let res = migrate_payment_method( state, migrate_request, merchant_id, merchant_context, controller, ) .await; match res { Ok(api::ApplicationResponse::Json(response)) => Ok(response), Err(e) => Err(e.to_string()), _ => Err("Failed to migrate payment method".to_string()), } } Err(e) => Err(e.to_string()), }; result.push(pm_api::PaymentMethodMigrationResponse::from((res, record))); } Ok(api::ApplicationResponse::Json(result)) } #[derive(Debug, form::MultipartForm)] pub struct PaymentMethodsMigrateForm { #[multipart(limit = "1MB")] pub file: bytes::Bytes, pub merchant_id: text::Text<common_utils::id_type::MerchantId>, pub merchant_connector_id: Option<text::Text<common_utils::id_type::MerchantConnectorAccountId>>, pub merchant_connector_ids: Option<text::Text<String>>, } pub struct MerchantConnectorValidator; impl MerchantConnectorValidator { pub fn parse_comma_separated_ids( ids_string: &str, ) -> Result<Vec<common_utils::id_type::MerchantConnectorAccountId>, errors::ApiErrorResponse> { // Estimate capacity based on comma count let capacity = ids_string.matches(',').count() + 1; let mut result = Vec::with_capacity(capacity); for id in ids_string.split(',') { let trimmed_id = id.trim(); if !trimmed_id.is_empty() { let mca_id = common_utils::id_type::MerchantConnectorAccountId::wrap(trimmed_id.to_string()) .map_err(|_| errors::ApiErrorResponse::InvalidRequestData { message: format!("Invalid merchant_connector_account_id: {trimmed_id}"), })?; result.push(mca_id); } } Ok(result) } fn validate_form_csv_conflicts( records: &[pm_api::PaymentMethodRecord], form_has_single_id: bool, form_has_multiple_ids: bool, ) -> Result<(), errors::ApiErrorResponse> { if form_has_single_id { // If form has merchant_connector_id, CSV records should not have merchant_connector_ids for (index, record) in records.iter().enumerate() { if record.merchant_connector_ids.is_some() { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Record at line {} has merchant_connector_ids but form has merchant_connector_id. Only one should be provided", index + 1 ), }); } } } if form_has_multiple_ids { // If form has merchant_connector_ids, CSV records should not have merchant_connector_id for (index, record) in records.iter().enumerate() { if record.merchant_connector_id.is_some() { return Err(errors::ApiErrorResponse::InvalidRequestData { message: format!( "Record at line {} has merchant_connector_id but form has merchant_connector_ids. Only one should be provided", index + 1 ), }); } } } Ok(()) } } type MigrationValidationResult = Result< ( common_utils::id_type::MerchantId, Vec<pm_api::PaymentMethodRecord>, Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, ), errors::ApiErrorResponse, >; impl PaymentMethodsMigrateForm { pub fn validate_and_get_payment_method_records(self) -> MigrationValidationResult { // Step 1: Validate form-level conflicts let form_has_single_id = self.merchant_connector_id.is_some(); let form_has_multiple_ids = self.merchant_connector_ids.is_some(); if form_has_single_id && form_has_multiple_ids { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Both merchant_connector_id and merchant_connector_ids cannot be provided" .to_string(), }); } // Ensure at least one is provided if !form_has_single_id && !form_has_multiple_ids { return Err(errors::ApiErrorResponse::InvalidRequestData { message: "Either merchant_connector_id or merchant_connector_ids must be provided" .to_string(), }); } // Step 2: Parse CSV let records = parse_csv(self.file.data.to_bytes()).map_err(|e| { errors::ApiErrorResponse::PreconditionFailed { message: e.to_string(), } })?; // Step 3: Validate CSV vs Form conflicts MerchantConnectorValidator::validate_form_csv_conflicts( &records, form_has_single_id, form_has_multiple_ids, )?; // Step 4: Prepare the merchant connector account IDs for return let mca_ids = if let Some(ref single_id) = self.merchant_connector_id { Some(vec![(**single_id).clone()]) } else if let Some(ref ids_string) = self.merchant_connector_ids { let parsed_ids = MerchantConnectorValidator::parse_comma_separated_ids(ids_string)?; if parsed_ids.is_empty() { None } else { Some(parsed_ids) } } else { None }; // Step 5: Return the updated structure Ok((self.merchant_id.clone(), records, mca_ids)) } } fn parse_csv(data: &[u8]) -> csv::Result<Vec<pm_api::PaymentMethodRecord>> { let mut csv_reader = Reader::from_reader(data); let mut records = Vec::new(); let mut id_counter = 0; for result in csv_reader.deserialize() { let mut record: pm_api::PaymentMethodRecord = result?; id_counter += 1; record.line_number = Some(id_counter); records.push(record); } Ok(records) } #[instrument(skip_all)] pub fn validate_card_expiry( card_exp_month: &masking::Secret<String>, card_exp_year: &masking::Secret<String>, ) -> errors::CustomResult<(), errors::ApiErrorResponse> { let exp_month = card_exp_month .peek() .to_string() .parse::<u8>() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "card_exp_month", })?; ::cards::CardExpirationMonth::try_from(exp_month).change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid Expiry Month".to_string(), }, )?; let year_str = card_exp_year.peek().to_string(); validate_card_exp_year(year_str).change_context( errors::ApiErrorResponse::PreconditionFailed { message: "Invalid Expiry Year".to_string(), }, )?; Ok(()) } fn validate_card_exp_year(year: String) -> Result<(), errors::ValidationError> { let year_str = year.to_string(); if year_str.len() == 2 || year_str.len() == 4 { year_str .parse::<u16>() .map_err(|_| errors::ValidationError::InvalidValue { message: "card_exp_year".to_string(), })?; Ok(()) } else { Err(errors::ValidationError::InvalidValue { message: "invalid card expiration year".to_string(), }) } } #[derive(Debug)] pub struct RecordMigrationStatus { pub card_migrated: Option<bool>, pub network_token_migrated: Option<bool>, pub connector_mandate_details_migrated: Option<bool>, pub network_transaction_migrated: Option<bool>, } #[derive(Debug)] pub struct RecordMigrationStatusBuilder { pub card_migrated: Option<bool>, pub network_token_migrated: Option<bool>, pub connector_mandate_details_migrated: Option<bool>, pub network_transaction_migrated: Option<bool>, } impl RecordMigrationStatusBuilder { pub fn new() -> Self { Self { card_migrated: None, network_token_migrated: None, connector_mandate_details_migrated: None, network_transaction_migrated: None, } } pub fn card_migrated(&mut self, card_migrated: bool) { self.card_migrated = Some(card_migrated); } pub fn network_token_migrated(&mut self, network_token_migrated: Option<bool>) { self.network_token_migrated = network_token_migrated; } pub fn connector_mandate_details_migrated( &mut self, connector_mandate_details_migrated: Option<bool>, ) { self.connector_mandate_details_migrated = connector_mandate_details_migrated; } pub fn network_transaction_id_migrated(&mut self, network_transaction_migrated: Option<bool>) { self.network_transaction_migrated = network_transaction_migrated; } pub fn build(self) -> RecordMigrationStatus { RecordMigrationStatus { card_migrated: self.card_migrated, network_token_migrated: self.network_token_migrated, connector_mandate_details_migrated: self.connector_mandate_details_migrated, network_transaction_migrated: self.network_transaction_migrated, } } } impl Default for RecordMigrationStatusBuilder { fn default() -> Self { Self::new() } }
crates/payment_methods/src/core/migration.rs
payment_methods::src::core::migration
2,339
true
// File: crates/payment_methods/src/core/migration/payment_methods.rs // Module: payment_methods::src::core::migration::payment_methods use std::str::FromStr; #[cfg(feature = "v2")] use api_models::enums as api_enums; #[cfg(feature = "v1")] use api_models::enums; use api_models::payment_methods as pm_api; #[cfg(feature = "v1")] use common_utils::{ consts, crypto::Encryptable, ext_traits::{AsyncExt, ConfigExt}, generate_id, }; use common_utils::{errors::CustomResult, id_type}; use error_stack::ResultExt; use hyperswitch_domain_models::{ api::ApplicationResponse, errors::api_error_response as errors, merchant_context, }; #[cfg(feature = "v1")] use hyperswitch_domain_models::{ext_traits::OptionExt, payment_methods as domain_pm}; use masking::PeekInterface; #[cfg(feature = "v1")] use masking::Secret; #[cfg(feature = "v1")] use router_env::{instrument, logger, tracing}; #[cfg(feature = "v1")] use serde_json::json; use storage_impl::cards_info; #[cfg(feature = "v1")] use crate::{ controller::create_encrypted_data, core::migration, helpers::{ForeignFrom, StorageErrorExt}, }; use crate::{controller::PaymentMethodsController, helpers::ForeignTryFrom, state}; #[cfg(feature = "v1")] pub async fn migrate_payment_method( state: &state::PaymentMethodsState, req: pm_api::PaymentMethodMigrate, merchant_id: &id_type::MerchantId, merchant_context: &merchant_context::MerchantContext, controller: &dyn PaymentMethodsController, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodMigrateResponse>, errors::ApiErrorResponse> { let mut req = req; let card_details = &req.card.get_required_value("card")?; let card_number_validation_result = cards::CardNumber::from_str(card_details.card_number.peek()); let card_bin_details = populate_bin_details_for_masked_card( card_details, &*state.store, req.payment_method_type.as_ref(), ) .await?; req.card = Some(api_models::payment_methods::MigrateCardDetail { card_issuing_country: card_bin_details.issuer_country.clone(), card_network: card_bin_details.card_network.clone(), card_issuer: card_bin_details.card_issuer.clone(), card_type: card_bin_details.card_type.clone(), ..card_details.clone() }); if let Some(connector_mandate_details) = &req.connector_mandate_details { controller .validate_merchant_connector_ids_in_connector_mandate_details( merchant_context.get_merchant_key_store(), connector_mandate_details, merchant_id, card_bin_details.card_network.clone(), ) .await?; }; let should_require_connector_mandate_details = req.network_token.is_none(); let mut migration_status = migration::RecordMigrationStatusBuilder::new(); let resp = match card_number_validation_result { Ok(card_number) => { let payment_method_create_request = pm_api::PaymentMethodCreate::get_payment_method_create_from_payment_method_migrate( card_number, &req, ); logger::debug!("Storing the card in locker and migrating the payment method"); get_client_secret_or_add_payment_method_for_migration( state, payment_method_create_request, merchant_context, &mut migration_status, controller, ) .await? } Err(card_validation_error) => { logger::debug!("Card number to be migrated is invalid, skip saving in locker {card_validation_error}"); skip_locker_call_and_migrate_payment_method( state, &req, merchant_id.to_owned(), merchant_context, card_bin_details.clone(), should_require_connector_mandate_details, &mut migration_status, controller, ) .await? } }; let payment_method_response = match resp { ApplicationResponse::Json(response) => response, _ => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the payment method response")?, }; let pm_id = payment_method_response.payment_method_id.clone(); let network_token = req.network_token.clone(); let network_token_migrated = match network_token { Some(nt_detail) => { logger::debug!("Network token migration"); let network_token_requestor_ref_id = nt_detail.network_token_requestor_ref_id.clone(); let network_token_data = &nt_detail.network_token_data; Some( controller .save_network_token_and_update_payment_method( &req, merchant_context.get_merchant_key_store(), network_token_data, network_token_requestor_ref_id, pm_id, ) .await .map_err(|err| logger::error!(?err, "Failed to save network token")) .ok() .unwrap_or_default(), ) } None => { logger::debug!("Network token data is not available"); None } }; migration_status.network_token_migrated(network_token_migrated); let migrate_status = migration_status.build(); Ok(ApplicationResponse::Json( pm_api::PaymentMethodMigrateResponse { payment_method_response, card_migrated: migrate_status.card_migrated, network_token_migrated: migrate_status.network_token_migrated, connector_mandate_details_migrated: migrate_status.connector_mandate_details_migrated, network_transaction_id_migrated: migrate_status.network_transaction_migrated, }, )) } #[cfg(feature = "v2")] pub async fn migrate_payment_method( _state: &state::PaymentMethodsState, _req: pm_api::PaymentMethodMigrate, _merchant_id: &id_type::MerchantId, _merchant_context: &merchant_context::MerchantContext, _controller: &dyn PaymentMethodsController, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodMigrateResponse>, errors::ApiErrorResponse> { todo!() } #[cfg(feature = "v1")] pub async fn populate_bin_details_for_masked_card( card_details: &api_models::payment_methods::MigrateCardDetail, db: &dyn state::PaymentMethodsStorageInterface, payment_method_type: Option<&enums::PaymentMethodType>, ) -> CustomResult<pm_api::CardDetailFromLocker, errors::ApiErrorResponse> { if let Some( // Cards enums::PaymentMethodType::Credit | enums::PaymentMethodType::Debit // Wallets | enums::PaymentMethodType::ApplePay | enums::PaymentMethodType::GooglePay, ) = payment_method_type { migration::validate_card_expiry( &card_details.card_exp_month, &card_details.card_exp_year, )?; } let card_number = card_details.card_number.clone(); let (card_isin, _last4_digits) = get_card_bin_and_last4_digits_for_masked_card( card_number.peek(), ) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid masked card number".to_string(), })?; let card_bin_details = if card_details.card_issuer.is_some() && card_details.card_network.is_some() && card_details.card_type.is_some() && card_details.card_issuing_country.is_some() { pm_api::CardDetailFromLocker::foreign_try_from((card_details, None))? } else { let card_info = db .get_card_info(&card_isin) .await .map_err(|error| logger::error!(card_info_error=?error)) .ok() .flatten(); pm_api::CardDetailFromLocker::foreign_try_from((card_details, card_info))? }; Ok(card_bin_details) } #[cfg(feature = "v1")] impl ForeignTryFrom<( &api_models::payment_methods::MigrateCardDetail, Option<cards_info::CardInfo>, )> for pm_api::CardDetailFromLocker { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( (card_details, card_info): ( &api_models::payment_methods::MigrateCardDetail, Option<cards_info::CardInfo>, ), ) -> Result<Self, Self::Error> { let (card_isin, last4_digits) = get_card_bin_and_last4_digits_for_masked_card(card_details.card_number.peek()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid masked card number".to_string(), })?; if let Some(card_bin_info) = card_info { Ok(Self { scheme: card_details .card_network .clone() .or(card_bin_info.card_network.clone()) .map(|card_network| card_network.to_string()), last4_digits: Some(last4_digits.clone()), issuer_country: card_details .card_issuing_country .clone() .or(card_bin_info.card_issuing_country), card_number: None, expiry_month: Some(card_details.card_exp_month.clone()), expiry_year: Some(card_details.card_exp_year.clone()), card_token: None, card_fingerprint: None, card_holder_name: card_details.card_holder_name.clone(), nick_name: card_details.nick_name.clone(), card_isin: Some(card_isin.clone()), card_issuer: card_details .card_issuer .clone() .or(card_bin_info.card_issuer), card_network: card_details .card_network .clone() .or(card_bin_info.card_network), card_type: card_details.card_type.clone().or(card_bin_info.card_type), saved_to_locker: false, }) } else { Ok(Self { scheme: card_details .card_network .clone() .map(|card_network| card_network.to_string()), last4_digits: Some(last4_digits.clone()), issuer_country: card_details.card_issuing_country.clone(), card_number: None, expiry_month: Some(card_details.card_exp_month.clone()), expiry_year: Some(card_details.card_exp_year.clone()), card_token: None, card_fingerprint: None, card_holder_name: card_details.card_holder_name.clone(), nick_name: card_details.nick_name.clone(), card_isin: Some(card_isin.clone()), card_issuer: card_details.card_issuer.clone(), card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker: false, }) } } } #[cfg(feature = "v2")] impl ForeignTryFrom<( &api_models::payment_methods::MigrateCardDetail, Option<cards_info::CardInfo>, )> for pm_api::CardDetailFromLocker { type Error = error_stack::Report<errors::ApiErrorResponse>; fn foreign_try_from( (card_details, card_info): ( &api_models::payment_methods::MigrateCardDetail, Option<cards_info::CardInfo>, ), ) -> Result<Self, Self::Error> { let (card_isin, last4_digits) = get_card_bin_and_last4_digits_for_masked_card(card_details.card_number.peek()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid masked card number".to_string(), })?; if let Some(card_bin_info) = card_info { Ok(Self { last4_digits: Some(last4_digits.clone()), issuer_country: card_details .card_issuing_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten() .or(card_bin_info .card_issuing_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten()), card_number: None, expiry_month: Some(card_details.card_exp_month.clone()), expiry_year: Some(card_details.card_exp_year.clone()), card_fingerprint: None, card_holder_name: card_details.card_holder_name.clone(), nick_name: card_details.nick_name.clone(), card_isin: Some(card_isin.clone()), card_issuer: card_details .card_issuer .clone() .or(card_bin_info.card_issuer), card_network: card_details .card_network .clone() .or(card_bin_info.card_network), card_type: card_details.card_type.clone().or(card_bin_info.card_type), saved_to_locker: false, }) } else { Ok(Self { last4_digits: Some(last4_digits.clone()), issuer_country: card_details .card_issuing_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten(), card_number: None, expiry_month: Some(card_details.card_exp_month.clone()), expiry_year: Some(card_details.card_exp_year.clone()), card_fingerprint: None, card_holder_name: card_details.card_holder_name.clone(), nick_name: card_details.nick_name.clone(), card_isin: Some(card_isin.clone()), card_issuer: card_details.card_issuer.clone(), card_network: card_details.card_network.clone(), card_type: card_details.card_type.clone(), saved_to_locker: false, }) } } } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn get_client_secret_or_add_payment_method_for_migration( state: &state::PaymentMethodsState, req: pm_api::PaymentMethodCreate, merchant_context: &merchant_context::MerchantContext, migration_status: &mut migration::RecordMigrationStatusBuilder, controller: &dyn PaymentMethodsController, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> { let merchant_id = merchant_context.get_merchant_account().get_id(); let customer_id = req.customer_id.clone().get_required_value("customer_id")?; #[cfg(not(feature = "payouts"))] let condition = req.card.is_some(); #[cfg(feature = "payouts")] let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some(); let key_manager_state = &state.into(); let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() .async_map(|billing| { create_encrypted_data( key_manager_state, merchant_context.get_merchant_key_store(), billing, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method billing address")?; let connector_mandate_details = req .connector_mandate_details .clone() .map(serde_json::to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError)?; if condition { Box::pin(save_migration_payment_method( req, migration_status, controller, )) .await } else { let payment_method_id = generate_id(consts::ID_LENGTH, "pm"); let res = controller .create_payment_method( &req, &customer_id, payment_method_id.as_str(), None, merchant_id, None, None, None, connector_mandate_details.clone(), Some(enums::PaymentMethodStatus::AwaitingData), None, payment_method_billing_address, None, None, None, None, Default::default(), ) .await?; migration_status.connector_mandate_details_migrated( connector_mandate_details .clone() .and_then(|val| (val != json!({})).then_some(true)) .or_else(|| { req.connector_mandate_details .clone() .and_then(|val| (!val.0.is_empty()).then_some(false)) }), ); //card is not migrated in this case migration_status.card_migrated(false); if res.status == enums::PaymentMethodStatus::AwaitingData { controller .add_payment_method_status_update_task( &res, enums::PaymentMethodStatus::AwaitingData, enums::PaymentMethodStatus::Inactive, merchant_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to add payment method status update task in process tracker", )?; } Ok(ApplicationResponse::Json( pm_api::PaymentMethodResponse::foreign_from((None, res)), )) } } #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn skip_locker_call_and_migrate_payment_method( state: &state::PaymentMethodsState, req: &pm_api::PaymentMethodMigrate, merchant_id: id_type::MerchantId, merchant_context: &merchant_context::MerchantContext, card: pm_api::CardDetailFromLocker, should_require_connector_mandate_details: bool, migration_status: &mut migration::RecordMigrationStatusBuilder, controller: &dyn PaymentMethodsController, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> { let db = &*state.store; let customer_id = req.customer_id.clone().get_required_value("customer_id")?; // In this case, since we do not have valid card details, recurring payments can only be done through connector mandate details. //if network token data is present, then connector mandate details are not mandatory let connector_mandate_details = if should_require_connector_mandate_details { let connector_mandate_details_req = req .connector_mandate_details .clone() .and_then(|c| c.payments) .clone() .get_required_value("connector mandate details")?; Some( serde_json::to_value(&connector_mandate_details_req) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse connector mandate details")?, ) } else { req.connector_mandate_details .clone() .and_then(|c| c.payments) .map(|mandate_details_req| { serde_json::to_value(&mandate_details_req) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse connector mandate details") }) .transpose()? }; let key_manager_state = &state.into(); let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() .async_map(|billing| { create_encrypted_data( key_manager_state, merchant_context.get_merchant_key_store(), billing, ) }) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method billing address")?; let customer = db .find_customer_by_customer_id_merchant_id( &state.into(), &customer_id, &merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; let payment_method_card_details = pm_api::PaymentMethodsData::Card( pm_api::CardDetailsPaymentMethod::from((card.clone(), None)), ); let payment_method_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = Some( create_encrypted_data( &state.into(), merchant_context.get_merchant_key_store(), payment_method_card_details, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method card details")?, ); let payment_method_metadata: Option<serde_json::Value> = req.metadata.as_ref().map(|data| data.peek()).cloned(); let network_transaction_id = req.network_transaction_id.clone(); let payment_method_id = generate_id(consts::ID_LENGTH, "pm"); let current_time = common_utils::date_time::now(); let response = db .insert_payment_method( &state.into(), merchant_context.get_merchant_key_store(), domain_pm::PaymentMethod { customer_id: customer_id.to_owned(), merchant_id: merchant_id.to_owned(), payment_method_id: payment_method_id.to_string(), locker_id: None, payment_method: req.payment_method, payment_method_type: req.payment_method_type, payment_method_issuer: req.payment_method_issuer.clone(), scheme: req.card_network.clone().or(card.scheme.clone()), metadata: payment_method_metadata.map(Secret::new), payment_method_data: payment_method_data_encrypted, connector_mandate_details: connector_mandate_details.clone(), customer_acceptance: None, client_secret: None, status: enums::PaymentMethodStatus::Active, network_transaction_id: network_transaction_id.clone(), payment_method_issuer_code: None, accepted_currency: None, token: None, cardholder_name: None, issuer_name: None, issuer_country: None, payer_country: None, is_stored: None, swift_code: None, direct_debit_token: None, created_at: current_time, last_modified: current_time, last_used_at: current_time, payment_method_billing_address, updated_by: None, version: common_types::consts::API_VERSION, network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, vault_source_details: Default::default(), }, merchant_context.get_merchant_account().storage_scheme, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; logger::debug!("Payment method inserted in db"); migration_status.network_transaction_id_migrated( network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)), ); migration_status.connector_mandate_details_migrated( connector_mandate_details .clone() .and_then(|val| if val == json!({}) { None } else { Some(true) }) .or_else(|| { req.connector_mandate_details.clone().and_then(|val| { val.payments .and_then(|payin_val| (!payin_val.0.is_empty()).then_some(false)) }) }), ); if customer.default_payment_method_id.is_none() && req.payment_method.is_some() { let _ = controller .set_default_payment_method(&merchant_id, &customer_id, payment_method_id.to_owned()) .await .map_err(|error| logger::error!(?error, "Failed to set the payment method as default")); } Ok(ApplicationResponse::Json( pm_api::PaymentMethodResponse::foreign_from((Some(card), response)), )) } // need to discuss regarding the migration APIs for v2 #[cfg(feature = "v2")] pub async fn skip_locker_call_and_migrate_payment_method( _state: state::PaymentMethodsState, _req: &pm_api::PaymentMethodMigrate, _merchant_id: id_type::MerchantId, _merchant_context: &merchant_context::MerchantContext, _card: pm_api::CardDetailFromLocker, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> { todo!() } pub fn get_card_bin_and_last4_digits_for_masked_card( masked_card_number: &str, ) -> Result<(String, String), cards::CardNumberValidationErr> { let last4_digits = masked_card_number .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(); let card_isin = masked_card_number.chars().take(6).collect::<String>(); cards::validate::validate_card_number_chars(&card_isin) .and_then(|_| cards::validate::validate_card_number_chars(&last4_digits))?; Ok((card_isin, last4_digits)) } #[cfg(feature = "v1")] #[instrument(skip_all)] pub async fn save_migration_payment_method( req: pm_api::PaymentMethodCreate, migration_status: &mut migration::RecordMigrationStatusBuilder, controller: &dyn PaymentMethodsController, ) -> CustomResult<ApplicationResponse<pm_api::PaymentMethodResponse>, errors::ApiErrorResponse> { let connector_mandate_details = req .connector_mandate_details .clone() .map(serde_json::to_value) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError)?; let network_transaction_id = req.network_transaction_id.clone(); let res = controller.add_payment_method(&req).await?; migration_status.card_migrated(true); migration_status.network_transaction_id_migrated( network_transaction_id.and_then(|val| (!val.is_empty_after_trim()).then_some(true)), ); migration_status.connector_mandate_details_migrated( connector_mandate_details .and_then(|val| if val == json!({}) { None } else { Some(true) }) .or_else(|| { req.connector_mandate_details .and_then(|val| (!val.0.is_empty()).then_some(false)) }), ); Ok(res) }
crates/payment_methods/src/core/migration/payment_methods.rs
payment_methods::src::core::migration::payment_methods
5,542
true
// File: crates/payment_methods/src/configs/payment_connector_required_fields.rs // Module: payment_methods::src::configs::payment_connector_required_fields use std::collections::{HashMap, HashSet}; use api_models::{ enums::{self, Connector, FieldType}, payment_methods::RequiredFieldInfo, }; use crate::configs::settings::{ BankRedirectConfig, ConnectorFields, Mandates, RequiredFieldFinal, SupportedConnectorsForMandate, SupportedPaymentMethodTypesForMandate, SupportedPaymentMethodsForMandate, ZeroMandates, }; #[cfg(feature = "v1")] use crate::configs::settings::{PaymentMethodType, RequiredFields}; impl Default for ZeroMandates { fn default() -> Self { Self { supported_payment_methods: SupportedPaymentMethodsForMandate(HashMap::new()), } } } 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([Connector::Adyen]), }, )])), ), ( enums::PaymentMethod::Wallet, SupportedPaymentMethodTypesForMandate(HashMap::from([ ( enums::PaymentMethodType::GooglePay, SupportedConnectorsForMandate { connector_list: HashSet::from([ Connector::Stripe, Connector::Adyen, Connector::Globalpay, Connector::Multisafepay, Connector::Bankofamerica, Connector::Novalnet, Connector::Noon, Connector::Cybersource, Connector::Wellsfargo, ]), }, ), ( enums::PaymentMethodType::ApplePay, SupportedConnectorsForMandate { connector_list: HashSet::from([ Connector::Stripe, Connector::Adyen, Connector::Bankofamerica, Connector::Cybersource, Connector::Novalnet, Connector::Wellsfargo, ]), }, ), ( enums::PaymentMethodType::SamsungPay, SupportedConnectorsForMandate { connector_list: HashSet::from([Connector::Cybersource]), }, ), ])), ), ( enums::PaymentMethod::Card, SupportedPaymentMethodTypesForMandate(HashMap::from([ ( enums::PaymentMethodType::Credit, SupportedConnectorsForMandate { connector_list: HashSet::from([ Connector::Aci, Connector::Adyen, Connector::Authorizedotnet, Connector::Globalpay, Connector::Worldpay, Connector::Fiuu, Connector::Multisafepay, Connector::Nexinets, Connector::Noon, Connector::Novalnet, Connector::Payme, Connector::Stripe, Connector::Bankofamerica, Connector::Cybersource, Connector::Wellsfargo, ]), }, ), ( enums::PaymentMethodType::Debit, SupportedConnectorsForMandate { connector_list: HashSet::from([ Connector::Aci, Connector::Adyen, Connector::Authorizedotnet, Connector::Globalpay, Connector::Worldpay, Connector::Fiuu, Connector::Multisafepay, Connector::Nexinets, Connector::Noon, Connector::Novalnet, Connector::Payme, Connector::Stripe, ]), }, ), ])), ), ])), update_mandate_supported: SupportedPaymentMethodsForMandate(HashMap::default()), } } } #[derive(Clone, serde::Serialize)] #[cfg_attr(feature = "v2", allow(dead_code))] // multiple variants are never constructed for v2 enum RequiredField { CardNumber, CardExpMonth, CardExpYear, CardCvc, CardNetwork, BillingUserFirstName, BillingUserLastName, /// display name and field type for billing first name BillingFirstName(&'static str, FieldType), /// display name and field type for billing last name BillingLastName(&'static str, FieldType), BillingEmail, Email, BillingPhone, BillingPhoneCountryCode, BillingAddressLine1, BillingAddressLine2, BillingAddressCity, BillingAddressState, BillingAddressZip, BillingCountries(Vec<&'static str>), BillingAddressCountries(Vec<&'static str>), ShippingFirstName, ShippingLastName, ShippingAddressCity, ShippingAddressState, ShippingAddressZip, ShippingCountries(Vec<&'static str>), ShippingAddressCountries(Vec<&'static str>), ShippingAddressLine1, ShippingAddressLine2, ShippingPhone, ShippingPhoneCountryCode, ShippingEmail, OpenBankingUkIssuer, OpenBankingCzechRepublicIssuer, OpenBankingPolandIssuer, OpenBankingSlovakiaIssuer, OpenBankingFpxIssuer, OpenBankingThailandIssuer, BanContactCardNumber, BanContactCardExpMonth, BanContactCardExpYear, IdealBankName, EpsBankName, EpsBankOptions(HashSet<enums::BankNames>), BlikCode, MifinityDateOfBirth, MifinityLanguagePreference(Vec<&'static str>), CryptoNetwork, CyptoPayCurrency(Vec<&'static str>), BoletoSocialSecurityNumber, UpiCollectVpaId, AchBankDebitAccountNumber, AchBankDebitRoutingNumber, AchBankDebitBankType(Vec<enums::BankType>), AchBankDebitBankAccountHolderName, SepaBankDebitIban, BacsBankDebitAccountNumber, BacsBankDebitSortCode, BecsBankDebitAccountNumber, BecsBankDebitBsbNumber, BecsBankDebitSortCode, PixKey, PixCnpj, PixCpf, PixSourceBankAccountId, GiftCardNumber, GiftCardCvc, DcbMsisdn, DcbClientUid, OrderDetailsProductName, Description, } impl RequiredField { fn to_tuple(&self) -> (String, RequiredFieldInfo) { match self { Self::CardNumber => ( "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: FieldType::UserCardNumber, value: None, }, ), Self::CardExpMonth => ( "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: FieldType::UserCardExpiryMonth, value: None, }, ), Self::CardExpYear => ( "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: FieldType::UserCardExpiryYear, value: None, }, ), Self::CardCvc => ( "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: FieldType::UserCardCvc, value: None, }, ), Self::CardNetwork => ( "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: FieldType::UserCardNetwork, value: None, }, ), Self::BillingUserFirstName => ( "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: FieldType::UserFullName, value: None, }, ), Self::BillingUserLastName => ( "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: FieldType::UserFullName, value: None, }, ), Self::BillingFirstName(display_name, field_type) => ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.first_name".to_string(), display_name: display_name.to_string(), field_type: field_type.clone(), value: None, }, ), Self::BillingLastName(display_name, field_type) => ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.last_name".to_string(), display_name: display_name.to_string(), field_type: field_type.clone(), value: None, }, ), Self::Email => ( "email".to_string(), RequiredFieldInfo { required_field: "email".to_string(), display_name: "email".to_string(), field_type: FieldType::UserEmailAddress, value: None, }, ), Self::BillingEmail => ( "billing.email".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.email".to_string(), display_name: "email".to_string(), field_type: FieldType::UserEmailAddress, value: None, }, ), Self::BillingPhone => ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: FieldType::UserPhoneNumber, value: None, }, ), Self::BillingPhoneCountryCode => ( "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: FieldType::UserPhoneNumberCountryCode, value: None, }, ), Self::BillingAddressLine1 => ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line1".to_string(), display_name: "line1".to_string(), field_type: FieldType::UserAddressLine1, value: None, }, ), Self::BillingAddressLine2 => ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.line2".to_string(), display_name: "line2".to_string(), field_type: FieldType::UserAddressLine2, value: None, }, ), Self::BillingAddressCity => ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.city".to_string(), display_name: "city".to_string(), field_type: FieldType::UserAddressCity, value: None, }, ), Self::BillingAddressState => ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.state".to_string(), display_name: "state".to_string(), field_type: FieldType::UserAddressState, value: None, }, ), Self::BillingAddressZip => ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.zip".to_string(), display_name: "zip".to_string(), field_type: FieldType::UserAddressPincode, value: None, }, ), Self::BillingCountries(countries) => ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: FieldType::UserCountry { options: countries.iter().map(|c| c.to_string()).collect(), }, value: None, }, ), Self::BillingAddressCountries(countries) => ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: FieldType::UserAddressCountry { options: countries.iter().map(|c| c.to_string()).collect(), }, value: None, }, ), Self::ShippingFirstName => ( "shipping.address.first_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.first_name".to_string(), display_name: "shipping_first_name".to_string(), field_type: FieldType::UserShippingName, value: None, }, ), Self::ShippingLastName => ( "shipping.address.last_name".to_string(), RequiredFieldInfo { required_field: "shipping.address.last_name".to_string(), display_name: "shipping_last_name".to_string(), field_type: FieldType::UserShippingName, value: None, }, ), Self::ShippingAddressCity => ( "shipping.address.city".to_string(), RequiredFieldInfo { required_field: "shipping.address.city".to_string(), display_name: "city".to_string(), field_type: FieldType::UserShippingAddressCity, value: None, }, ), Self::ShippingAddressState => ( "shipping.address.state".to_string(), RequiredFieldInfo { required_field: "shipping.address.state".to_string(), display_name: "state".to_string(), field_type: FieldType::UserShippingAddressState, value: None, }, ), Self::ShippingAddressZip => ( "shipping.address.zip".to_string(), RequiredFieldInfo { required_field: "shipping.address.zip".to_string(), display_name: "zip".to_string(), field_type: FieldType::UserShippingAddressPincode, value: None, }, ), Self::ShippingCountries(countries) => ( "shipping.address.country".to_string(), RequiredFieldInfo { required_field: "shipping.address.country".to_string(), display_name: "country".to_string(), field_type: FieldType::UserCountry { options: countries.iter().map(|c| c.to_string()).collect(), }, value: None, }, ), Self::ShippingAddressCountries(countries) => ( "shipping.address.country".to_string(), RequiredFieldInfo { required_field: "shipping.address.country".to_string(), display_name: "country".to_string(), field_type: FieldType::UserShippingAddressCountry { options: countries.iter().map(|c| c.to_string()).collect(), }, value: None, }, ), Self::ShippingAddressLine1 => ( "shipping.address.line1".to_string(), RequiredFieldInfo { required_field: "shipping.address.line1".to_string(), display_name: "line1".to_string(), field_type: FieldType::UserShippingAddressLine1, value: None, }, ), Self::ShippingAddressLine2 => ( "shipping.address.line2".to_string(), RequiredFieldInfo { required_field: "shipping.address.line2".to_string(), display_name: "line2".to_string(), field_type: FieldType::UserShippingAddressLine2, value: None, }, ), Self::ShippingPhone => ( "shipping.phone.number".to_string(), RequiredFieldInfo { required_field: "shipping.phone.number".to_string(), display_name: "phone_number".to_string(), field_type: FieldType::UserPhoneNumber, value: None, }, ), Self::ShippingPhoneCountryCode => ( "shipping.phone.country_code".to_string(), RequiredFieldInfo { required_field: "shipping.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: FieldType::UserPhoneNumberCountryCode, value: None, }, ), Self::ShippingEmail => ( "shipping.email".to_string(), RequiredFieldInfo { required_field: "shipping.email".to_string(), display_name: "email".to_string(), field_type: FieldType::UserEmailAddress, value: None, }, ), Self::OpenBankingUkIssuer => ( "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: FieldType::UserBank, value: None, }, ), Self::OpenBankingCzechRepublicIssuer => ( "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: FieldType::UserBank, value: None, }, ), Self::OpenBankingPolandIssuer => ( "payment_method_data.bank_redirect.online_banking_poland.issuer".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_redirect.online_banking_poland.issuer".to_string(), display_name: "issuer".to_string(), field_type: FieldType::UserBank, value: None, }, ), Self::OpenBankingSlovakiaIssuer => ( "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: FieldType::UserBank, value: None, }, ), Self::OpenBankingFpxIssuer => ( "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: FieldType::UserBank, value: None, }, ), Self::OpenBankingThailandIssuer => ( "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: FieldType::UserBank, value: None, }, ), Self::BanContactCardNumber => ( "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: FieldType::UserCardNumber, value: None, }, ), Self::BanContactCardExpMonth => ( "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: FieldType::UserCardExpiryMonth, value: None, }, ), Self::BanContactCardExpYear => ( "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: FieldType::UserCardExpiryYear, value: None, }, ), Self::IdealBankName => ( "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: FieldType::UserBank, value: None, }, ), Self::EpsBankName => ( "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: FieldType::UserBank, value: None, }, ), Self::EpsBankOptions(bank) => ( "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: FieldType::UserBankOptions { options: bank.iter().map(|bank| bank.to_string()).collect(), }, value: None, }, ), Self::BlikCode => ( "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: FieldType::UserBlikCode, value: None, }, ), Self::MifinityDateOfBirth => ( "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: FieldType::UserDateOfBirth, value: None, }, ), Self::MifinityLanguagePreference(languages) => ( "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: FieldType::LanguagePreference { options: languages.iter().map(|l| l.to_string()).collect(), }, value: None, }, ), Self::CryptoNetwork => ( "payment_method_data.crypto.network".to_string(), RequiredFieldInfo { required_field: "payment_method_data.crypto.network".to_string(), display_name: "network".to_string(), field_type: FieldType::UserCryptoCurrencyNetwork, value: None, }, ), Self::CyptoPayCurrency(currencies) => ( "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: FieldType::UserCurrency { options: currencies.iter().map(|c| c.to_string()).collect(), }, value: None, }, ), Self::BoletoSocialSecurityNumber => ( "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: FieldType::UserSocialSecurityNumber, value: None, }, ), Self::UpiCollectVpaId => ( "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: FieldType::UserVpaId, value: None, }, ), Self::AchBankDebitAccountNumber => ( "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: FieldType::UserBankAccountNumber, value: None, }, ), Self::AchBankDebitRoutingNumber => ( "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: FieldType::UserBankRoutingNumber, value: None, }, ), Self::AchBankDebitBankType(bank_type) => ( "payment_method_data.bank_debit.ach_bank_debit.bank_type".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.ach_bank_debit.bank_type" .to_string(), display_name: "bank_type".to_string(), field_type: FieldType::UserBankType { options: bank_type.iter().map(|bt| bt.to_string()).collect(), }, value: None, }, ), Self::AchBankDebitBankAccountHolderName => ( "payment_method_data.bank_debit.ach_bank_debit.bank_account_holder_name" .to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_debit.ach_bank_debit.bank_account_holder_name" .to_string(), display_name: "bank_account_holder_name".to_string(), field_type: FieldType::UserBankAccountHolderName, value: None, }, ), Self::SepaBankDebitIban => ( "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: FieldType::UserIban, value: None, }, ), Self::BacsBankDebitAccountNumber => ( "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: FieldType::UserBankAccountNumber, value: None, }, ), Self::BacsBankDebitSortCode => ( "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: FieldType::UserBankSortCode, value: None, }, ), Self::BecsBankDebitAccountNumber => ( "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: FieldType::UserBankAccountNumber, value: None, }, ), Self::BecsBankDebitBsbNumber => ( "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: FieldType::UserBsbNumber, value: None, }, ), Self::BecsBankDebitSortCode => ( "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: FieldType::UserBankSortCode, value: None, }, ), Self::PixKey => ( "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: FieldType::UserPixKey, value: None, }, ), Self::PixCnpj => ( "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: FieldType::UserCnpj, value: None, }, ), Self::PixCpf => ( "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: FieldType::UserCpf, value: None, }, ), Self::PixSourceBankAccountId => ( "payment_method_data.bank_transfer.pix.source_bank_account_id".to_string(), RequiredFieldInfo { required_field: "payment_method_data.bank_transfer.pix.source_bank_account_id" .to_string(), display_name: "source_bank_account_id".to_string(), field_type: FieldType::UserSourceBankAccountId, value: None, }, ), Self::GiftCardNumber => ( "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: FieldType::UserCardNumber, value: None, }, ), Self::GiftCardCvc => ( "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: FieldType::UserCardCvc, value: None, }, ), Self::DcbMsisdn => ( "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: FieldType::UserMsisdn, value: None, }, ), Self::DcbClientUid => ( "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: FieldType::UserClientIdentifier, value: None, }, ), Self::OrderDetailsProductName => ( "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: FieldType::OrderDetailsProductName, value: None, }, ), Self::Description => ( "description".to_string(), RequiredFieldInfo { required_field: "description".to_string(), display_name: "description".to_string(), field_type: FieldType::Text, value: None, }, ), } } } // Define helper functions for common field groups #[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn card_basic() -> Vec<RequiredField> { vec![ RequiredField::CardNumber, RequiredField::CardExpMonth, RequiredField::CardExpYear, RequiredField::CardCvc, ] } #[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn full_name() -> Vec<RequiredField> { vec![ RequiredField::BillingUserFirstName, RequiredField::BillingUserLastName, ] } #[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn billing_name() -> Vec<RequiredField> { vec![ RequiredField::BillingFirstName("billing_first_name", FieldType::UserBillingName), RequiredField::BillingLastName("billing_last_name", FieldType::UserBillingName), ] } #[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn billing_email_billing_name() -> Vec<RequiredField> { vec![ RequiredField::BillingEmail, RequiredField::BillingFirstName("billing_first_name", FieldType::UserBillingName), RequiredField::BillingLastName("billing_last_name", FieldType::UserBillingName), ] } #[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn billing_email_billing_name_phone() -> Vec<RequiredField> { vec![ RequiredField::BillingFirstName("billing_first_name", FieldType::UserBillingName), RequiredField::BillingLastName("billing_last_name", FieldType::UserBillingName), RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ] } #[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn email() -> Vec<RequiredField> { [RequiredField::Email].to_vec() } #[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn billing_email() -> Vec<RequiredField> { [RequiredField::BillingEmail].to_vec() } #[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn card_with_name() -> Vec<RequiredField> { [card_basic(), full_name()].concat() } #[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn billing_email_name() -> Vec<RequiredField> { vec![ RequiredField::BillingEmail, RequiredField::BillingUserFirstName, RequiredField::BillingUserLastName, ] } #[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn billing_address() -> Vec<RequiredField> { vec![ RequiredField::BillingAddressCity, RequiredField::BillingAddressState, RequiredField::BillingAddressZip, RequiredField::BillingAddressCountries(vec!["ALL"]), RequiredField::BillingAddressLine1, ] } /// Define the mandate, non-mandate, and common required fields for a connector /// Eg: fields(vec![RequiredField::CardNumber], vec![RequiredField::BillingEmail], vec![RequiredField::BillingAddressCity]) #[cfg(feature = "v1")] fn fields( mandate: Vec<RequiredField>, non_mandate: Vec<RequiredField>, common: Vec<RequiredField>, ) -> RequiredFieldFinal { let mandate_fields: HashMap<_, _> = mandate.iter().map(|f| f.to_tuple()).collect(); let non_mandate_fields: HashMap<_, _> = non_mandate.iter().map(|f| f.to_tuple()).collect(); let common_fields: HashMap<_, _> = common.iter().map(|f| f.to_tuple()).collect(); RequiredFieldFinal { mandate: mandate_fields, non_mandate: non_mandate_fields, common: common_fields, } } #[cfg_attr(feature = "v2", allow(dead_code))] // This function is not used in v2 fn connectors(connectors: Vec<(Connector, RequiredFieldFinal)>) -> ConnectorFields { ConnectorFields { fields: connectors.into_iter().collect(), } } pub fn get_billing_required_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ RequiredField::BillingFirstName("billing_first_name", FieldType::UserBillingName) .to_tuple(), RequiredField::BillingLastName("billing_last_name", FieldType::UserBillingName).to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressLine2.to_tuple(), RequiredField::BillingPhone.to_tuple(), RequiredField::BillingPhoneCountryCode.to_tuple(), RequiredField::BillingEmail.to_tuple(), ]) } pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ RequiredField::ShippingFirstName.to_tuple(), RequiredField::ShippingLastName.to_tuple(), RequiredField::ShippingAddressCity.to_tuple(), RequiredField::ShippingAddressState.to_tuple(), RequiredField::ShippingAddressZip.to_tuple(), RequiredField::ShippingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::ShippingAddressLine1.to_tuple(), RequiredField::ShippingPhone.to_tuple(), RequiredField::ShippingPhoneCountryCode.to_tuple(), RequiredField::ShippingEmail.to_tuple(), ]) } #[cfg(feature = "v1")] impl RequiredFields { pub fn new(bank_config: &BankRedirectConfig) -> Self { let cards_required_fields = get_cards_required_fields(); let mut debit_required_fields = cards_required_fields.clone(); debit_required_fields.extend(HashMap::from([ ( Connector::Bankofamerica, fields( vec![], vec![], [card_basic(), email(), full_name(), billing_address()].concat(), ), ), ( Connector::Getnet, fields( vec![], vec![], [card_basic(), vec![RequiredField::CardNetwork]].concat(), ), ), ])); Self(HashMap::from([ ( enums::PaymentMethod::Card, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::Debit, ConnectorFields { fields: cards_required_fields.clone(), }, ), ( enums::PaymentMethodType::Credit, ConnectorFields { fields: debit_required_fields.clone(), }, ), ])), ), ( enums::PaymentMethod::BankRedirect, PaymentMethodType(get_bank_redirect_required_fields(bank_config)), ), ( enums::PaymentMethod::Wallet, PaymentMethodType(get_wallet_required_fields()), ), ( enums::PaymentMethod::PayLater, PaymentMethodType(get_pay_later_required_fields()), ), ( enums::PaymentMethod::Crypto, PaymentMethodType(HashMap::from([( enums::PaymentMethodType::CryptoCurrency, connectors(vec![( Connector::Cryptopay, fields( vec![], vec![ RequiredField::CyptoPayCurrency(vec![ "BTC", "LTC", "ETH", "XRP", "XLM", "BCH", "ADA", "SOL", "SHIB", "TRX", "DOGE", "BNB", "USDT", "USDC", "DAI", ]), RequiredField::CryptoNetwork, ], vec![], ), )]), )])), ), ( enums::PaymentMethod::Voucher, PaymentMethodType(get_voucher_required_fields()), ), ( enums::PaymentMethod::Upi, PaymentMethodType(HashMap::from([( enums::PaymentMethodType::UpiCollect, connectors(vec![ ( Connector::Razorpay, fields( vec![], vec![], vec![ RequiredField::UpiCollectVpaId, RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ], ), ), ( Connector::Phonepe, fields( vec![], vec![], vec![ RequiredField::UpiCollectVpaId, RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ], ), ), ( Connector::Paytm, fields( vec![], vec![], vec![ RequiredField::UpiCollectVpaId, RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ], ), ), ]), )])), ), ( enums::PaymentMethod::BankDebit, PaymentMethodType(get_bank_debit_required_fields()), ), ( enums::PaymentMethod::BankTransfer, PaymentMethodType(get_bank_transfer_required_fields()), ), ( enums::PaymentMethod::GiftCard, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::PaySafeCard, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::Givex, connectors(vec![( Connector::Adyen, fields( vec![], vec![RequiredField::GiftCardNumber, RequiredField::GiftCardCvc], vec![], ), )]), ), ])), ), ( enums::PaymentMethod::CardRedirect, PaymentMethodType(HashMap::from([ ( enums::PaymentMethodType::Benefit, connectors(vec![( Connector::Adyen, fields( vec![], vec![ RequiredField::BillingFirstName( "first_name", FieldType::UserFullName, ), RequiredField::BillingLastName( "last_name", FieldType::UserFullName, ), RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ], vec![], ), )]), ), ( enums::PaymentMethodType::Knet, connectors(vec![( Connector::Adyen, fields( vec![], vec![ RequiredField::BillingFirstName( "first_name", FieldType::UserFullName, ), RequiredField::BillingLastName( "last_name", FieldType::UserFullName, ), RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ], vec![], ), )]), ), ( enums::PaymentMethodType::MomoAtm, connectors(vec![( Connector::Adyen, fields( vec![], vec![ RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ], vec![], ), )]), ), ])), ), ( enums::PaymentMethod::MobilePayment, PaymentMethodType(HashMap::from([( enums::PaymentMethodType::DirectCarrierBilling, connectors(vec![( Connector::Digitalvirgo, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::DcbMsisdn.to_tuple(), RequiredField::DcbClientUid.to_tuple(), RequiredField::OrderDetailsProductName.to_tuple(), ]), }, )]), )])), ), ])) } } #[cfg(feature = "v1")] impl Default for RequiredFields { fn default() -> Self { Self::new(&BankRedirectConfig::default()) } } #[cfg(feature = "v1")] fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> { HashMap::from([ (Connector::Aci, fields(vec![], vec![], card_with_name())), (Connector::Authipay, fields(vec![], vec![], card_basic())), (Connector::Adyen, fields(vec![], vec![], card_with_name())), (Connector::Airwallex, fields(vec![], card_basic(), vec![])), ( Connector::Authorizedotnet, fields(vec![], vec![], card_basic()), ), ( Connector::Bambora, fields(vec![], [card_with_name(), billing_email()].concat(), vec![]), ), ( Connector::Bankofamerica, fields( vec![], vec![], [card_basic(), email(), full_name(), billing_address()].concat(), ), ), ( Connector::Barclaycard, fields( vec![], vec![], [card_basic(), email(), full_name(), billing_address()].concat(), ), ), (Connector::Billwerk, fields(vec![], vec![], card_basic())), ( Connector::Bluesnap, fields( vec![], [card_basic(), email(), full_name()].concat(), vec![], ), ), (Connector::Boku, fields(vec![], vec![], card_basic())), (Connector::Braintree, fields(vec![], vec![], card_basic())), (Connector::Celero, fields(vec![], vec![], card_basic())), (Connector::Checkout, fields(vec![], card_basic(), vec![])), ( Connector::Coinbase, fields(vec![], vec![RequiredField::BillingUserFirstName], vec![]), ), ( Connector::Cybersource, fields( vec![], vec![], [card_with_name(), billing_email(), billing_address()].concat(), ), ), ( Connector::Datatrans, fields(vec![], vec![], [billing_email(), card_with_name()].concat()), ), ( Connector::Deutschebank, fields( vec![], [ card_basic(), email(), billing_address(), vec![ RequiredField::BillingFirstName("first_name", FieldType::UserFullName), RequiredField::BillingLastName("last_name", FieldType::UserFullName), ], ] .concat(), vec![], ), ), ( Connector::Dlocal, fields( vec![], [ card_with_name(), vec![RequiredField::BillingAddressCountries(vec!["ALL"])], ] .concat(), vec![], ), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector1, fields(vec![], vec![], card_basic()), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector2, fields(vec![], vec![], card_basic()), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector3, fields(vec![], vec![], card_basic()), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector4, fields(vec![], vec![], card_basic()), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector5, fields(vec![], vec![], card_basic()), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector6, fields(vec![], vec![], card_basic()), ), #[cfg(feature = "dummy_connector")] ( Connector::DummyConnector7, fields(vec![], vec![], card_basic()), ), ( Connector::Elavon, fields(vec![], [card_basic(), billing_email()].concat(), vec![]), ), (Connector::Fiserv, fields(vec![], card_basic(), vec![])), ( Connector::Fiuu, fields( vec![ RequiredField::BillingEmail, RequiredField::BillingUserFirstName, ], vec![], card_basic(), ), ), (Connector::Forte, fields(vec![], card_with_name(), vec![])), (Connector::Globalpay, fields(vec![], vec![], card_basic())), ( Connector::Hipay, fields( vec![], vec![], [ vec![RequiredField::BillingEmail], billing_address(), card_with_name(), ] .concat(), ), ), ( Connector::Helcim, fields( vec![], [ card_with_name(), vec![ RequiredField::BillingAddressZip, RequiredField::BillingAddressLine1, ], ] .concat(), vec![], ), ), (Connector::Iatapay, fields(vec![], vec![], vec![])), (Connector::Mollie, fields(vec![], card_with_name(), vec![])), (Connector::Moneris, fields(vec![], card_basic(), vec![])), ( Connector::Multisafepay, fields( vec![], vec![], [ card_with_name(), vec![ RequiredField::BillingAddressLine1, RequiredField::BillingAddressLine2, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressCountries(vec!["ALL"]), ], ] .concat(), ), ), (Connector::Nexinets, fields(vec![], vec![], card_basic())), ( Connector::Nexixpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::CardNumber.to_tuple(), RequiredField::CardExpMonth.to_tuple(), RequiredField::CardExpYear.to_tuple(), RequiredField::BillingFirstName("first_name", FieldType::UserFullName) .to_tuple(), RequiredField::BillingLastName("last_name", FieldType::UserFullName).to_tuple(), ]), }, ), ( Connector::Nmi, fields( vec![], [card_with_name(), vec![RequiredField::BillingAddressZip]].concat(), vec![], ), ), (Connector::Noon, fields(vec![], vec![], card_with_name())), ( Connector::Novalnet, fields( vec![], vec![], [ vec![ RequiredField::BillingFirstName("first_name", FieldType::UserFullName), RequiredField::BillingLastName("last_name", FieldType::UserFullName), ], billing_email(), ] .concat(), ), ), ( Connector::Nuvei, fields( vec![], vec![], [ card_basic(), vec![ RequiredField::BillingEmail, RequiredField::BillingCountries(vec!["ALL"]), RequiredField::BillingFirstName("first_name", FieldType::UserFullName), RequiredField::BillingLastName("last_name", FieldType::UserFullName), ], ] .concat(), ), ), ( Connector::Paybox, fields( vec![], vec![], [ email(), card_with_name(), vec![ RequiredField::BillingAddressLine1, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressCountries(vec!["ALL"]), ], ] .concat(), ), ), ( Connector::Paysafe, fields( vec![ RequiredField::BillingAddressCountries(vec!["ALL"]), RequiredField::BillingEmail, RequiredField::BillingAddressZip, RequiredField::BillingAddressState, ], vec![], vec![], ), ), ( Connector::Payload, fields( vec![], vec![], [ email(), card_with_name(), vec![ RequiredField::BillingAddressLine1, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressState, RequiredField::BillingAddressCountries(vec!["ALL"]), ], ] .concat(), ), ), ( Connector::Payme, fields(vec![], vec![], [email(), card_with_name()].concat()), ), (Connector::Paypal, fields(vec![], card_basic(), vec![])), (Connector::Payu, fields(vec![], card_basic(), vec![])), ( Connector::Peachpayments, fields(vec![], vec![], card_with_name()), ), ( Connector::Powertranz, fields(vec![], card_with_name(), vec![]), ), (Connector::Rapyd, fields(vec![], card_with_name(), vec![])), (Connector::Redsys, fields(vec![], card_basic(), vec![])), (Connector::Shift4, fields(vec![], card_basic(), vec![])), (Connector::Silverflow, fields(vec![], vec![], card_basic())), (Connector::Square, fields(vec![], vec![], card_basic())), (Connector::Stax, fields(vec![], card_with_name(), vec![])), (Connector::Stripe, fields(vec![], vec![], card_basic())), ( Connector::Trustpay, fields( vec![], [ card_with_name(), vec![ RequiredField::BillingAddressLine1, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressCountries(vec!["ALL"]), ], ] .concat(), vec![], ), ), ( Connector::Trustpayments, fields(vec![], vec![], card_basic()), ), ( Connector::Tesouro, fields( vec![], vec![], vec![ RequiredField::CardNumber, RequiredField::CardExpMonth, RequiredField::CardExpYear, RequiredField::CardCvc, ], ), ), (Connector::Tsys, fields(vec![], card_basic(), vec![])), ( Connector::Wellsfargo, fields( vec![], vec![], [card_with_name(), email(), billing_address()].concat(), ), ), ( Connector::Worldline, fields( vec![], [ card_basic(), vec![RequiredField::BillingAddressCountries(vec!["ALL"])], ] .concat(), vec![], ), ), ( Connector::Worldpay, fields( vec![], vec![], vec![ RequiredField::CardNumber, RequiredField::CardExpMonth, RequiredField::CardExpYear, RequiredField::BillingUserFirstName, ], ), ), ( Connector::Worldpayvantiv, fields(vec![], card_basic(), vec![]), ), ( Connector::Xendit, fields( vec![], vec![], [ card_basic(), vec![ RequiredField::BillingEmail, RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, RequiredField::BillingUserFirstName, RequiredField::BillingUserLastName, RequiredField::BillingAddressCountries(vec!["ID,PH"]), ], ] .concat(), ), ), ( Connector::Zen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::CardNumber.to_tuple(), RequiredField::CardExpMonth.to_tuple(), RequiredField::CardExpYear.to_tuple(), RequiredField::Email.to_tuple(), ]), common: HashMap::new(), }, ), ]) } #[cfg(feature = "v1")] fn get_bank_redirect_required_fields( bank_config: &BankRedirectConfig, ) -> HashMap<enums::PaymentMethodType, ConnectorFields> { HashMap::from([ ( enums::PaymentMethodType::OpenBankingUk, connectors(vec![ (Connector::Volt, fields(vec![], billing_name(), vec![])), ( Connector::Adyen, fields(vec![], vec![RequiredField::OpenBankingUkIssuer], vec![]), ), ]), ), ( enums::PaymentMethodType::Trustly, connectors(vec![ (Connector::Adyen, fields(vec![], vec![], vec![])), ( Connector::Airwallex, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), RequiredField::BillingAddressCountries(vec![ "DE", "DK", "EE", "ES", "FI", "GB", "LV", "LT", "NL", "PL", "PT", "SE", "SK", ]) .to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::OnlineBankingCzechRepublic, connectors(vec![( Connector::Adyen, fields( vec![], vec![RequiredField::OpenBankingCzechRepublicIssuer], vec![], ), )]), ), ( enums::PaymentMethodType::OnlineBankingFinland, connectors(vec![( Connector::Adyen, fields(vec![], vec![RequiredField::BillingEmail], vec![]), )]), ), ( enums::PaymentMethodType::OnlineBankingPoland, connectors(vec![( Connector::Adyen, fields( vec![], vec![ RequiredField::OpenBankingPolandIssuer, RequiredField::BillingEmail, ], vec![], ), )]), ), ( enums::PaymentMethodType::OnlineBankingSlovakia, connectors(vec![( Connector::Adyen, fields( vec![], vec![RequiredField::OpenBankingSlovakiaIssuer], vec![], ), )]), ), ( enums::PaymentMethodType::OnlineBankingFpx, connectors(vec![( Connector::Adyen, fields(vec![], vec![RequiredField::OpenBankingFpxIssuer], vec![]), )]), ), ( enums::PaymentMethodType::OnlineBankingThailand, connectors(vec![( Connector::Adyen, fields( vec![], vec![RequiredField::OpenBankingThailandIssuer], vec![], ), )]), ), ( enums::PaymentMethodType::Bizum, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::Przelewy24, connectors(vec![( Connector::Stripe, fields(vec![], vec![RequiredField::BillingEmail], vec![]), )]), ), ( enums::PaymentMethodType::BancontactCard, connectors(vec![ (Connector::Mollie, fields(vec![], vec![], vec![])), ( Connector::Stripe, fields( vec![RequiredField::BillingEmail], vec![], vec![ RequiredField::BillingFirstName( "billing_name", FieldType::UserFullName, ), RequiredField::BillingLastName("billing_name", FieldType::UserFullName), ], ), ), ( Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BanContactCardNumber.to_tuple(), RequiredField::BanContactCardExpMonth.to_tuple(), RequiredField::BanContactCardExpYear.to_tuple(), RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), ]), }, ), ]), ), ( enums::PaymentMethodType::Giropay, connectors(vec![ ( Connector::Aci, fields( vec![], vec![RequiredField::BillingCountries(vec!["DE"])], vec![], ), ), (Connector::Adyen, fields(vec![], vec![], vec![])), ( Connector::Globalpay, fields( vec![], vec![], vec![RequiredField::BillingAddressCountries(vec!["DE"])], ), ), (Connector::Mollie, fields(vec![], vec![], vec![])), ( Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCountries(vec!["DE"]).to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingCountries(vec!["DE"]).to_tuple(), RequiredField::BillingFirstName( "billing_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_name", FieldType::UserBillingName, ) .to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Stripe, fields( vec![], vec![ RequiredField::BillingFirstName( "billing_name", FieldType::UserBillingName, ), RequiredField::BillingLastName( "billing_name", FieldType::UserBillingName, ), ], vec![], ), ), (Connector::Shift4, fields(vec![], vec![], vec![])), ( Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["DE"]).to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::Ideal, connectors(vec![ ( Connector::Aci, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::IdealBankName.to_tuple(), RequiredField::BillingCountries(vec!["NL"]).to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Adyen, fields(vec![], vec![], vec![RequiredField::IdealBankName]), ), (Connector::Globalpay, fields(vec![], vec![], vec![])), (Connector::Mollie, fields(vec![], vec![], vec![])), (Connector::Nexinets, fields(vec![], vec![], vec![])), (Connector::Airwallex, fields(vec![], vec![], vec![])), ( Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCountries(vec!["NL"]).to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Shift4, fields( vec![], vec![RequiredField::BillingCountries(vec!["NL"])], vec![], ), ), ( Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingCountries(vec!["NL"]).to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Stripe, RequiredFieldFinal { mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_name", FieldType::UserFullName, ) .to_tuple(), RequiredField::BillingLastName("billing_name", FieldType::UserFullName) .to_tuple(), RequiredField::BillingEmail.to_tuple(), ]), non_mandate: HashMap::new(), common: HashMap::new(), }, ), ( Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["NL"]).to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::Sofort, connectors(vec![ ( Connector::Aci, fields( vec![], vec![RequiredField::BillingCountries(vec![ "ES", "GB", "SE", "AT", "NL", "DE", "CH", "BE", "FR", "FI", "IT", "PL", ])], vec![], ), ), (Connector::Adyen, fields(vec![], vec![], vec![])), ( Connector::Globalpay, fields( vec![], vec![], vec![RequiredField::BillingAddressCountries(vec![ "AT", "BE", "DE", "ES", "IT", "NL", ])], ), ), (Connector::Mollie, fields(vec![], vec![], vec![])), (Connector::Nexinets, fields(vec![], vec![], vec![])), ( Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCountries(vec![ "ES", "GB", "IT", "DE", "FR", "AT", "BE", "NL", "BE", "SK", ]) .to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingCountries(vec![ "ES", "GB", "AT", "NL", "DE", "BE", ]) .to_tuple(), RequiredField::BillingFirstName( "billing_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_name", FieldType::UserBillingName, ) .to_tuple(), ]), common: HashMap::new(), }, ), (Connector::Shift4, fields(vec![], vec![], vec![])), ( Connector::Stripe, RequiredFieldFinal { mandate: HashMap::from([RequiredField::BillingEmail.to_tuple()]), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingCountries(vec!["ES", "AT", "NL", "DE", "BE"]) .to_tuple(), RequiredField::BillingFirstName( "account_holder_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "account_holder_name", FieldType::UserBillingName, ) .to_tuple(), ]), }, ), ( Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec![ "ES", "GB", "SE", "AT", "NL", "DE", "CH", "BE", "FR", "FI", "IT", "PL", ]) .to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::Eps, connectors(vec![ ( Connector::Adyen, fields(vec![], vec![], vec![RequiredField::EpsBankName]), ), ( Connector::Stripe, fields( vec![], vec![ RequiredField::BillingFirstName( "billing_name", FieldType::UserFullName, ), RequiredField::EpsBankOptions( bank_config .0 .get(&enums::PaymentMethodType::Eps) .and_then(|connector_bank_names| { connector_bank_names.0.get("stripe") }) .map(|bank_names| bank_names.banks.clone()) .unwrap_or_default(), ), RequiredField::BillingLastName("billing_name", FieldType::UserFullName), ], vec![], ), ), ( Connector::Aci, fields( vec![], vec![RequiredField::BillingCountries(vec!["AT"])], vec![], ), ), ( Connector::Globalpay, fields( vec![], vec![], vec![RequiredField::BillingAddressCountries(vec!["AT"])], ), ), (Connector::Mollie, fields(vec![], vec![], vec![])), ( Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_name", FieldType::UserFullName, ) .to_tuple(), RequiredField::BillingLastName("billing_name", FieldType::UserFullName) .to_tuple(), RequiredField::BillingCountries(vec!["AT"]).to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["AT"]).to_tuple(), ]), common: HashMap::new(), }, ), (Connector::Shift4, fields(vec![], vec![], vec![])), ( Connector::Nuvei, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCountries(vec!["AT"]).to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::Blik, connectors(vec![ ( Connector::Adyen, fields(vec![], vec![], vec![RequiredField::BlikCode]), ), ( Connector::Stripe, fields(vec![], vec![], vec![RequiredField::BlikCode]), ), ( Connector::Trustpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), ]), }, ), ( Connector::Airwallex, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::Interac, connectors(vec![ ( Connector::Paysafe, fields(vec![], vec![RequiredField::BillingEmail], vec![]), ), ( Connector::Gigadat, fields( vec![], vec![ RequiredField::BillingEmail, RequiredField::BillingUserFirstName, RequiredField::BillingUserLastName, RequiredField::BillingPhone, ], vec![], ), ), ( Connector::Loonio, fields( vec![], vec![ RequiredField::BillingEmail, RequiredField::BillingUserFirstName, RequiredField::BillingUserLastName, ], vec![], ), ), ]), ), ]) } #[cfg(feature = "v1")] fn get_wallet_required_fields() -> HashMap<enums::PaymentMethodType, ConnectorFields> { HashMap::from([ ( enums::PaymentMethodType::ApplePay, connectors(vec![ (Connector::Stripe, fields(vec![], vec![], vec![])), (Connector::Adyen, fields(vec![], vec![], vec![])), ( Connector::Nuvei, fields( vec![], vec![], vec![ RequiredField::BillingEmail, RequiredField::BillingCountries(vec!["ALL"]), RequiredField::BillingFirstName("first_name", FieldType::UserFullName), RequiredField::BillingLastName("last_name", FieldType::UserFullName), ], ), ), ( Connector::Bankofamerica, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), ]), }, ), ( Connector::Cybersource, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingEmail.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), ]), }, ), ( Connector::Novalnet, fields(vec![], vec![], vec![RequiredField::BillingEmail]), ), ( Connector::Paysafe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), ]), }, ), ( Connector::Wellsfargo, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::ShippingFirstName.to_tuple(), RequiredField::ShippingLastName.to_tuple(), RequiredField::ShippingAddressCity.to_tuple(), RequiredField::ShippingAddressState.to_tuple(), RequiredField::ShippingAddressZip.to_tuple(), RequiredField::ShippingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::ShippingAddressLine1.to_tuple(), ]), }, ), ]), ), ( enums::PaymentMethodType::SamsungPay, connectors(vec![( Connector::Cybersource, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingEmail.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), ]), }, )]), ), ( enums::PaymentMethodType::GooglePay, connectors(vec![ (Connector::Adyen, fields(vec![], vec![], vec![])), ( Connector::Bankofamerica, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), ]), }, ), ( Connector::Barclaycard, fields(vec![], vec![], [full_name(), billing_address()].concat()), ), (Connector::Bluesnap, fields(vec![], vec![], vec![])), (Connector::Noon, fields(vec![], vec![], vec![])), ( Connector::Novalnet, fields(vec![], vec![], vec![RequiredField::BillingEmail]), ), ( Connector::Nuvei, fields( vec![], vec![], vec![ RequiredField::BillingEmail, RequiredField::BillingCountries(vec!["ALL"]), RequiredField::BillingFirstName("first_name", FieldType::UserFullName), RequiredField::BillingLastName("last_name", FieldType::UserFullName), ], ), ), (Connector::Airwallex, fields(vec![], vec![], vec![])), (Connector::Authorizedotnet, fields(vec![], vec![], vec![])), (Connector::Checkout, fields(vec![], vec![], vec![])), (Connector::Globalpay, fields(vec![], vec![], vec![])), ( Connector::Multisafepay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressLine2.to_tuple(), ]), }, ), ( Connector::Cybersource, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingEmail.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), ]), }, ), (Connector::Payu, fields(vec![], vec![], vec![])), (Connector::Rapyd, fields(vec![], vec![], vec![])), (Connector::Stripe, fields(vec![], vec![], vec![])), (Connector::Trustpay, fields(vec![], vec![], vec![])), ( Connector::Wellsfargo, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::Email.to_tuple(), RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::ShippingFirstName.to_tuple(), RequiredField::ShippingLastName.to_tuple(), RequiredField::ShippingAddressCity.to_tuple(), RequiredField::ShippingAddressState.to_tuple(), RequiredField::ShippingAddressZip.to_tuple(), RequiredField::ShippingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::ShippingAddressLine1.to_tuple(), ]), }, ), ]), ), ( enums::PaymentMethodType::WeChatPay, connectors(vec![ (Connector::Stripe, fields(vec![], vec![], vec![])), (Connector::Adyen, fields(vec![], vec![], vec![])), ]), ), ( enums::PaymentMethodType::AliPay, connectors(vec![ (Connector::Stripe, fields(vec![], vec![], vec![])), (Connector::Adyen, fields(vec![], vec![], vec![])), ]), ), ( enums::PaymentMethodType::AliPayHk, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::AmazonPay, connectors(vec![ (Connector::Stripe, fields(vec![], vec![], vec![])), ( Connector::Amazonpay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::ShippingFirstName.to_tuple(), RequiredField::ShippingLastName.to_tuple(), RequiredField::ShippingAddressLine1.to_tuple(), RequiredField::ShippingAddressCity.to_tuple(), RequiredField::ShippingAddressState.to_tuple(), RequiredField::ShippingAddressZip.to_tuple(), RequiredField::ShippingPhone.to_tuple(), ]), }, ), ]), ), ( enums::PaymentMethodType::Cashapp, connectors(vec![(Connector::Stripe, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::MbWay, connectors(vec![( Connector::Adyen, fields( vec![], vec![ RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, ], vec![], ), )]), ), ( enums::PaymentMethodType::KakaoPay, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::Twint, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::Gcash, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::Vipps, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::Dana, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::Momo, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::Swish, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::TouchNGo, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( // 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, connectors(vec![ ( Connector::Adyen, fields(vec![], vec![], vec![RequiredField::BillingEmail]), ), (Connector::Braintree, fields(vec![], vec![], vec![])), ( Connector::Novalnet, fields(vec![], vec![], vec![RequiredField::BillingEmail]), ), ( Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::ShippingFirstName.to_tuple(), RequiredField::ShippingLastName.to_tuple(), RequiredField::ShippingAddressCity.to_tuple(), RequiredField::ShippingAddressState.to_tuple(), RequiredField::ShippingAddressZip.to_tuple(), RequiredField::ShippingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::ShippingAddressLine1.to_tuple(), ]), }, ), ( Connector::Airwallex, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::Mifinity, connectors(vec![( Connector::Mifinity, fields( vec![], vec![], vec![ RequiredField::MifinityDateOfBirth, RequiredField::BillingAddressLine1, RequiredField::BillingAddressCity, RequiredField::BillingFirstName("first_name", FieldType::UserFullName), RequiredField::BillingLastName("last_name", FieldType::UserFullName), RequiredField::BillingPhone, RequiredField::BillingPhoneCountryCode, RequiredField::BillingCountries(vec![ "BR", "CN", "SG", "MY", "DE", "CH", "DK", "GB", "ES", "AD", "GI", "FI", "FR", "GR", "HR", "IT", "JP", "MX", "AR", "CO", "CL", "PE", "VE", "UY", "PY", "BO", "EC", "GT", "HN", "SV", "NI", "CR", "PA", "DO", "CU", "PR", "NL", "NO", "PL", "PT", "SE", "RU", "TR", "TW", "HK", "MO", "AX", "AL", "DZ", "AS", "AO", "AI", "AG", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BE", "BZ", "BJ", "BM", "BT", "BQ", "BA", "BW", "IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF", "TD", "CX", "CC", "KM", "CG", "CK", "CI", "CW", "CY", "CZ", "DJ", "DM", "EG", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "GF", "PF", "TF", "GA", "GM", "GE", "GH", "GL", "GD", "GP", "GU", "GG", "GN", "GW", "GY", "HT", "HM", "VA", "IS", "IN", "ID", "IE", "IM", "IL", "JE", "JO", "KZ", "KE", "KI", "KW", "KG", "LA", "LV", "LB", "LS", "LI", "LT", "LU", "MK", "MG", "MW", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "FM", "MD", "MC", "MN", "ME", "MS", "MA", "MZ", "NA", "NR", "NP", "NC", "NZ", "NE", "NG", "NU", "NF", "MP", "OM", "PK", "PW", "PS", "PG", "PH", "PN", "QA", "RE", "RO", "RW", "BL", "SH", "KN", "LC", "MF", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS", "SC", "SL", "SX", "SK", "SI", "SB", "SO", "ZA", "GS", "KR", "LK", "SR", "SJ", "SZ", "TH", "TL", "TG", "TK", "TO", "TT", "TN", "TM", "TC", "TV", "UG", "UA", "AE", "UZ", "VU", "VN", "VG", "VI", "WF", "EH", "ZM", ]), RequiredField::BillingEmail, RequiredField::MifinityLanguagePreference(vec![ "BR", "PT_BR", "CN", "ZH_CN", "DE", "DK", "DA", "DA_DK", "EN", "ES", "FI", "FR", "GR", "EL", "EL_GR", "HR", "IT", "JP", "JA", "JA_JP", "LA", "ES_LA", "NL", "NO", "PL", "PT", "RU", "SV", "SE", "SV_SE", "ZH", "TW", "ZH_TW", ]), ], ), )]), ), ( enums::PaymentMethodType::Skrill, connectors(vec![ ( Connector::Airwallex, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::BillingEmail.to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Paysafe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::BillingEmail.to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ]) } #[cfg(feature = "v1")] fn get_pay_later_required_fields() -> HashMap<enums::PaymentMethodType, ConnectorFields> { HashMap::from([ ( enums::PaymentMethodType::AfterpayClearpay, connectors(vec![ ( Connector::Stripe, fields( vec![], vec![ RequiredField::BillingEmail, RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ), RequiredField::BillingAddressLine1, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressCountries(vec![ "GB", "AU", "CA", "US", "NZ", ]), RequiredField::BillingAddressState, RequiredField::ShippingFirstName, RequiredField::ShippingLastName, RequiredField::ShippingAddressCity, RequiredField::ShippingAddressState, RequiredField::ShippingAddressZip, RequiredField::ShippingAddressCountries(vec!["ALL"]), RequiredField::ShippingAddressLine1, ], vec![], ), ), ( Connector::Adyen, fields( vec![], vec![ RequiredField::BillingEmail, RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ), RequiredField::BillingAddressLine1, RequiredField::BillingAddressLine2, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressCountries(vec![ "GB", "AU", "CA", "US", "NZ", ]), RequiredField::BillingAddressState, RequiredField::ShippingAddressCity, RequiredField::ShippingAddressZip, RequiredField::ShippingAddressCountries(vec![ "GB", "AU", "CA", "US", "NZ", ]), RequiredField::ShippingAddressLine1, RequiredField::ShippingAddressLine2, ], vec![], ), ), ]), ), ( enums::PaymentMethodType::Flexiti, connectors(vec![( Connector::Flexiti, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressLine2.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::ShippingFirstName.to_tuple(), RequiredField::ShippingLastName.to_tuple(), RequiredField::ShippingAddressLine1.to_tuple(), RequiredField::ShippingAddressLine2.to_tuple(), RequiredField::ShippingAddressZip.to_tuple(), RequiredField::ShippingAddressCity.to_tuple(), RequiredField::ShippingAddressState.to_tuple(), ]), common: HashMap::new(), }, )]), ), ( enums::PaymentMethodType::Klarna, connectors(vec![ ( Connector::Stripe, fields( vec![], vec![ RequiredField::BillingAddressCountries(vec![ "AU", "AT", "BE", "CA", "CZ", "DK", "FI", "FR", "GR", "DE", "IE", "IT", "NL", "NZ", "NO", "PL", "PT", "RO", "ES", "SE", "CH", "GB", "US", ]), RequiredField::BillingEmail, ], vec![], ), ), ( Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::BillingEmail.to_tuple(), ]), }, ), ( Connector::Klarna, fields( vec![], vec![], vec![RequiredField::BillingAddressCountries(vec![ "AU", "AT", "BE", "CA", "CZ", "DK", "FI", "FR", "DE", "GR", "IE", "IT", "NL", "NZ", "NO", "PL", "PT", "ES", "SE", "CH", "GB", "US", ])], ), ), ( Connector::Airwallex, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([RequiredField::BillingAddressCountries(vec![ "AT", "BE", "FI", "FR", "DE", "GR", "IE", "IT", "NL", "PT", "ES", "DK", "NO", "PL", "SE", "CH", "GB", "CZ", "US", ]) .to_tuple()]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::Affirm, connectors(vec![ (Connector::Stripe, fields(vec![], vec![], vec![])), ( Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["US"]).to_tuple(), RequiredField::BillingPhone.to_tuple(), RequiredField::BillingPhoneCountryCode.to_tuple(), RequiredField::BillingEmail.to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressLine2.to_tuple(), RequiredField::ShippingAddressLine1.to_tuple(), RequiredField::ShippingAddressLine2.to_tuple(), RequiredField::ShippingAddressZip.to_tuple(), RequiredField::ShippingAddressCity.to_tuple(), RequiredField::ShippingCountries(vec!["US"]).to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::PayBright, connectors(vec![( Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["CA"]).to_tuple(), RequiredField::BillingPhone.to_tuple(), RequiredField::BillingPhoneCountryCode.to_tuple(), RequiredField::BillingEmail.to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressLine2.to_tuple(), RequiredField::ShippingAddressCity.to_tuple(), RequiredField::ShippingAddressZip.to_tuple(), RequiredField::ShippingAddressCountries(vec!["ALL"]).to_tuple(), RequiredField::ShippingAddressLine1.to_tuple(), RequiredField::ShippingAddressLine2.to_tuple(), ]), common: HashMap::new(), }, )]), ), ( enums::PaymentMethodType::Walley, connectors(vec![( Connector::Adyen, fields( vec![], vec![ RequiredField::BillingPhone, RequiredField::BillingAddressCountries(vec!["DK", "FI", "NO", "SE"]), RequiredField::BillingPhoneCountryCode, RequiredField::BillingEmail, ], vec![], ), )]), ), ( enums::PaymentMethodType::Alma, connectors(vec![( Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["FR"]).to_tuple(), RequiredField::BillingPhone.to_tuple(), RequiredField::BillingPhoneCountryCode.to_tuple(), RequiredField::BillingEmail.to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressLine2.to_tuple(), ]), common: HashMap::new(), }, )]), ), ( enums::PaymentMethodType::Atome, connectors(vec![ ( Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["MY", "SG"]).to_tuple(), RequiredField::BillingPhone.to_tuple(), RequiredField::BillingPhoneCountryCode.to_tuple(), RequiredField::BillingEmail.to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressLine2.to_tuple(), ]), common: HashMap::new(), }, ), ( Connector::Airwallex, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingPhone.to_tuple(), RequiredField::BillingPhoneCountryCode.to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ]) } #[cfg(feature = "v1")] fn get_voucher_required_fields() -> HashMap<enums::PaymentMethodType, ConnectorFields> { HashMap::from([ ( enums::PaymentMethodType::Boleto, connectors(vec![ ( Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BoletoSocialSecurityNumber.to_tuple(), RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressState.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressCountries(vec!["BR"]).to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressLine2.to_tuple(), ]), common: HashMap::new(), }, ), (Connector::Zen, fields(vec![], vec![], vec![])), ]), ), ( enums::PaymentMethodType::Alfamart, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name(), vec![]), )]), ), ( enums::PaymentMethodType::Indomaret, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name(), vec![]), )]), ), ( enums::PaymentMethodType::Oxxo, connectors(vec![(Connector::Adyen, fields(vec![], vec![], vec![]))]), ), ( enums::PaymentMethodType::SevenEleven, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name_phone(), vec![]), )]), ), ( enums::PaymentMethodType::Lawson, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name_phone(), vec![]), )]), ), ( enums::PaymentMethodType::MiniStop, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name_phone(), vec![]), )]), ), ( enums::PaymentMethodType::FamilyMart, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name_phone(), vec![]), )]), ), ( enums::PaymentMethodType::Seicomart, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name_phone(), vec![]), )]), ), ( enums::PaymentMethodType::PayEasy, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name_phone(), vec![]), )]), ), ]) } #[cfg(feature = "v1")] fn get_bank_debit_required_fields() -> HashMap<enums::PaymentMethodType, ConnectorFields> { HashMap::from([ ( enums::PaymentMethodType::Ach, connectors(vec![ ( Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "owner_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::AchBankDebitAccountNumber.to_tuple(), RequiredField::AchBankDebitRoutingNumber.to_tuple(), ]), }, ), ( Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingFirstName( "owner_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "owner_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::AchBankDebitAccountNumber.to_tuple(), RequiredField::AchBankDebitRoutingNumber.to_tuple(), ]), }, ), ( Connector::Dwolla, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::from([ RequiredField::BillingFirstName( "first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName("last_name", FieldType::UserBillingName) .to_tuple(), RequiredField::AchBankDebitAccountNumber.to_tuple(), RequiredField::AchBankDebitRoutingNumber.to_tuple(), RequiredField::AchBankDebitBankAccountHolderName.to_tuple(), RequiredField::AchBankDebitBankType(vec![ enums::BankType::Checking, enums::BankType::Savings, ]) .to_tuple(), ]), common: HashMap::new(), }, ), ]), ), ( enums::PaymentMethodType::Sepa, connectors(vec![ ( Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "owner_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::SepaBankDebitIban.to_tuple(), RequiredField::BillingEmail.to_tuple(), ]), }, ), ( Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingFirstName( "owner_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "owner_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::SepaBankDebitIban.to_tuple(), ]), }, ), ( Connector::Deutschebank, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingFirstName( "owner_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "owner_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingEmail.to_tuple(), RequiredField::SepaBankDebitIban.to_tuple(), ]), }, ), ( Connector::Inespay, fields(vec![], vec![], vec![RequiredField::SepaBankDebitIban]), ), ( Connector::Nordea, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingAddressCountries(vec!["DK,FI,NO,SE"]).to_tuple(), RequiredField::SepaBankDebitIban.to_tuple(), ]), }, ), ]), ), ( enums::PaymentMethodType::Bacs, connectors(vec![ ( Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BacsBankDebitAccountNumber.to_tuple(), RequiredField::BacsBankDebitSortCode.to_tuple(), RequiredField::BillingAddressCountries(vec!["UK"]).to_tuple(), RequiredField::BillingAddressZip.to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), ]), }, ), ( Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingFirstName( "owner_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "owner_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BacsBankDebitAccountNumber.to_tuple(), RequiredField::BacsBankDebitSortCode.to_tuple(), ]), }, ), ]), ), ( enums::PaymentMethodType::Becs, connectors(vec![ ( Connector::Stripe, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "owner_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BecsBankDebitAccountNumber.to_tuple(), RequiredField::BecsBankDebitBsbNumber.to_tuple(), RequiredField::BillingEmail.to_tuple(), ]), }, ), ( Connector::Adyen, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingFirstName( "owner_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BillingLastName( "owner_name", FieldType::UserBillingName, ) .to_tuple(), RequiredField::BecsBankDebitAccountNumber.to_tuple(), RequiredField::BecsBankDebitSortCode.to_tuple(), ]), }, ), ]), ), ]) } #[cfg(feature = "v1")] fn get_bank_transfer_required_fields() -> HashMap<enums::PaymentMethodType, ConnectorFields> { HashMap::from([ ( enums::PaymentMethodType::Multibanco, connectors(vec![( Connector::Stripe, fields(vec![], vec![RequiredField::BillingEmail], vec![]), )]), ), ( enums::PaymentMethodType::LocalBankTransfer, connectors(vec![( Connector::Zsl, fields( vec![], vec![ RequiredField::BillingAddressCountries(vec!["CN"]), RequiredField::BillingAddressCity, ], vec![], ), )]), ), ( enums::PaymentMethodType::Ach, connectors(vec![( Connector::Checkbook, fields( vec![], vec![], vec![ RequiredField::BillingUserFirstName, RequiredField::BillingUserLastName, RequiredField::BillingEmail, RequiredField::Description, ], ), )]), ), ( enums::PaymentMethodType::Pix, connectors(vec![ ( Connector::Itaubank, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::PixKey.to_tuple(), RequiredField::PixCnpj.to_tuple(), RequiredField::PixCpf.to_tuple(), RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), ]), }, ), (Connector::Adyen, fields(vec![], vec![], vec![])), ( Connector::Santander, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), ]), }, ), ( Connector::Calida, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), RequiredField::BillingCountries(vec![ "AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE", "IS", "LI", "NO", ]) .to_tuple(), RequiredField::BillingAddressCity.to_tuple(), RequiredField::BillingAddressLine1.to_tuple(), RequiredField::BillingAddressZip.to_tuple(), ]), }, ), ( Connector::Facilitapay, RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: HashMap::from([ RequiredField::PixSourceBankAccountId.to_tuple(), RequiredField::BillingAddressCountries(vec!["BR"]).to_tuple(), RequiredField::BillingUserFirstName.to_tuple(), RequiredField::BillingUserLastName.to_tuple(), RequiredField::PixCpf.to_tuple(), ]), }, ), ]), ), ( enums::PaymentMethodType::PermataBankTransfer, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name(), vec![]), )]), ), ( enums::PaymentMethodType::BcaBankTransfer, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name(), vec![]), )]), ), ( enums::PaymentMethodType::BniVa, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name(), vec![]), )]), ), ( enums::PaymentMethodType::BriVa, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name(), vec![]), )]), ), ( enums::PaymentMethodType::CimbVa, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name(), vec![]), )]), ), ( enums::PaymentMethodType::DanamonVa, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name(), vec![]), )]), ), ( enums::PaymentMethodType::MandiriVa, connectors(vec![( Connector::Adyen, fields(vec![], billing_email_billing_name(), vec![]), )]), ), ( enums::PaymentMethodType::SepaBankTransfer, connectors(vec![ ( Connector::Stripe, fields( vec![], vec![], vec![ RequiredField::BillingEmail, RequiredField::BillingUserFirstName, RequiredField::BillingUserLastName, RequiredField::BillingAddressCountries(vec![ "BE", "DE", "ES", "FR", "IE", "NL", ]), ], ), ), ( Connector::Trustpay, fields( vec![], vec![], vec![ RequiredField::Email, RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ), RequiredField::BillingAddressLine1, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressCountries(vec!["ALL"]), ], ), ), ]), ), ( enums::PaymentMethodType::InstantBankTransfer, connectors(vec![( Connector::Trustpay, fields( vec![], vec![], vec![ RequiredField::Email, RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ), RequiredField::BillingAddressLine1, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressCountries(vec!["ALL"]), ], ), )]), ), ( enums::PaymentMethodType::InstantBankTransferFinland, connectors(vec![( Connector::Trustpay, fields( vec![], vec![], vec![ RequiredField::Email, RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ), RequiredField::BillingAddressLine1, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressCountries(vec!["FI"]), ], ), )]), ), ( enums::PaymentMethodType::InstantBankTransferPoland, connectors(vec![( Connector::Trustpay, fields( vec![], vec![], vec![ RequiredField::Email, RequiredField::BillingFirstName( "billing_first_name", FieldType::UserBillingName, ), RequiredField::BillingLastName( "billing_last_name", FieldType::UserBillingName, ), RequiredField::BillingAddressLine1, RequiredField::BillingAddressCity, RequiredField::BillingAddressZip, RequiredField::BillingAddressCountries(vec!["PL"]), ], ), )]), ), ( enums::PaymentMethodType::Bacs, connectors(vec![( Connector::Stripe, fields(vec![], vec![], billing_email_name()), )]), ), ]) } #[test] fn test_required_fields_to_json() { #![allow(clippy::unwrap_used)] // Test billing fields let billing_fields = get_billing_required_fields(); // let billing_json = serde_json::to_string_pretty(&billing_fields)?; // Verify billing fields have expected entries assert!(billing_fields.contains_key("billing.address.first_name")); assert!(billing_fields.contains_key("billing.address.last_name")); assert!(billing_fields.contains_key("billing.address.city")); assert!(billing_fields.contains_key("billing.address.zip")); assert!(billing_fields.contains_key("billing.email")); // Verify specific billing field properties let billing_first_name = billing_fields.get("billing.address.first_name").unwrap(); assert_eq!(billing_first_name.display_name, "billing_first_name"); assert!(matches!( billing_first_name.field_type, FieldType::UserBillingName )); // Test shipping fields let shipping_fields = get_shipping_required_fields(); // let shipping_json = serde_json::to_string_pretty(&shipping_fields)?; // Verify shipping fields have expected entries assert!(shipping_fields.contains_key("shipping.address.first_name")); assert!(shipping_fields.contains_key("shipping.address.last_name")); assert!(shipping_fields.contains_key("shipping.address.city")); assert!(shipping_fields.contains_key("shipping.address.zip")); assert!(shipping_fields.contains_key("shipping.email")); // Verify specific shipping field properties let shipping_address_line1 = shipping_fields.get("shipping.address.line1").unwrap(); assert_eq!(shipping_address_line1.display_name, "line1"); assert!(matches!( shipping_address_line1.field_type, FieldType::UserShippingAddressLine1 )); #[cfg(feature = "v1")] { let default_fields = RequiredFields::default(); // let default_json = serde_json::to_string_pretty(&default_fields.0)?; // Check default fields for payment methods assert!(default_fields.0.contains_key(&enums::PaymentMethod::Card)); assert!(default_fields.0.contains_key(&enums::PaymentMethod::Wallet)); // Verify card payment method types if let Some(card_method) = default_fields.0.get(&enums::PaymentMethod::Card) { assert!(card_method .0 .contains_key(&enums::PaymentMethodType::Credit)); assert!(card_method.0.contains_key(&enums::PaymentMethodType::Debit)); } // Verify specific connector fields if let Some(card_method) = default_fields.0.get(&enums::PaymentMethod::Card) { if let Some(credit_type) = card_method.0.get(&enums::PaymentMethodType::Credit) { // Check if Stripe connector exists assert!(credit_type.fields.contains_key(&Connector::Stripe)); // Verify Stripe required fields if let Some(stripe_fields) = credit_type.fields.get(&Connector::Stripe) { // Check that card_basic fields are in "common" fields for Stripe assert!(stripe_fields .common .contains_key("payment_method_data.card.card_number")); assert!(stripe_fields .common .contains_key("payment_method_data.card.card_exp_month")); assert!(stripe_fields .common .contains_key("payment_method_data.card.card_exp_year")); assert!(stripe_fields .common .contains_key("payment_method_data.card.card_cvc")); } } } // print the result of default required fields as json in new file serde_json::to_writer_pretty( std::fs::File::create("default_required_fields.json").unwrap(), &default_fields, ) .unwrap(); } }
crates/payment_methods/src/configs/payment_connector_required_fields.rs
payment_methods::src::configs::payment_connector_required_fields
27,033
true
// File: crates/payment_methods/src/configs/settings.rs // Module: payment_methods::src::configs::settings use std::collections::{HashMap, HashSet}; use api_models::{enums, payment_methods::RequiredFieldInfo}; use common_utils::errors::CustomResult; use hyperswitch_interfaces::secrets_interface::{ secret_handler::SecretsHandler, secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, SecretManagementInterface, SecretsManagementError, }; use masking::Secret; use serde::{self, Deserialize, Serialize}; #[derive(Debug, Serialize, 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, Serialize, Deserialize, Clone)] pub struct PaymentMethodType(pub HashMap<enums::PaymentMethodType, ConnectorFields>); #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ConnectorFields { pub fields: HashMap<enums::Connector, RequiredFieldFinal>, } #[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>, } #[cfg(feature = "v1")] #[derive(Debug, Serialize, 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, Serialize, Deserialize, Clone)] pub struct RequiredFieldFinal { pub mandate: Option<Vec<RequiredFieldInfo>>, pub non_mandate: Option<Vec<RequiredFieldInfo>>, pub common: Option<Vec<RequiredFieldInfo>>, } #[derive(Debug, Deserialize, Clone, Default)] pub struct PaymentMethodAuth { pub redis_expiry: i64, pub pm_auth_key: Secret<String>, } #[async_trait::async_trait] impl SecretsHandler for 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 })) } } #[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)] 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)] pub struct Mandates { pub supported_payment_methods: SupportedPaymentMethodsForMandate, pub update_mandate_supported: SupportedPaymentMethodsForMandate, } #[derive(Debug, Deserialize, Clone)] pub struct ZeroMandates { pub supported_payment_methods: SupportedPaymentMethodsForMandate, } 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) }
crates/payment_methods/src/configs/settings.rs
payment_methods::src::configs::settings
1,191
true
// File: crates/pm_auth/src/core.rs // Module: pm_auth::src::core pub mod errors;
crates/pm_auth/src/core.rs
pm_auth::src::core
24
true
// File: crates/pm_auth/src/consts.rs // Module: pm_auth::src::consts pub const REQUEST_TIME_OUT: u64 = 30; // will timeout after the mentioned limit pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT"; // timeout error code pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time"; // error message for timed out request pub const NO_ERROR_CODE: &str = "No error code"; pub const NO_ERROR_MESSAGE: &str = "No error message";
crates/pm_auth/src/consts.rs
pm_auth::src::consts
117
true
// File: crates/pm_auth/src/types.rs // Module: pm_auth::src::types pub mod api; use std::marker::PhantomData; use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate}; use api_models::enums as api_enums; use common_enums::{CountryAlpha2, PaymentMethod, PaymentMethodType}; use common_utils::{id_type, types}; use masking::Secret; #[derive(Debug, Clone)] pub struct PaymentAuthRouterData<F, Request, Response> { pub flow: PhantomData<F>, pub merchant_id: Option<id_type::MerchantId>, pub connector: Option<String>, pub request: Request, pub response: Result<Response, ErrorResponse>, pub connector_auth_type: ConnectorAuthType, pub connector_http_status_code: Option<u16>, } #[derive(Debug, Clone)] pub struct LinkTokenRequest { pub client_name: String, pub country_codes: Option<Vec<String>>, pub language: Option<String>, pub user_info: Option<id_type::CustomerId>, pub client_platform: Option<api_enums::ClientPlatform>, pub android_package_name: Option<String>, pub redirect_uri: Option<String>, } #[derive(Debug, Clone)] pub struct LinkTokenResponse { pub link_token: String, } pub type LinkTokenRouterData = PaymentAuthRouterData<LinkToken, LinkTokenRequest, LinkTokenResponse>; #[derive(Debug, Clone)] pub struct ExchangeTokenRequest { pub public_token: String, } #[derive(Debug, Clone)] pub struct ExchangeTokenResponse { pub access_token: String, } impl From<ExchangeTokenResponse> for api_models::pm_auth::ExchangeTokenCreateResponse { fn from(value: ExchangeTokenResponse) -> Self { Self { access_token: value.access_token, } } } pub type ExchangeTokenRouterData = PaymentAuthRouterData<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>; #[derive(Debug, Clone)] pub struct BankAccountCredentialsRequest { pub access_token: Secret<String>, pub optional_ids: Option<BankAccountOptionalIDs>, } #[derive(Debug, Clone)] pub struct BankAccountOptionalIDs { pub ids: Vec<Secret<String>>, } #[derive(Debug, Clone)] pub struct BankAccountCredentialsResponse { pub credentials: Vec<BankAccountDetails>, } #[derive(Debug, Clone)] pub struct BankAccountDetails { pub account_name: Option<String>, pub account_details: PaymentMethodTypeDetails, pub payment_method_type: PaymentMethodType, pub payment_method: PaymentMethod, pub account_id: Secret<String>, pub account_type: Option<String>, pub balance: Option<types::FloatMajorUnit>, } #[derive(Debug, Clone)] pub enum PaymentMethodTypeDetails { Ach(BankAccountDetailsAch), Bacs(BankAccountDetailsBacs), Sepa(BankAccountDetailsSepa), } #[derive(Debug, Clone)] pub struct BankAccountDetailsAch { pub account_number: Secret<String>, pub routing_number: Secret<String>, } #[derive(Debug, Clone)] pub struct BankAccountDetailsBacs { pub account_number: Secret<String>, pub sort_code: Secret<String>, } #[derive(Debug, Clone)] pub struct BankAccountDetailsSepa { pub iban: Secret<String>, pub bic: Secret<String>, } pub type BankDetailsRouterData = PaymentAuthRouterData< BankAccountCredentials, BankAccountCredentialsRequest, BankAccountCredentialsResponse, >; #[derive(Debug, Clone)] pub struct RecipientCreateRequest { pub name: String, pub account_data: RecipientAccountData, pub address: Option<RecipientCreateAddress>, } #[derive(Debug, Clone)] pub struct RecipientCreateResponse { pub recipient_id: String, } #[derive(Debug, Clone)] pub enum RecipientAccountData { Iban(Secret<String>), Bacs { sort_code: Secret<String>, account_number: Secret<String>, }, FasterPayments { sort_code: Secret<String>, account_number: Secret<String>, }, Sepa(Secret<String>), SepaInstant(Secret<String>), Elixir { account_number: Secret<String>, iban: Secret<String>, }, Bankgiro(Secret<String>), Plusgiro(Secret<String>), } #[derive(Debug, Clone)] pub struct RecipientCreateAddress { pub street: String, pub city: String, pub postal_code: String, pub country: CountryAlpha2, } pub type RecipientCreateRouterData = PaymentAuthRouterData<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>; pub type PaymentAuthLinkTokenType = dyn api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>; pub type PaymentAuthExchangeTokenType = dyn api::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>; pub type PaymentAuthBankAccountDetailsType = dyn api::ConnectorIntegration< BankAccountCredentials, BankAccountCredentialsRequest, BankAccountCredentialsResponse, >; pub type PaymentInitiationRecipientCreateType = dyn api::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>; #[derive(Clone, Debug, strum::EnumString, strum::Display)] #[strum(serialize_all = "snake_case")] pub enum PaymentMethodAuthConnectors { Plaid, } #[derive(Debug, Clone)] pub struct ResponseRouterData<Flow, R, Request, Response> { pub response: R, pub data: PaymentAuthRouterData<Flow, Request, Response>, pub http_code: u16, } #[derive(Clone, Debug, serde::Serialize)] pub struct ErrorResponse { pub code: String, pub message: String, pub reason: Option<String>, pub status_code: u16, } impl ErrorResponse { fn get_not_implemented() -> Self { Self { code: "IR_00".to_string(), message: "This API is under development and will be made available soon.".to_string(), reason: None, status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(), } } } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub enum MerchantAccountData { Iban { iban: Secret<String>, name: String, }, Bacs { account_number: Secret<String>, sort_code: Secret<String>, name: String, }, FasterPayments { account_number: Secret<String>, sort_code: Secret<String>, name: String, }, Sepa { iban: Secret<String>, name: String, }, SepaInstant { iban: Secret<String>, name: String, }, Elixir { account_number: Secret<String>, iban: Secret<String>, name: String, }, Bankgiro { number: Secret<String>, name: String, }, Plusgiro { number: Secret<String>, name: String, }, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum MerchantRecipientData { ConnectorRecipientId(Secret<String>), WalletId(Secret<String>), AccountData(MerchantAccountData), } #[derive(Default, Debug, Clone, serde::Deserialize)] pub enum ConnectorAuthType { BodyKey { client_id: Secret<String>, secret: Secret<String>, }, #[default] NoKey, } #[derive(Clone, Debug)] pub struct Response { pub headers: Option<http::HeaderMap>, pub response: bytes::Bytes, pub status_code: u16, } #[derive(serde::Deserialize, Clone)] pub struct AuthServiceQueryParam { pub client_secret: Option<String>, }
crates/pm_auth/src/types.rs
pm_auth::src::types
1,650
true
// File: crates/pm_auth/src/lib.rs // Module: pm_auth::src::lib pub mod connector; pub mod consts; pub mod core; pub mod types;
crates/pm_auth/src/lib.rs
pm_auth::src::lib
36
true
// File: crates/pm_auth/src/connector.rs // Module: pm_auth::src::connector pub mod plaid; pub use self::plaid::Plaid;
crates/pm_auth/src/connector.rs
pm_auth::src::connector
36
true
// File: crates/pm_auth/src/types/api.rs // Module: pm_auth::src::types::api pub mod auth_service; use std::fmt::Debug; use common_utils::{ errors::CustomResult, request::{Request, RequestContent}, }; use masking::Maskable; use crate::{ core::errors::ConnectorError, types::{ self as auth_types, api::auth_service::{AuthService, PaymentInitiation}, }, }; #[async_trait::async_trait] pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync { fn get_headers( &self, _req: &super::PaymentAuthRouterData<T, Req, Resp>, _connectors: &auth_types::PaymentMethodAuthConnectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { Ok(vec![]) } fn get_content_type(&self) -> &'static str { mime::APPLICATION_JSON.essence_str() } fn get_url( &self, _req: &super::PaymentAuthRouterData<T, Req, Resp>, _connectors: &auth_types::PaymentMethodAuthConnectors, ) -> CustomResult<String, ConnectorError> { Ok(String::new()) } fn get_request_body( &self, _req: &super::PaymentAuthRouterData<T, Req, Resp>, ) -> CustomResult<RequestContent, ConnectorError> { Ok(RequestContent::Json(Box::new(serde_json::json!(r#"{}"#)))) } fn build_request( &self, _req: &super::PaymentAuthRouterData<T, Req, Resp>, _connectors: &auth_types::PaymentMethodAuthConnectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(None) } fn handle_response( &self, data: &super::PaymentAuthRouterData<T, Req, Resp>, _res: auth_types::Response, ) -> CustomResult<super::PaymentAuthRouterData<T, Req, Resp>, ConnectorError> where T: Clone, Req: Clone, Resp: Clone, { Ok(data.clone()) } fn get_error_response( &self, _res: auth_types::Response, ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> { Ok(auth_types::ErrorResponse::get_not_implemented()) } fn get_5xx_error_response( &self, res: auth_types::Response, ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> { let error_message = match res.status_code { 500 => "internal_server_error", 501 => "not_implemented", 502 => "bad_gateway", 503 => "service_unavailable", 504 => "gateway_timeout", 505 => "http_version_not_supported", 506 => "variant_also_negotiates", 507 => "insufficient_storage", 508 => "loop_detected", 510 => "not_extended", 511 => "network_authentication_required", _ => "unknown_error", }; Ok(auth_types::ErrorResponse { code: res.status_code.to_string(), message: error_message.to_string(), reason: String::from_utf8(res.response.to_vec()).ok(), status_code: res.status_code, }) } } pub trait ConnectorCommonExt<Flow, Req, Resp>: ConnectorCommon + ConnectorIntegration<Flow, Req, Resp> { fn build_headers( &self, _req: &auth_types::PaymentAuthRouterData<Flow, Req, Resp>, _connectors: &auth_types::PaymentMethodAuthConnectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { Ok(Vec::new()) } } pub type BoxedConnectorIntegration<'a, T, Req, Resp> = Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>; pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static { fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>; } impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S where S: ConnectorIntegration<T, Req, Resp>, { fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> { Box::new(self) } } pub trait AuthServiceConnector: AuthService + Send + Debug + PaymentInitiation {} impl<T: Send + Debug + AuthService + PaymentInitiation> AuthServiceConnector for T {} pub type BoxedPaymentAuthConnector = Box<&'static (dyn AuthServiceConnector + Sync)>; #[derive(Clone, Debug)] pub struct PaymentAuthConnectorData { pub connector: BoxedPaymentAuthConnector, pub connector_name: super::PaymentMethodAuthConnectors, } pub trait ConnectorCommon { fn id(&self) -> &'static str; fn get_auth_header( &self, _auth_type: &auth_types::ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { Ok(Vec::new()) } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str; fn build_error_response( &self, res: auth_types::Response, ) -> CustomResult<auth_types::ErrorResponse, ConnectorError> { Ok(auth_types::ErrorResponse { status_code: res.status_code, code: crate::consts::NO_ERROR_CODE.to_string(), message: crate::consts::NO_ERROR_MESSAGE.to_string(), reason: None, }) } }
crates/pm_auth/src/types/api.rs
pm_auth::src::types::api
1,282
true
// File: crates/pm_auth/src/types/api/auth_service.rs // Module: pm_auth::src::types::api::auth_service use crate::types::{ BankAccountCredentialsRequest, BankAccountCredentialsResponse, ExchangeTokenRequest, ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse, RecipientCreateRequest, RecipientCreateResponse, }; pub trait AuthService: super::ConnectorCommon + AuthServiceLinkToken + AuthServiceExchangeToken + AuthServiceBankAccountCredentials { } pub trait PaymentInitiation: super::ConnectorCommon + PaymentInitiationRecipientCreate {} #[derive(Debug, Clone)] pub struct LinkToken; pub trait AuthServiceLinkToken: super::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse> { } #[derive(Debug, Clone)] pub struct ExchangeToken; pub trait AuthServiceExchangeToken: super::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse> { } #[derive(Debug, Clone)] pub struct BankAccountCredentials; pub trait AuthServiceBankAccountCredentials: super::ConnectorIntegration< BankAccountCredentials, BankAccountCredentialsRequest, BankAccountCredentialsResponse, > { } #[derive(Debug, Clone)] pub struct RecipientCreate; pub trait PaymentInitiationRecipientCreate: super::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse> { }
crates/pm_auth/src/types/api/auth_service.rs
pm_auth::src::types::api::auth_service
278
true
// File: crates/pm_auth/src/core/errors.rs // Module: pm_auth::src::core::errors #[derive(Debug, thiserror::Error, PartialEq)] pub enum ConnectorError { #[error("Failed to obtain authentication type")] FailedToObtainAuthType, #[error("Missing required field: {field_name}")] MissingRequiredField { field_name: &'static str }, #[error("Failed to execute a processing step: {0:?}")] ProcessingStepFailed(Option<bytes::Bytes>), #[error("Failed to deserialize connector response")] ResponseDeserializationFailed, #[error("Failed to encode connector request")] RequestEncodingFailed, #[error("Invalid connector configuration: {config}")] InvalidConnectorConfig { config: &'static str }, } pub type CustomResult<T, E> = error_stack::Result<T, E>; #[derive(Debug, thiserror::Error)] pub enum ParsingError { #[error("Failed to parse enum: {0}")] EnumParseFailure(&'static str), #[error("Failed to parse struct: {0}")] StructParseFailure(&'static str), #[error("Failed to serialize to {0} format")] EncodeError(&'static str), #[error("Unknown error while parsing")] UnknownError, }
crates/pm_auth/src/core/errors.rs
pm_auth::src::core::errors
270
true
// File: crates/pm_auth/src/connector/plaid.rs // Module: pm_auth::src::connector::plaid pub mod transformers; use std::fmt::Debug; use common_utils::{ ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, }; use error_stack::ResultExt; use masking::{Mask, Maskable}; use transformers as plaid; use crate::{ core::errors, types::{ self as auth_types, api::{ auth_service::{ self, BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate, }, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, }, }, }; #[derive(Debug, Clone)] pub struct Plaid; impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &auth_types::PaymentAuthRouterData<Flow, Request, Response>, _connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( "Content-Type".to_string(), self.get_content_type().to_string().into(), )]; let mut auth = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut auth); Ok(header) } } impl ConnectorCommon for Plaid { fn id(&self) -> &'static str { "plaid" } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, _connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str { "https://sandbox.plaid.com" } fn get_auth_header( &self, auth_type: &auth_types::ConnectorAuthType, ) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let auth = plaid::PlaidAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; let client_id = auth.client_id.into_masked(); let secret = auth.secret.into_masked(); Ok(vec![ ("PLAID-CLIENT-ID".to_string(), client_id), ("PLAID-SECRET".to_string(), secret), ]) } fn build_error_response( &self, res: auth_types::Response, ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { let response: plaid::PlaidErrorResponse = res.response .parse_struct("PlaidErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; Ok(auth_types::ErrorResponse { status_code: res.status_code, code: crate::consts::NO_ERROR_CODE.to_string(), message: response.error_message, reason: response.display_message, }) } } impl auth_service::AuthService for Plaid {} impl auth_service::PaymentInitiationRecipientCreate for Plaid {} impl auth_service::PaymentInitiation for Plaid {} impl auth_service::AuthServiceLinkToken for Plaid {} impl ConnectorIntegration<LinkToken, auth_types::LinkTokenRequest, auth_types::LinkTokenResponse> for Plaid { fn get_headers( &self, req: &auth_types::LinkTokenRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Vec<(String, 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: &auth_types::LinkTokenRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "/link/token/create" )) } fn get_request_body( &self, req: &auth_types::LinkTokenRouterData, ) -> errors::CustomResult<RequestContent, errors::ConnectorError> { let req_obj = plaid::PlaidLinkTokenRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &auth_types::LinkTokenRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&auth_types::PaymentAuthLinkTokenType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(auth_types::PaymentAuthLinkTokenType::get_headers( self, req, connectors, )?) .set_body(auth_types::PaymentAuthLinkTokenType::get_request_body( self, req, )?) .build(), )) } fn handle_response( &self, data: &auth_types::LinkTokenRouterData, res: auth_types::Response, ) -> errors::CustomResult<auth_types::LinkTokenRouterData, errors::ConnectorError> { let response: plaid::PlaidLinkTokenResponse = res .response .parse_struct("PlaidLinkTokenResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; <auth_types::LinkTokenRouterData>::try_from(auth_types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: auth_types::Response, ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res) } } impl auth_service::AuthServiceExchangeToken for Plaid {} impl ConnectorIntegration< ExchangeToken, auth_types::ExchangeTokenRequest, auth_types::ExchangeTokenResponse, > for Plaid { fn get_headers( &self, req: &auth_types::ExchangeTokenRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Vec<(String, 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: &auth_types::ExchangeTokenRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "/item/public_token/exchange" )) } fn get_request_body( &self, req: &auth_types::ExchangeTokenRouterData, ) -> errors::CustomResult<RequestContent, errors::ConnectorError> { let req_obj = plaid::PlaidExchangeTokenRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &auth_types::ExchangeTokenRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&auth_types::PaymentAuthExchangeTokenType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(auth_types::PaymentAuthExchangeTokenType::get_headers( self, req, connectors, )?) .set_body(auth_types::PaymentAuthExchangeTokenType::get_request_body( self, req, )?) .build(), )) } fn handle_response( &self, data: &auth_types::ExchangeTokenRouterData, res: auth_types::Response, ) -> errors::CustomResult<auth_types::ExchangeTokenRouterData, errors::ConnectorError> { let response: plaid::PlaidExchangeTokenResponse = res .response .parse_struct("PlaidExchangeTokenResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; <auth_types::ExchangeTokenRouterData>::try_from(auth_types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: auth_types::Response, ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res) } } impl auth_service::AuthServiceBankAccountCredentials for Plaid {} impl ConnectorIntegration< BankAccountCredentials, auth_types::BankAccountCredentialsRequest, auth_types::BankAccountCredentialsResponse, > for Plaid { fn get_headers( &self, req: &auth_types::BankDetailsRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Vec<(String, 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: &auth_types::BankDetailsRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<String, errors::ConnectorError> { Ok(format!("{}{}", self.base_url(connectors), "/auth/get")) } fn get_request_body( &self, req: &auth_types::BankDetailsRouterData, ) -> errors::CustomResult<RequestContent, errors::ConnectorError> { let req_obj = plaid::PlaidBankAccountCredentialsRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &auth_types::BankDetailsRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&auth_types::PaymentAuthBankAccountDetailsType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(auth_types::PaymentAuthBankAccountDetailsType::get_headers( self, req, connectors, )?) .set_body( auth_types::PaymentAuthBankAccountDetailsType::get_request_body(self, req)?, ) .build(), )) } fn handle_response( &self, data: &auth_types::BankDetailsRouterData, res: auth_types::Response, ) -> errors::CustomResult<auth_types::BankDetailsRouterData, errors::ConnectorError> { let response: plaid::PlaidBankAccountCredentialsResponse = res .response .parse_struct("PlaidBankAccountCredentialsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; <auth_types::BankDetailsRouterData>::try_from(auth_types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: auth_types::Response, ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res) } } impl ConnectorIntegration< RecipientCreate, auth_types::RecipientCreateRequest, auth_types::RecipientCreateResponse, > for Plaid { fn get_headers( &self, req: &auth_types::RecipientCreateRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Vec<(String, 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: &auth_types::RecipientCreateRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<String, errors::ConnectorError> { Ok(format!( "{}{}", self.base_url(connectors), "/payment_initiation/recipient/create" )) } fn get_request_body( &self, req: &auth_types::RecipientCreateRouterData, ) -> errors::CustomResult<RequestContent, errors::ConnectorError> { let req_obj = plaid::PlaidRecipientCreateRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(req_obj))) } fn build_request( &self, req: &auth_types::RecipientCreateRouterData, connectors: &auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&auth_types::PaymentInitiationRecipientCreateType::get_url( self, req, connectors, )?) .attach_default_headers() .headers( auth_types::PaymentInitiationRecipientCreateType::get_headers( self, req, connectors, )?, ) .set_body( auth_types::PaymentInitiationRecipientCreateType::get_request_body(self, req)?, ) .build(), )) } fn handle_response( &self, data: &auth_types::RecipientCreateRouterData, res: auth_types::Response, ) -> errors::CustomResult<auth_types::RecipientCreateRouterData, errors::ConnectorError> { let response: plaid::PlaidRecipientCreateResponse = res .response .parse_struct("PlaidRecipientCreateResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; Ok(<auth_types::RecipientCreateRouterData>::from( auth_types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }, )) } fn get_error_response( &self, res: auth_types::Response, ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> { self.build_error_response(res) } }
crates/pm_auth/src/connector/plaid.rs
pm_auth::src::connector::plaid
3,157
true
// File: crates/pm_auth/src/connector/plaid/transformers.rs // Module: pm_auth::src::connector::plaid::transformers use std::collections::HashMap; use common_enums::{PaymentMethod, PaymentMethodType}; use common_utils::{id_type, types as util_types}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{core::errors, types}; #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct PlaidLinkTokenRequest { client_name: String, country_codes: Vec<String>, language: String, products: Vec<String>, user: User, android_package_name: Option<String>, redirect_uri: Option<String>, } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct User { pub client_user_id: id_type::CustomerId, } impl TryFrom<&types::LinkTokenRouterData> for PlaidLinkTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::LinkTokenRouterData) -> Result<Self, Self::Error> { Ok(Self { client_name: item.request.client_name.clone(), country_codes: item.request.country_codes.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "country_codes", }, )?, language: item.request.language.clone().unwrap_or("en".to_string()), products: vec!["auth".to_string()], user: User { client_user_id: item.request.user_info.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "country_codes", }, )?, }, android_package_name: match item.request.client_platform { Some(api_models::enums::ClientPlatform::Android) => { item.request.android_package_name.clone() } Some(api_models::enums::ClientPlatform::Ios) | Some(api_models::enums::ClientPlatform::Web) | Some(api_models::enums::ClientPlatform::Unknown) | None => None, }, redirect_uri: match item.request.client_platform { Some(api_models::enums::ClientPlatform::Ios) => item.request.redirect_uri.clone(), Some(api_models::enums::ClientPlatform::Android) | Some(api_models::enums::ClientPlatform::Web) | Some(api_models::enums::ClientPlatform::Unknown) | None => None, }, }) } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub struct PlaidLinkTokenResponse { link_token: String, } impl<F, T> TryFrom<types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>> for types::PaymentAuthRouterData<F, T, types::LinkTokenResponse> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::LinkTokenResponse { link_token: item.response.link_token, }), ..item.data }) } } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct PlaidExchangeTokenRequest { public_token: String, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidExchangeTokenResponse { pub access_token: String, } impl<F, T> TryFrom< types::ResponseRouterData<F, PlaidExchangeTokenResponse, T, types::ExchangeTokenResponse>, > for types::PaymentAuthRouterData<F, T, types::ExchangeTokenResponse> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData< F, PlaidExchangeTokenResponse, T, types::ExchangeTokenResponse, >, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::ExchangeTokenResponse { access_token: item.response.access_token, }), ..item.data }) } } impl TryFrom<&types::ExchangeTokenRouterData> for PlaidExchangeTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::ExchangeTokenRouterData) -> Result<Self, Self::Error> { Ok(Self { public_token: item.request.public_token.clone(), }) } } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct PlaidRecipientCreateRequest { pub name: String, #[serde(flatten)] pub account_data: PlaidRecipientAccountData, pub address: Option<PlaidRecipientCreateAddress>, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidRecipientCreateResponse { pub recipient_id: String, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "lowercase")] pub enum PlaidRecipientAccountData { Iban(Secret<String>), Bacs { sort_code: Secret<String>, account: Secret<String>, }, } impl TryFrom<&types::RecipientAccountData> for PlaidRecipientAccountData { type Error = errors::ConnectorError; fn try_from(item: &types::RecipientAccountData) -> Result<Self, Self::Error> { match item { types::RecipientAccountData::Iban(iban) => Ok(Self::Iban(iban.clone())), types::RecipientAccountData::Bacs { sort_code, account_number, } => Ok(Self::Bacs { sort_code: sort_code.clone(), account: account_number.clone(), }), types::RecipientAccountData::FasterPayments { .. } | types::RecipientAccountData::Sepa(_) | types::RecipientAccountData::SepaInstant(_) | types::RecipientAccountData::Elixir { .. } | types::RecipientAccountData::Bankgiro(_) | types::RecipientAccountData::Plusgiro(_) => { Err(errors::ConnectorError::InvalidConnectorConfig { config: "Invalid payment method selected. Only Iban, Bacs Supported", }) } } } } #[derive(Debug, Serialize, Eq, PartialEq)] pub struct PlaidRecipientCreateAddress { pub street: String, pub city: String, pub postal_code: String, pub country: String, } impl From<&types::RecipientCreateAddress> for PlaidRecipientCreateAddress { fn from(item: &types::RecipientCreateAddress) -> Self { Self { street: item.street.clone(), city: item.city.clone(), postal_code: item.postal_code.clone(), country: common_enums::CountryAlpha2::to_string(&item.country), } } } impl TryFrom<&types::RecipientCreateRouterData> for PlaidRecipientCreateRequest { type Error = errors::ConnectorError; fn try_from(item: &types::RecipientCreateRouterData) -> Result<Self, Self::Error> { Ok(Self { name: item.request.name.clone(), account_data: PlaidRecipientAccountData::try_from(&item.request.account_data)?, address: item .request .address .as_ref() .map(PlaidRecipientCreateAddress::from), }) } } impl<F, T> From< types::ResponseRouterData< F, PlaidRecipientCreateResponse, T, types::RecipientCreateResponse, >, > for types::PaymentAuthRouterData<F, T, types::RecipientCreateResponse> { fn from( item: types::ResponseRouterData< F, PlaidRecipientCreateResponse, T, types::RecipientCreateResponse, >, ) -> Self { Self { response: Ok(types::RecipientCreateResponse { recipient_id: item.response.recipient_id, }), ..item.data } } } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct PlaidBankAccountCredentialsRequest { access_token: String, options: Option<BankAccountCredentialsOptions>, } #[derive(Debug, Deserialize, PartialEq)] pub struct PlaidBankAccountCredentialsResponse { pub accounts: Vec<PlaidBankAccountCredentialsAccounts>, pub numbers: PlaidBankAccountCredentialsNumbers, // pub item: PlaidBankAccountCredentialsItem, pub request_id: String, } #[derive(Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct BankAccountCredentialsOptions { account_ids: Vec<String>, } #[derive(Debug, Deserialize, PartialEq)] pub struct PlaidBankAccountCredentialsAccounts { pub account_id: String, pub name: String, pub subtype: Option<String>, pub balances: Option<PlaidBankAccountCredentialsBalances>, } #[derive(Debug, Deserialize, PartialEq)] pub struct PlaidBankAccountCredentialsBalances { pub available: Option<util_types::FloatMajorUnit>, pub current: Option<util_types::FloatMajorUnit>, pub limit: Option<util_types::FloatMajorUnit>, pub iso_currency_code: Option<String>, pub unofficial_currency_code: Option<String>, pub last_updated_datetime: Option<String>, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidBankAccountCredentialsNumbers { pub ach: Vec<PlaidBankAccountCredentialsACH>, pub eft: Vec<PlaidBankAccountCredentialsEFT>, pub international: Vec<PlaidBankAccountCredentialsInternational>, pub bacs: Vec<PlaidBankAccountCredentialsBacs>, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidBankAccountCredentialsItem { pub item_id: String, pub institution_id: Option<String>, pub webhook: Option<String>, pub error: Option<PlaidErrorResponse>, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidBankAccountCredentialsACH { pub account_id: String, pub account: String, pub routing: String, pub wire_routing: Option<String>, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidBankAccountCredentialsEFT { pub account_id: String, pub account: String, pub institution: String, pub branch: String, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidBankAccountCredentialsInternational { pub account_id: String, pub iban: String, pub bic: String, } #[derive(Debug, Deserialize, Eq, PartialEq)] pub struct PlaidBankAccountCredentialsBacs { pub account_id: String, pub account: String, pub sort_code: String, } impl TryFrom<&types::BankDetailsRouterData> for PlaidBankAccountCredentialsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::BankDetailsRouterData) -> Result<Self, Self::Error> { let options = item.request.optional_ids.as_ref().map(|bank_account_ids| { let ids = bank_account_ids .ids .iter() .map(|id| id.peek().to_string()) .collect::<Vec<_>>(); BankAccountCredentialsOptions { account_ids: ids } }); Ok(Self { access_token: item.request.access_token.peek().to_string(), options, }) } } impl<F, T> TryFrom< types::ResponseRouterData< F, PlaidBankAccountCredentialsResponse, T, types::BankAccountCredentialsResponse, >, > for types::PaymentAuthRouterData<F, T, types::BankAccountCredentialsResponse> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: types::ResponseRouterData< F, PlaidBankAccountCredentialsResponse, T, types::BankAccountCredentialsResponse, >, ) -> Result<Self, Self::Error> { let (account_numbers, accounts_info) = (item.response.numbers, item.response.accounts); let mut bank_account_vec = Vec::new(); let mut id_to_subtype = HashMap::new(); accounts_info.into_iter().for_each(|acc| { id_to_subtype.insert( acc.account_id, ( acc.subtype, acc.name, acc.balances.and_then(|balance| balance.available), ), ); }); account_numbers.ach.into_iter().for_each(|ach| { let (acc_type, acc_name, available_balance) = if let Some(( _type, name, available_balance, )) = id_to_subtype.get(&ach.account_id) { (_type.to_owned(), Some(name.clone()), *available_balance) } else { (None, None, None) }; let account_details = types::PaymentMethodTypeDetails::Ach(types::BankAccountDetailsAch { account_number: Secret::new(ach.account), routing_number: Secret::new(ach.routing), }); let bank_details_new = types::BankAccountDetails { account_name: acc_name, account_details, payment_method_type: PaymentMethodType::Ach, payment_method: PaymentMethod::BankDebit, account_id: ach.account_id.into(), account_type: acc_type, balance: available_balance, }; bank_account_vec.push(bank_details_new); }); account_numbers.bacs.into_iter().for_each(|bacs| { let (acc_type, acc_name, available_balance) = if let Some((_type, name, available_balance)) = id_to_subtype.get(&bacs.account_id) { (_type.to_owned(), Some(name.clone()), *available_balance) } else { (None, None, None) }; let account_details = types::PaymentMethodTypeDetails::Bacs(types::BankAccountDetailsBacs { account_number: Secret::new(bacs.account), sort_code: Secret::new(bacs.sort_code), }); let bank_details_new = types::BankAccountDetails { account_name: acc_name, account_details, payment_method_type: PaymentMethodType::Bacs, payment_method: PaymentMethod::BankDebit, account_id: bacs.account_id.into(), account_type: acc_type, balance: available_balance, }; bank_account_vec.push(bank_details_new); }); account_numbers.international.into_iter().for_each(|sepa| { let (acc_type, acc_name, available_balance) = if let Some((_type, name, available_balance)) = id_to_subtype.get(&sepa.account_id) { (_type.to_owned(), Some(name.clone()), *available_balance) } else { (None, None, None) }; let account_details = types::PaymentMethodTypeDetails::Sepa(types::BankAccountDetailsSepa { iban: Secret::new(sepa.iban), bic: Secret::new(sepa.bic), }); let bank_details_new = types::BankAccountDetails { account_name: acc_name, account_details, payment_method_type: PaymentMethodType::Sepa, payment_method: PaymentMethod::BankDebit, account_id: sepa.account_id.into(), account_type: acc_type, balance: available_balance, }; bank_account_vec.push(bank_details_new); }); Ok(Self { response: Ok(types::BankAccountCredentialsResponse { credentials: bank_account_vec, }), ..item.data }) } } pub struct PlaidAuthType { pub client_id: Secret<String>, pub secret: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { client_id, secret } => Ok(Self { client_id: client_id.to_owned(), secret: secret.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } #[derive(Debug, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub struct PlaidErrorResponse { pub display_message: Option<String>, pub error_code: Option<String>, pub error_message: String, pub error_type: Option<String>, }
crates/pm_auth/src/connector/plaid/transformers.rs
pm_auth::src::connector::plaid::transformers
3,538
true
// File: crates/kgraph_utils/benches/evaluation.rs // Module: kgraph_utils::benches::evaluation #![allow(unused, clippy::expect_used)] use std::{collections::HashMap, str::FromStr}; use api_models::{ admin as admin_api, enums as api_enums, payment_methods::RequestPaymentMethodTypes, }; use common_utils::types::MinorUnit; use criterion::{black_box, criterion_group, criterion_main, Criterion}; use euclid::{ dirval, dssa::graph::{self, CgraphExt}, frontend::dir, types::{NumValue, NumValueRefinement}, }; use hyperswitch_constraint_graph::{CycleCheck, Memoization}; use kgraph_utils::{error::KgraphError, transformers::IntoDirValue, types::CountryCurrencyFilter}; #[cfg(feature = "v1")] fn build_test_data( total_enabled: usize, total_pm_types: usize, ) -> hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue> { use api_models::{admin::*, payment_methods::*}; let mut pms_enabled: Vec<PaymentMethodsEnabled> = Vec::new(); for _ in (0..total_enabled) { let mut pm_types: Vec<RequestPaymentMethodTypes> = Vec::new(); for _ in (0..total_pm_types) { pm_types.push(RequestPaymentMethodTypes { payment_method_type: api_enums::PaymentMethodType::Credit, payment_experience: None, card_networks: Some(vec![ api_enums::CardNetwork::Visa, api_enums::CardNetwork::Mastercard, ]), accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![ api_enums::Currency::USD, api_enums::Currency::INR, ])), accepted_countries: None, minimum_amount: Some(MinorUnit::new(10)), maximum_amount: Some(MinorUnit::new(1000)), recurring_enabled: Some(true), installment_payment_enabled: Some(true), }); } pms_enabled.push(PaymentMethodsEnabled { payment_method: api_enums::PaymentMethod::Card, payment_method_types: Some(pm_types), }); } let profile_id = common_utils::generate_profile_id_of_default_length(); // #[cfg(feature = "v2")] // let stripe_account = MerchantConnectorResponse { // connector_type: api_enums::ConnectorType::FizOperations, // connector_name: "stripe".to_string(), // id: common_utils::generate_merchant_connector_account_id_of_default_length(), // connector_account_details: masking::Secret::new(serde_json::json!({})), // disabled: None, // metadata: None, // payment_methods_enabled: Some(pms_enabled), // connector_label: Some("something".to_string()), // frm_configs: None, // connector_webhook_details: None, // profile_id, // applepay_verified_domains: None, // pm_auth_config: None, // status: api_enums::ConnectorStatus::Inactive, // additional_merchant_data: None, // connector_wallets_details: None, // }; #[cfg(feature = "v1")] let stripe_account = MerchantConnectorResponse { connector_type: api_enums::ConnectorType::FizOperations, connector_name: "stripe".to_string(), merchant_connector_id: common_utils::generate_merchant_connector_account_id_of_default_length(), connector_account_details: masking::Secret::new(serde_json::json!({})), test_mode: None, disabled: None, metadata: None, payment_methods_enabled: Some(pms_enabled), business_country: Some(api_enums::CountryAlpha2::US), business_label: Some("hello".to_string()), connector_label: Some("something".to_string()), business_sub_label: Some("something".to_string()), frm_configs: None, connector_webhook_details: None, profile_id, applepay_verified_domains: None, pm_auth_config: None, status: api_enums::ConnectorStatus::Inactive, additional_merchant_data: None, connector_wallets_details: None, }; let config = CountryCurrencyFilter { connector_configs: HashMap::new(), default_configs: None, }; #[cfg(feature = "v1")] kgraph_utils::mca::make_mca_graph(vec![stripe_account], &config) .expect("Failed graph construction") } #[cfg(feature = "v1")] fn evaluation(c: &mut Criterion) { let small_graph = build_test_data(3, 8); let big_graph = build_test_data(20, 20); c.bench_function("MCA Small Graph Evaluation", |b| { b.iter(|| { small_graph.key_value_analysis( dirval!(Connector = Stripe), &graph::AnalysisContext::from_dir_values([ dirval!(Connector = Stripe), dirval!(PaymentMethod = Card), dirval!(CardType = Credit), dirval!(CardNetwork = Visa), dirval!(PaymentCurrency = BWP), dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), &mut CycleCheck::new(), None, ); }); }); c.bench_function("MCA Big Graph Evaluation", |b| { b.iter(|| { big_graph.key_value_analysis( dirval!(Connector = Stripe), &graph::AnalysisContext::from_dir_values([ dirval!(Connector = Stripe), dirval!(PaymentMethod = Card), dirval!(CardType = Credit), dirval!(CardNetwork = Visa), dirval!(PaymentCurrency = BWP), dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), &mut CycleCheck::new(), None, ); }); }); } #[cfg(feature = "v1")] criterion_group!(benches, evaluation); #[cfg(feature = "v1")] criterion_main!(benches); #[cfg(feature = "v2")] fn main() {}
crates/kgraph_utils/benches/evaluation.rs
kgraph_utils::benches::evaluation
1,333
true
// File: crates/kgraph_utils/src/types.rs // Module: kgraph_utils::src::types use std::collections::{HashMap, HashSet}; use api_models::enums as api_enums; use serde::Deserialize; #[derive(Debug, Deserialize, Clone, Default)] pub struct CountryCurrencyFilter { pub connector_configs: HashMap<api_enums::RoutableConnectors, PaymentMethodFilters>, pub default_configs: Option<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(api_enums::PaymentMethodType), CardNetwork(api_enums::CardNetwork), } #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct CurrencyCountryFlowFilter { pub currency: Option<HashSet<api_enums::Currency>>, pub country: Option<HashSet<api_enums::CountryAlpha2>>, pub not_available_flows: Option<NotAvailableFlows>, } #[derive(Debug, Deserialize, Copy, Clone, Default)] #[serde(default)] pub struct NotAvailableFlows { pub capture_method: Option<api_enums::CaptureMethod>, }
crates/kgraph_utils/src/types.rs
kgraph_utils::src::types
283
true
// File: crates/kgraph_utils/src/error.rs // Module: kgraph_utils::src::error #[cfg(feature = "v2")] use common_enums::connector_enums; use euclid::{dssa::types::AnalysisErrorType, frontend::dir}; #[derive(Debug, thiserror::Error, serde::Serialize)] #[serde(tag = "type", content = "info", rename_all = "snake_case")] pub enum KgraphError { #[error("Invalid connector name encountered: '{0}'")] InvalidConnectorName( #[cfg(feature = "v1")] String, #[cfg(feature = "v2")] connector_enums::Connector, ), #[error("Error in domain creation")] DomainCreationError, #[error("There was an error constructing the graph: {0}")] GraphConstructionError(hyperswitch_constraint_graph::GraphError<dir::DirValue>), #[error("There was an error constructing the context")] ContextConstructionError(Box<AnalysisErrorType>), #[error("there was an unprecedented indexing error")] IndexingError, }
crates/kgraph_utils/src/error.rs
kgraph_utils::src::error
229
true
// File: crates/kgraph_utils/src/transformers.rs // Module: kgraph_utils::src::transformers use api_models::enums as api_enums; use euclid::{ backend::BackendInput, dirval, dssa::types::AnalysisErrorType, frontend::{ast, dir}, types::{NumValue, StrValue}, }; use crate::error::KgraphError; pub trait IntoContext { fn into_context(self) -> Result<Vec<dir::DirValue>, KgraphError>; } impl IntoContext for BackendInput { fn into_context(self) -> Result<Vec<dir::DirValue>, KgraphError> { let mut ctx: Vec<dir::DirValue> = Vec::new(); ctx.push(dir::DirValue::PaymentAmount(NumValue { number: self.payment.amount, refinement: None, })); ctx.push(dir::DirValue::PaymentCurrency(self.payment.currency)); if let Some(auth_type) = self.payment.authentication_type { ctx.push(dir::DirValue::AuthenticationType(auth_type)); } if let Some(capture_method) = self.payment.capture_method { ctx.push(dir::DirValue::CaptureMethod(capture_method)); } if let Some(business_country) = self.payment.business_country { ctx.push(dir::DirValue::BusinessCountry(business_country)); } if let Some(business_label) = self.payment.business_label { ctx.push(dir::DirValue::BusinessLabel(StrValue { value: business_label, })); } if let Some(billing_country) = self.payment.billing_country { ctx.push(dir::DirValue::BillingCountry(billing_country)); } if let Some(payment_method) = self.payment_method.payment_method { ctx.push(dir::DirValue::PaymentMethod(payment_method)); } if let (Some(pm_type), Some(payment_method)) = ( self.payment_method.payment_method_type, self.payment_method.payment_method, ) { ctx.push((pm_type, payment_method).into_dir_value()?) } if let Some(card_network) = self.payment_method.card_network { ctx.push(dir::DirValue::CardNetwork(card_network)); } if let Some(setup_future_usage) = self.payment.setup_future_usage { ctx.push(dir::DirValue::SetupFutureUsage(setup_future_usage)); } if let Some(mandate_acceptance_type) = self.mandate.mandate_acceptance_type { ctx.push(dir::DirValue::MandateAcceptanceType( mandate_acceptance_type, )); } if let Some(mandate_type) = self.mandate.mandate_type { ctx.push(dir::DirValue::MandateType(mandate_type)); } if let Some(payment_type) = self.mandate.payment_type { ctx.push(dir::DirValue::PaymentType(payment_type)); } Ok(ctx) } } pub trait IntoDirValue { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError>; } impl IntoDirValue for ast::ConnectorChoice { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { Ok(dir::DirValue::Connector(Box::new(self))) } } impl IntoDirValue for api_enums::PaymentMethod { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { match self { Self::Card => Ok(dirval!(PaymentMethod = Card)), Self::Wallet => Ok(dirval!(PaymentMethod = Wallet)), Self::PayLater => Ok(dirval!(PaymentMethod = PayLater)), Self::BankRedirect => Ok(dirval!(PaymentMethod = BankRedirect)), Self::Crypto => Ok(dirval!(PaymentMethod = Crypto)), Self::BankDebit => Ok(dirval!(PaymentMethod = BankDebit)), Self::BankTransfer => Ok(dirval!(PaymentMethod = BankTransfer)), Self::Reward => Ok(dirval!(PaymentMethod = Reward)), Self::RealTimePayment => Ok(dirval!(PaymentMethod = RealTimePayment)), Self::Upi => Ok(dirval!(PaymentMethod = Upi)), Self::Voucher => Ok(dirval!(PaymentMethod = Voucher)), Self::GiftCard => Ok(dirval!(PaymentMethod = GiftCard)), Self::CardRedirect => Ok(dirval!(PaymentMethod = CardRedirect)), Self::OpenBanking => Ok(dirval!(PaymentMethod = OpenBanking)), Self::MobilePayment => Ok(dirval!(PaymentMethod = MobilePayment)), } } } impl IntoDirValue for api_enums::AuthenticationType { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { match self { Self::ThreeDs => Ok(dirval!(AuthenticationType = ThreeDs)), Self::NoThreeDs => Ok(dirval!(AuthenticationType = NoThreeDs)), } } } impl IntoDirValue for api_enums::FutureUsage { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { match self { Self::OnSession => Ok(dirval!(SetupFutureUsage = OnSession)), Self::OffSession => Ok(dirval!(SetupFutureUsage = OffSession)), } } } impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { match self.0 { api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)), api_enums::PaymentMethodType::Paysera => Ok(dirval!(WalletType = Paysera)), api_enums::PaymentMethodType::Skrill => Ok(dirval!(WalletType = Skrill)), api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)), api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)), #[cfg(feature = "v2")] api_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)), api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)), api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), api_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)), api_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)), api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)), api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)), api_enums::PaymentMethodType::AfterpayClearpay => { Ok(dirval!(PayLaterType = AfterpayClearpay)) } api_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)), api_enums::PaymentMethodType::Bluecode => Ok(dirval!(WalletType = Bluecode)), api_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)), api_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)), api_enums::PaymentMethodType::CryptoCurrency => { Ok(dirval!(CryptoType = CryptoCurrency)) } api_enums::PaymentMethodType::RevolutPay => Ok(dirval!(WalletType = RevolutPay)), api_enums::PaymentMethodType::Ach => match self.1 { api_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Ach)), api_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Ach)), api_enums::PaymentMethod::BankRedirect | api_enums::PaymentMethod::Card | api_enums::PaymentMethod::CardRedirect | api_enums::PaymentMethod::PayLater | api_enums::PaymentMethod::Wallet | api_enums::PaymentMethod::Crypto | api_enums::PaymentMethod::Reward | api_enums::PaymentMethod::RealTimePayment | api_enums::PaymentMethod::Upi | api_enums::PaymentMethod::MobilePayment | api_enums::PaymentMethod::Voucher | api_enums::PaymentMethod::OpenBanking | api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError( Box::new(AnalysisErrorType::NotSupported), )), }, api_enums::PaymentMethodType::Bacs => match self.1 { api_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Bacs)), api_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Bacs)), api_enums::PaymentMethod::BankRedirect | api_enums::PaymentMethod::Card | api_enums::PaymentMethod::CardRedirect | api_enums::PaymentMethod::PayLater | api_enums::PaymentMethod::Wallet | api_enums::PaymentMethod::Crypto | api_enums::PaymentMethod::Reward | api_enums::PaymentMethod::RealTimePayment | api_enums::PaymentMethod::Upi | api_enums::PaymentMethod::MobilePayment | api_enums::PaymentMethod::Voucher | api_enums::PaymentMethod::OpenBanking | api_enums::PaymentMethod::GiftCard => Err(KgraphError::ContextConstructionError( Box::new(AnalysisErrorType::NotSupported), )), }, api_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)), api_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)), api_enums::PaymentMethodType::SepaGuarenteedDebit => { Ok(dirval!(BankDebitType = SepaGuarenteedDebit)) } api_enums::PaymentMethodType::SepaBankTransfer => { Ok(dirval!(BankTransferType = SepaBankTransfer)) } api_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)), api_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)), api_enums::PaymentMethodType::BancontactCard => { Ok(dirval!(BankRedirectType = BancontactCard)) } api_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)), api_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)), api_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)), api_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)), api_enums::PaymentMethodType::Multibanco => Ok(dirval!(BankTransferType = Multibanco)), api_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)), api_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)), api_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)), api_enums::PaymentMethodType::OnlineBankingCzechRepublic => { Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic)) } api_enums::PaymentMethodType::OnlineBankingFinland => { Ok(dirval!(BankRedirectType = OnlineBankingFinland)) } api_enums::PaymentMethodType::OnlineBankingPoland => { Ok(dirval!(BankRedirectType = OnlineBankingPoland)) } api_enums::PaymentMethodType::OnlineBankingSlovakia => { Ok(dirval!(BankRedirectType = OnlineBankingSlovakia)) } api_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)), api_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)), api_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)), api_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)), api_enums::PaymentMethodType::Flexiti => Ok(dirval!(PayLaterType = Flexiti)), api_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)), api_enums::PaymentMethodType::Breadpay => Ok(dirval!(PayLaterType = Breadpay)), api_enums::PaymentMethodType::Przelewy24 => Ok(dirval!(BankRedirectType = Przelewy24)), api_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)), api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)), api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)), api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)), api_enums::PaymentMethodType::UpiQr => Ok(dirval!(UpiType = UpiQr)), api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)), api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)), api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)), api_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)), api_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)), api_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)), api_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)), api_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)), api_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)), api_enums::PaymentMethodType::OnlineBankingFpx => { Ok(dirval!(BankRedirectType = OnlineBankingFpx)) } api_enums::PaymentMethodType::LocalBankRedirect => { Ok(dirval!(BankRedirectType = LocalBankRedirect)) } api_enums::PaymentMethodType::OnlineBankingThailand => { Ok(dirval!(BankRedirectType = OnlineBankingThailand)) } api_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)), api_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)), api_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)), api_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)), api_enums::PaymentMethodType::PagoEfectivo => Ok(dirval!(VoucherType = PagoEfectivo)), api_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)), api_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)), api_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)), api_enums::PaymentMethodType::BcaBankTransfer => { Ok(dirval!(BankTransferType = BcaBankTransfer)) } api_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)), api_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)), api_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)), api_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)), api_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)), api_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)), api_enums::PaymentMethodType::LocalBankTransfer => { Ok(dirval!(BankTransferType = LocalBankTransfer)) } api_enums::PaymentMethodType::InstantBankTransfer => { Ok(dirval!(BankTransferType = InstantBankTransfer)) } api_enums::PaymentMethodType::InstantBankTransferFinland => { Ok(dirval!(BankTransferType = InstantBankTransferFinland)) } api_enums::PaymentMethodType::InstantBankTransferPoland => { Ok(dirval!(BankTransferType = InstantBankTransferPoland)) } api_enums::PaymentMethodType::PermataBankTransfer => { Ok(dirval!(BankTransferType = PermataBankTransfer)) } api_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)), api_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)), api_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)), api_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)), api_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)), api_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)), api_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)), api_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)), api_enums::PaymentMethodType::BhnCardNetwork => { Ok(dirval!(GiftCardType = BhnCardNetwork)) } api_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)), api_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)), api_enums::PaymentMethodType::OpenBankingUk => { Ok(dirval!(BankRedirectType = OpenBankingUk)) } api_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)), api_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)), api_enums::PaymentMethodType::CardRedirect => { Ok(dirval!(CardRedirectType = CardRedirect)) } api_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)), api_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)), api_enums::PaymentMethodType::Fps => Ok(dirval!(RealTimePaymentType = Fps)), api_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)), api_enums::PaymentMethodType::PromptPay => Ok(dirval!(RealTimePaymentType = PromptPay)), api_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)), api_enums::PaymentMethodType::OpenBankingPIS => { Ok(dirval!(OpenBankingType = OpenBankingPIS)) } api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)), api_enums::PaymentMethodType::DirectCarrierBilling => { Ok(dirval!(MobilePaymentType = DirectCarrierBilling)) } api_enums::PaymentMethodType::IndonesianBankTransfer => { Ok(dirval!(BankTransferType = IndonesianBankTransfer)) } } } } impl IntoDirValue for api_enums::CardNetwork { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { match self { Self::Visa => Ok(dirval!(CardNetwork = Visa)), Self::Mastercard => Ok(dirval!(CardNetwork = Mastercard)), Self::AmericanExpress => Ok(dirval!(CardNetwork = AmericanExpress)), Self::JCB => Ok(dirval!(CardNetwork = JCB)), Self::DinersClub => Ok(dirval!(CardNetwork = DinersClub)), Self::Discover => Ok(dirval!(CardNetwork = Discover)), Self::CartesBancaires => Ok(dirval!(CardNetwork = CartesBancaires)), Self::UnionPay => Ok(dirval!(CardNetwork = UnionPay)), Self::Interac => Ok(dirval!(CardNetwork = Interac)), Self::RuPay => Ok(dirval!(CardNetwork = RuPay)), Self::Maestro => Ok(dirval!(CardNetwork = Maestro)), Self::Star => Ok(dirval!(CardNetwork = Star)), Self::Accel => Ok(dirval!(CardNetwork = Accel)), Self::Pulse => Ok(dirval!(CardNetwork = Pulse)), Self::Nyce => Ok(dirval!(CardNetwork = Nyce)), } } } impl IntoDirValue for api_enums::Currency { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { match self { Self::AED => Ok(dirval!(PaymentCurrency = AED)), Self::AFN => Ok(dirval!(PaymentCurrency = AFN)), Self::ALL => Ok(dirval!(PaymentCurrency = ALL)), Self::AMD => Ok(dirval!(PaymentCurrency = AMD)), Self::ANG => Ok(dirval!(PaymentCurrency = ANG)), Self::AOA => Ok(dirval!(PaymentCurrency = AOA)), Self::ARS => Ok(dirval!(PaymentCurrency = ARS)), Self::AUD => Ok(dirval!(PaymentCurrency = AUD)), Self::AWG => Ok(dirval!(PaymentCurrency = AWG)), Self::AZN => Ok(dirval!(PaymentCurrency = AZN)), Self::BAM => Ok(dirval!(PaymentCurrency = BAM)), Self::BBD => Ok(dirval!(PaymentCurrency = BBD)), Self::BDT => Ok(dirval!(PaymentCurrency = BDT)), Self::BGN => Ok(dirval!(PaymentCurrency = BGN)), Self::BHD => Ok(dirval!(PaymentCurrency = BHD)), Self::BIF => Ok(dirval!(PaymentCurrency = BIF)), Self::BMD => Ok(dirval!(PaymentCurrency = BMD)), Self::BND => Ok(dirval!(PaymentCurrency = BND)), Self::BOB => Ok(dirval!(PaymentCurrency = BOB)), Self::BRL => Ok(dirval!(PaymentCurrency = BRL)), Self::BSD => Ok(dirval!(PaymentCurrency = BSD)), Self::BTN => Ok(dirval!(PaymentCurrency = BTN)), Self::BWP => Ok(dirval!(PaymentCurrency = BWP)), Self::BYN => Ok(dirval!(PaymentCurrency = BYN)), Self::BZD => Ok(dirval!(PaymentCurrency = BZD)), Self::CAD => Ok(dirval!(PaymentCurrency = CAD)), Self::CDF => Ok(dirval!(PaymentCurrency = CDF)), Self::CHF => Ok(dirval!(PaymentCurrency = CHF)), Self::CLF => Ok(dirval!(PaymentCurrency = CLF)), Self::CLP => Ok(dirval!(PaymentCurrency = CLP)), Self::CNY => Ok(dirval!(PaymentCurrency = CNY)), Self::COP => Ok(dirval!(PaymentCurrency = COP)), Self::CRC => Ok(dirval!(PaymentCurrency = CRC)), Self::CUC => Ok(dirval!(PaymentCurrency = CUC)), Self::CUP => Ok(dirval!(PaymentCurrency = CUP)), Self::CVE => Ok(dirval!(PaymentCurrency = CVE)), Self::CZK => Ok(dirval!(PaymentCurrency = CZK)), Self::DJF => Ok(dirval!(PaymentCurrency = DJF)), Self::DKK => Ok(dirval!(PaymentCurrency = DKK)), Self::DOP => Ok(dirval!(PaymentCurrency = DOP)), Self::DZD => Ok(dirval!(PaymentCurrency = DZD)), Self::EGP => Ok(dirval!(PaymentCurrency = EGP)), Self::ERN => Ok(dirval!(PaymentCurrency = ERN)), Self::ETB => Ok(dirval!(PaymentCurrency = ETB)), Self::EUR => Ok(dirval!(PaymentCurrency = EUR)), Self::FJD => Ok(dirval!(PaymentCurrency = FJD)), Self::FKP => Ok(dirval!(PaymentCurrency = FKP)), Self::GBP => Ok(dirval!(PaymentCurrency = GBP)), Self::GEL => Ok(dirval!(PaymentCurrency = GEL)), Self::GHS => Ok(dirval!(PaymentCurrency = GHS)), Self::GIP => Ok(dirval!(PaymentCurrency = GIP)), Self::GMD => Ok(dirval!(PaymentCurrency = GMD)), Self::GNF => Ok(dirval!(PaymentCurrency = GNF)), Self::GTQ => Ok(dirval!(PaymentCurrency = GTQ)), Self::GYD => Ok(dirval!(PaymentCurrency = GYD)), Self::HKD => Ok(dirval!(PaymentCurrency = HKD)), Self::HNL => Ok(dirval!(PaymentCurrency = HNL)), Self::HRK => Ok(dirval!(PaymentCurrency = HRK)), Self::HTG => Ok(dirval!(PaymentCurrency = HTG)), Self::HUF => Ok(dirval!(PaymentCurrency = HUF)), Self::IDR => Ok(dirval!(PaymentCurrency = IDR)), Self::ILS => Ok(dirval!(PaymentCurrency = ILS)), Self::INR => Ok(dirval!(PaymentCurrency = INR)), Self::IQD => Ok(dirval!(PaymentCurrency = IQD)), Self::IRR => Ok(dirval!(PaymentCurrency = IRR)), Self::ISK => Ok(dirval!(PaymentCurrency = ISK)), Self::JMD => Ok(dirval!(PaymentCurrency = JMD)), Self::JOD => Ok(dirval!(PaymentCurrency = JOD)), Self::JPY => Ok(dirval!(PaymentCurrency = JPY)), Self::KES => Ok(dirval!(PaymentCurrency = KES)), Self::KGS => Ok(dirval!(PaymentCurrency = KGS)), Self::KHR => Ok(dirval!(PaymentCurrency = KHR)), Self::KMF => Ok(dirval!(PaymentCurrency = KMF)), Self::KPW => Ok(dirval!(PaymentCurrency = KPW)), Self::KRW => Ok(dirval!(PaymentCurrency = KRW)), Self::KWD => Ok(dirval!(PaymentCurrency = KWD)), Self::KYD => Ok(dirval!(PaymentCurrency = KYD)), Self::KZT => Ok(dirval!(PaymentCurrency = KZT)), Self::LAK => Ok(dirval!(PaymentCurrency = LAK)), Self::LBP => Ok(dirval!(PaymentCurrency = LBP)), Self::LKR => Ok(dirval!(PaymentCurrency = LKR)), Self::LRD => Ok(dirval!(PaymentCurrency = LRD)), Self::LSL => Ok(dirval!(PaymentCurrency = LSL)), Self::LYD => Ok(dirval!(PaymentCurrency = LYD)), Self::MAD => Ok(dirval!(PaymentCurrency = MAD)), Self::MDL => Ok(dirval!(PaymentCurrency = MDL)), Self::MGA => Ok(dirval!(PaymentCurrency = MGA)), Self::MKD => Ok(dirval!(PaymentCurrency = MKD)), Self::MMK => Ok(dirval!(PaymentCurrency = MMK)), Self::MNT => Ok(dirval!(PaymentCurrency = MNT)), Self::MOP => Ok(dirval!(PaymentCurrency = MOP)), Self::MRU => Ok(dirval!(PaymentCurrency = MRU)), Self::MUR => Ok(dirval!(PaymentCurrency = MUR)), Self::MVR => Ok(dirval!(PaymentCurrency = MVR)), Self::MWK => Ok(dirval!(PaymentCurrency = MWK)), Self::MXN => Ok(dirval!(PaymentCurrency = MXN)), Self::MYR => Ok(dirval!(PaymentCurrency = MYR)), Self::MZN => Ok(dirval!(PaymentCurrency = MZN)), Self::NAD => Ok(dirval!(PaymentCurrency = NAD)), Self::NGN => Ok(dirval!(PaymentCurrency = NGN)), Self::NIO => Ok(dirval!(PaymentCurrency = NIO)), Self::NOK => Ok(dirval!(PaymentCurrency = NOK)), Self::NPR => Ok(dirval!(PaymentCurrency = NPR)), Self::NZD => Ok(dirval!(PaymentCurrency = NZD)), Self::OMR => Ok(dirval!(PaymentCurrency = OMR)), Self::PAB => Ok(dirval!(PaymentCurrency = PAB)), Self::PEN => Ok(dirval!(PaymentCurrency = PEN)), Self::PGK => Ok(dirval!(PaymentCurrency = PGK)), Self::PHP => Ok(dirval!(PaymentCurrency = PHP)), Self::PKR => Ok(dirval!(PaymentCurrency = PKR)), Self::PLN => Ok(dirval!(PaymentCurrency = PLN)), Self::PYG => Ok(dirval!(PaymentCurrency = PYG)), Self::QAR => Ok(dirval!(PaymentCurrency = QAR)), Self::RON => Ok(dirval!(PaymentCurrency = RON)), Self::RSD => Ok(dirval!(PaymentCurrency = RSD)), Self::RUB => Ok(dirval!(PaymentCurrency = RUB)), Self::RWF => Ok(dirval!(PaymentCurrency = RWF)), Self::SAR => Ok(dirval!(PaymentCurrency = SAR)), Self::SBD => Ok(dirval!(PaymentCurrency = SBD)), Self::SCR => Ok(dirval!(PaymentCurrency = SCR)), Self::SDG => Ok(dirval!(PaymentCurrency = SDG)), Self::SEK => Ok(dirval!(PaymentCurrency = SEK)), Self::SGD => Ok(dirval!(PaymentCurrency = SGD)), Self::SHP => Ok(dirval!(PaymentCurrency = SHP)), Self::SLE => Ok(dirval!(PaymentCurrency = SLE)), Self::SLL => Ok(dirval!(PaymentCurrency = SLL)), Self::SOS => Ok(dirval!(PaymentCurrency = SOS)), Self::SRD => Ok(dirval!(PaymentCurrency = SRD)), Self::SSP => Ok(dirval!(PaymentCurrency = SSP)), Self::STD => Ok(dirval!(PaymentCurrency = STD)), Self::STN => Ok(dirval!(PaymentCurrency = STN)), Self::SVC => Ok(dirval!(PaymentCurrency = SVC)), Self::SYP => Ok(dirval!(PaymentCurrency = SYP)), Self::SZL => Ok(dirval!(PaymentCurrency = SZL)), Self::THB => Ok(dirval!(PaymentCurrency = THB)), Self::TJS => Ok(dirval!(PaymentCurrency = TJS)), Self::TMT => Ok(dirval!(PaymentCurrency = TMT)), Self::TND => Ok(dirval!(PaymentCurrency = TND)), Self::TOP => Ok(dirval!(PaymentCurrency = TOP)), Self::TRY => Ok(dirval!(PaymentCurrency = TRY)), Self::TTD => Ok(dirval!(PaymentCurrency = TTD)), Self::TWD => Ok(dirval!(PaymentCurrency = TWD)), Self::TZS => Ok(dirval!(PaymentCurrency = TZS)), Self::UAH => Ok(dirval!(PaymentCurrency = UAH)), Self::UGX => Ok(dirval!(PaymentCurrency = UGX)), Self::USD => Ok(dirval!(PaymentCurrency = USD)), Self::UYU => Ok(dirval!(PaymentCurrency = UYU)), Self::UZS => Ok(dirval!(PaymentCurrency = UZS)), Self::VES => Ok(dirval!(PaymentCurrency = VES)), Self::VND => Ok(dirval!(PaymentCurrency = VND)), Self::VUV => Ok(dirval!(PaymentCurrency = VUV)), Self::WST => Ok(dirval!(PaymentCurrency = WST)), Self::XAF => Ok(dirval!(PaymentCurrency = XAF)), Self::XCD => Ok(dirval!(PaymentCurrency = XCD)), Self::XOF => Ok(dirval!(PaymentCurrency = XOF)), Self::XPF => Ok(dirval!(PaymentCurrency = XPF)), Self::YER => Ok(dirval!(PaymentCurrency = YER)), Self::ZAR => Ok(dirval!(PaymentCurrency = ZAR)), Self::ZMW => Ok(dirval!(PaymentCurrency = ZMW)), Self::ZWL => Ok(dirval!(PaymentCurrency = ZWL)), } } } pub fn get_dir_country_dir_value(c: api_enums::Country) -> dir::enums::Country { match c { api_enums::Country::Afghanistan => dir::enums::Country::Afghanistan, api_enums::Country::AlandIslands => dir::enums::Country::AlandIslands, api_enums::Country::Albania => dir::enums::Country::Albania, api_enums::Country::Algeria => dir::enums::Country::Algeria, api_enums::Country::AmericanSamoa => dir::enums::Country::AmericanSamoa, api_enums::Country::Andorra => dir::enums::Country::Andorra, api_enums::Country::Angola => dir::enums::Country::Angola, api_enums::Country::Anguilla => dir::enums::Country::Anguilla, api_enums::Country::Antarctica => dir::enums::Country::Antarctica, api_enums::Country::AntiguaAndBarbuda => dir::enums::Country::AntiguaAndBarbuda, api_enums::Country::Argentina => dir::enums::Country::Argentina, api_enums::Country::Armenia => dir::enums::Country::Armenia, api_enums::Country::Aruba => dir::enums::Country::Aruba, api_enums::Country::Australia => dir::enums::Country::Australia, api_enums::Country::Austria => dir::enums::Country::Austria, api_enums::Country::Azerbaijan => dir::enums::Country::Azerbaijan, api_enums::Country::Bahamas => dir::enums::Country::Bahamas, api_enums::Country::Bahrain => dir::enums::Country::Bahrain, api_enums::Country::Bangladesh => dir::enums::Country::Bangladesh, api_enums::Country::Barbados => dir::enums::Country::Barbados, api_enums::Country::Belarus => dir::enums::Country::Belarus, api_enums::Country::Belgium => dir::enums::Country::Belgium, api_enums::Country::Belize => dir::enums::Country::Belize, api_enums::Country::Benin => dir::enums::Country::Benin, api_enums::Country::Bermuda => dir::enums::Country::Bermuda, api_enums::Country::Bhutan => dir::enums::Country::Bhutan, api_enums::Country::BoliviaPlurinationalState => { dir::enums::Country::BoliviaPlurinationalState } api_enums::Country::BonaireSintEustatiusAndSaba => { dir::enums::Country::BonaireSintEustatiusAndSaba } api_enums::Country::BosniaAndHerzegovina => dir::enums::Country::BosniaAndHerzegovina, api_enums::Country::Botswana => dir::enums::Country::Botswana, api_enums::Country::BouvetIsland => dir::enums::Country::BouvetIsland, api_enums::Country::Brazil => dir::enums::Country::Brazil, api_enums::Country::BritishIndianOceanTerritory => { dir::enums::Country::BritishIndianOceanTerritory } api_enums::Country::BruneiDarussalam => dir::enums::Country::BruneiDarussalam, api_enums::Country::Bulgaria => dir::enums::Country::Bulgaria, api_enums::Country::BurkinaFaso => dir::enums::Country::BurkinaFaso, api_enums::Country::Burundi => dir::enums::Country::Burundi, api_enums::Country::CaboVerde => dir::enums::Country::CaboVerde, api_enums::Country::Cambodia => dir::enums::Country::Cambodia, api_enums::Country::Cameroon => dir::enums::Country::Cameroon, api_enums::Country::Canada => dir::enums::Country::Canada, api_enums::Country::CaymanIslands => dir::enums::Country::CaymanIslands, api_enums::Country::CentralAfricanRepublic => dir::enums::Country::CentralAfricanRepublic, api_enums::Country::Chad => dir::enums::Country::Chad, api_enums::Country::Chile => dir::enums::Country::Chile, api_enums::Country::China => dir::enums::Country::China, api_enums::Country::ChristmasIsland => dir::enums::Country::ChristmasIsland, api_enums::Country::CocosKeelingIslands => dir::enums::Country::CocosKeelingIslands, api_enums::Country::Colombia => dir::enums::Country::Colombia, api_enums::Country::Comoros => dir::enums::Country::Comoros, api_enums::Country::Congo => dir::enums::Country::Congo, api_enums::Country::CongoDemocraticRepublic => dir::enums::Country::CongoDemocraticRepublic, api_enums::Country::CookIslands => dir::enums::Country::CookIslands, api_enums::Country::CostaRica => dir::enums::Country::CostaRica, api_enums::Country::CotedIvoire => dir::enums::Country::CotedIvoire, api_enums::Country::Croatia => dir::enums::Country::Croatia, api_enums::Country::Cuba => dir::enums::Country::Cuba, api_enums::Country::Curacao => dir::enums::Country::Curacao, api_enums::Country::Cyprus => dir::enums::Country::Cyprus, api_enums::Country::Czechia => dir::enums::Country::Czechia, api_enums::Country::Denmark => dir::enums::Country::Denmark, api_enums::Country::Djibouti => dir::enums::Country::Djibouti, api_enums::Country::Dominica => dir::enums::Country::Dominica, api_enums::Country::DominicanRepublic => dir::enums::Country::DominicanRepublic, api_enums::Country::Ecuador => dir::enums::Country::Ecuador, api_enums::Country::Egypt => dir::enums::Country::Egypt, api_enums::Country::ElSalvador => dir::enums::Country::ElSalvador, api_enums::Country::EquatorialGuinea => dir::enums::Country::EquatorialGuinea, api_enums::Country::Eritrea => dir::enums::Country::Eritrea, api_enums::Country::Estonia => dir::enums::Country::Estonia, api_enums::Country::Ethiopia => dir::enums::Country::Ethiopia, api_enums::Country::FalklandIslandsMalvinas => dir::enums::Country::FalklandIslandsMalvinas, api_enums::Country::FaroeIslands => dir::enums::Country::FaroeIslands, api_enums::Country::Fiji => dir::enums::Country::Fiji, api_enums::Country::Finland => dir::enums::Country::Finland, api_enums::Country::France => dir::enums::Country::France, api_enums::Country::FrenchGuiana => dir::enums::Country::FrenchGuiana, api_enums::Country::FrenchPolynesia => dir::enums::Country::FrenchPolynesia, api_enums::Country::FrenchSouthernTerritories => { dir::enums::Country::FrenchSouthernTerritories } api_enums::Country::Gabon => dir::enums::Country::Gabon, api_enums::Country::Gambia => dir::enums::Country::Gambia, api_enums::Country::Georgia => dir::enums::Country::Georgia, api_enums::Country::Germany => dir::enums::Country::Germany, api_enums::Country::Ghana => dir::enums::Country::Ghana, api_enums::Country::Gibraltar => dir::enums::Country::Gibraltar, api_enums::Country::Greece => dir::enums::Country::Greece, api_enums::Country::Greenland => dir::enums::Country::Greenland, api_enums::Country::Grenada => dir::enums::Country::Grenada, api_enums::Country::Guadeloupe => dir::enums::Country::Guadeloupe, api_enums::Country::Guam => dir::enums::Country::Guam, api_enums::Country::Guatemala => dir::enums::Country::Guatemala, api_enums::Country::Guernsey => dir::enums::Country::Guernsey, api_enums::Country::Guinea => dir::enums::Country::Guinea, api_enums::Country::GuineaBissau => dir::enums::Country::GuineaBissau, api_enums::Country::Guyana => dir::enums::Country::Guyana, api_enums::Country::Haiti => dir::enums::Country::Haiti, api_enums::Country::HeardIslandAndMcDonaldIslands => { dir::enums::Country::HeardIslandAndMcDonaldIslands } api_enums::Country::HolySee => dir::enums::Country::HolySee, api_enums::Country::Honduras => dir::enums::Country::Honduras, api_enums::Country::HongKong => dir::enums::Country::HongKong, api_enums::Country::Hungary => dir::enums::Country::Hungary, api_enums::Country::Iceland => dir::enums::Country::Iceland, api_enums::Country::India => dir::enums::Country::India, api_enums::Country::Indonesia => dir::enums::Country::Indonesia, api_enums::Country::IranIslamicRepublic => dir::enums::Country::IranIslamicRepublic, api_enums::Country::Iraq => dir::enums::Country::Iraq, api_enums::Country::Ireland => dir::enums::Country::Ireland, api_enums::Country::IsleOfMan => dir::enums::Country::IsleOfMan, api_enums::Country::Israel => dir::enums::Country::Israel, api_enums::Country::Italy => dir::enums::Country::Italy, api_enums::Country::Jamaica => dir::enums::Country::Jamaica, api_enums::Country::Japan => dir::enums::Country::Japan, api_enums::Country::Jersey => dir::enums::Country::Jersey, api_enums::Country::Jordan => dir::enums::Country::Jordan, api_enums::Country::Kazakhstan => dir::enums::Country::Kazakhstan, api_enums::Country::Kenya => dir::enums::Country::Kenya, api_enums::Country::Kiribati => dir::enums::Country::Kiribati, api_enums::Country::KoreaDemocraticPeoplesRepublic => { dir::enums::Country::KoreaDemocraticPeoplesRepublic } api_enums::Country::KoreaRepublic => dir::enums::Country::KoreaRepublic, api_enums::Country::Kuwait => dir::enums::Country::Kuwait, api_enums::Country::Kyrgyzstan => dir::enums::Country::Kyrgyzstan, api_enums::Country::LaoPeoplesDemocraticRepublic => { dir::enums::Country::LaoPeoplesDemocraticRepublic } api_enums::Country::Latvia => dir::enums::Country::Latvia, api_enums::Country::Lebanon => dir::enums::Country::Lebanon, api_enums::Country::Lesotho => dir::enums::Country::Lesotho, api_enums::Country::Liberia => dir::enums::Country::Liberia, api_enums::Country::Libya => dir::enums::Country::Libya, api_enums::Country::Liechtenstein => dir::enums::Country::Liechtenstein, api_enums::Country::Lithuania => dir::enums::Country::Lithuania, api_enums::Country::Luxembourg => dir::enums::Country::Luxembourg, api_enums::Country::Macao => dir::enums::Country::Macao, api_enums::Country::MacedoniaTheFormerYugoslavRepublic => { dir::enums::Country::MacedoniaTheFormerYugoslavRepublic } api_enums::Country::Madagascar => dir::enums::Country::Madagascar, api_enums::Country::Malawi => dir::enums::Country::Malawi, api_enums::Country::Malaysia => dir::enums::Country::Malaysia, api_enums::Country::Maldives => dir::enums::Country::Maldives, api_enums::Country::Mali => dir::enums::Country::Mali, api_enums::Country::Malta => dir::enums::Country::Malta, api_enums::Country::MarshallIslands => dir::enums::Country::MarshallIslands, api_enums::Country::Martinique => dir::enums::Country::Martinique, api_enums::Country::Mauritania => dir::enums::Country::Mauritania, api_enums::Country::Mauritius => dir::enums::Country::Mauritius, api_enums::Country::Mayotte => dir::enums::Country::Mayotte, api_enums::Country::Mexico => dir::enums::Country::Mexico, api_enums::Country::MicronesiaFederatedStates => { dir::enums::Country::MicronesiaFederatedStates } api_enums::Country::MoldovaRepublic => dir::enums::Country::MoldovaRepublic, api_enums::Country::Monaco => dir::enums::Country::Monaco, api_enums::Country::Mongolia => dir::enums::Country::Mongolia, api_enums::Country::Montenegro => dir::enums::Country::Montenegro, api_enums::Country::Montserrat => dir::enums::Country::Montserrat, api_enums::Country::Morocco => dir::enums::Country::Morocco, api_enums::Country::Mozambique => dir::enums::Country::Mozambique, api_enums::Country::Myanmar => dir::enums::Country::Myanmar, api_enums::Country::Namibia => dir::enums::Country::Namibia, api_enums::Country::Nauru => dir::enums::Country::Nauru, api_enums::Country::Nepal => dir::enums::Country::Nepal, api_enums::Country::Netherlands => dir::enums::Country::Netherlands, api_enums::Country::NewCaledonia => dir::enums::Country::NewCaledonia, api_enums::Country::NewZealand => dir::enums::Country::NewZealand, api_enums::Country::Nicaragua => dir::enums::Country::Nicaragua, api_enums::Country::Niger => dir::enums::Country::Niger, api_enums::Country::Nigeria => dir::enums::Country::Nigeria, api_enums::Country::Niue => dir::enums::Country::Niue, api_enums::Country::NorfolkIsland => dir::enums::Country::NorfolkIsland, api_enums::Country::NorthernMarianaIslands => dir::enums::Country::NorthernMarianaIslands, api_enums::Country::Norway => dir::enums::Country::Norway, api_enums::Country::Oman => dir::enums::Country::Oman, api_enums::Country::Pakistan => dir::enums::Country::Pakistan, api_enums::Country::Palau => dir::enums::Country::Palau, api_enums::Country::PalestineState => dir::enums::Country::PalestineState, api_enums::Country::Panama => dir::enums::Country::Panama, api_enums::Country::PapuaNewGuinea => dir::enums::Country::PapuaNewGuinea, api_enums::Country::Paraguay => dir::enums::Country::Paraguay, api_enums::Country::Peru => dir::enums::Country::Peru, api_enums::Country::Philippines => dir::enums::Country::Philippines, api_enums::Country::Pitcairn => dir::enums::Country::Pitcairn, api_enums::Country::Poland => dir::enums::Country::Poland, api_enums::Country::Portugal => dir::enums::Country::Portugal, api_enums::Country::PuertoRico => dir::enums::Country::PuertoRico, api_enums::Country::Qatar => dir::enums::Country::Qatar, api_enums::Country::Reunion => dir::enums::Country::Reunion, api_enums::Country::Romania => dir::enums::Country::Romania, api_enums::Country::RussianFederation => dir::enums::Country::RussianFederation, api_enums::Country::Rwanda => dir::enums::Country::Rwanda, api_enums::Country::SaintBarthelemy => dir::enums::Country::SaintBarthelemy, api_enums::Country::SaintHelenaAscensionAndTristandaCunha => { dir::enums::Country::SaintHelenaAscensionAndTristandaCunha } api_enums::Country::SaintKittsAndNevis => dir::enums::Country::SaintKittsAndNevis, api_enums::Country::SaintLucia => dir::enums::Country::SaintLucia, api_enums::Country::SaintMartinFrenchpart => dir::enums::Country::SaintMartinFrenchpart, api_enums::Country::SaintPierreAndMiquelon => dir::enums::Country::SaintPierreAndMiquelon, api_enums::Country::SaintVincentAndTheGrenadines => { dir::enums::Country::SaintVincentAndTheGrenadines } api_enums::Country::Samoa => dir::enums::Country::Samoa, api_enums::Country::SanMarino => dir::enums::Country::SanMarino, api_enums::Country::SaoTomeAndPrincipe => dir::enums::Country::SaoTomeAndPrincipe, api_enums::Country::SaudiArabia => dir::enums::Country::SaudiArabia, api_enums::Country::Senegal => dir::enums::Country::Senegal, api_enums::Country::Serbia => dir::enums::Country::Serbia, api_enums::Country::Seychelles => dir::enums::Country::Seychelles, api_enums::Country::SierraLeone => dir::enums::Country::SierraLeone, api_enums::Country::Singapore => dir::enums::Country::Singapore, api_enums::Country::SintMaartenDutchpart => dir::enums::Country::SintMaartenDutchpart, api_enums::Country::Slovakia => dir::enums::Country::Slovakia, api_enums::Country::Slovenia => dir::enums::Country::Slovenia, api_enums::Country::SolomonIslands => dir::enums::Country::SolomonIslands, api_enums::Country::Somalia => dir::enums::Country::Somalia, api_enums::Country::SouthAfrica => dir::enums::Country::SouthAfrica, api_enums::Country::SouthGeorgiaAndTheSouthSandwichIslands => { dir::enums::Country::SouthGeorgiaAndTheSouthSandwichIslands } api_enums::Country::SouthSudan => dir::enums::Country::SouthSudan, api_enums::Country::Spain => dir::enums::Country::Spain, api_enums::Country::SriLanka => dir::enums::Country::SriLanka, api_enums::Country::Sudan => dir::enums::Country::Sudan, api_enums::Country::Suriname => dir::enums::Country::Suriname, api_enums::Country::SvalbardAndJanMayen => dir::enums::Country::SvalbardAndJanMayen, api_enums::Country::Swaziland => dir::enums::Country::Swaziland, api_enums::Country::Sweden => dir::enums::Country::Sweden, api_enums::Country::Switzerland => dir::enums::Country::Switzerland, api_enums::Country::SyrianArabRepublic => dir::enums::Country::SyrianArabRepublic, api_enums::Country::TaiwanProvinceOfChina => dir::enums::Country::TaiwanProvinceOfChina, api_enums::Country::Tajikistan => dir::enums::Country::Tajikistan, api_enums::Country::TanzaniaUnitedRepublic => dir::enums::Country::TanzaniaUnitedRepublic, api_enums::Country::Thailand => dir::enums::Country::Thailand, api_enums::Country::TimorLeste => dir::enums::Country::TimorLeste, api_enums::Country::Togo => dir::enums::Country::Togo, api_enums::Country::Tokelau => dir::enums::Country::Tokelau, api_enums::Country::Tonga => dir::enums::Country::Tonga, api_enums::Country::TrinidadAndTobago => dir::enums::Country::TrinidadAndTobago, api_enums::Country::Tunisia => dir::enums::Country::Tunisia, api_enums::Country::Turkey => dir::enums::Country::Turkey, api_enums::Country::Turkmenistan => dir::enums::Country::Turkmenistan, api_enums::Country::TurksAndCaicosIslands => dir::enums::Country::TurksAndCaicosIslands, api_enums::Country::Tuvalu => dir::enums::Country::Tuvalu, api_enums::Country::Uganda => dir::enums::Country::Uganda, api_enums::Country::Ukraine => dir::enums::Country::Ukraine, api_enums::Country::UnitedArabEmirates => dir::enums::Country::UnitedArabEmirates, api_enums::Country::UnitedKingdomOfGreatBritainAndNorthernIreland => { dir::enums::Country::UnitedKingdomOfGreatBritainAndNorthernIreland } api_enums::Country::UnitedStatesOfAmerica => dir::enums::Country::UnitedStatesOfAmerica, api_enums::Country::UnitedStatesMinorOutlyingIslands => { dir::enums::Country::UnitedStatesMinorOutlyingIslands } api_enums::Country::Uruguay => dir::enums::Country::Uruguay, api_enums::Country::Uzbekistan => dir::enums::Country::Uzbekistan, api_enums::Country::Vanuatu => dir::enums::Country::Vanuatu, api_enums::Country::VenezuelaBolivarianRepublic => { dir::enums::Country::VenezuelaBolivarianRepublic } api_enums::Country::Vietnam => dir::enums::Country::Vietnam, api_enums::Country::VirginIslandsBritish => dir::enums::Country::VirginIslandsBritish, api_enums::Country::VirginIslandsUS => dir::enums::Country::VirginIslandsUS, api_enums::Country::WallisAndFutuna => dir::enums::Country::WallisAndFutuna, api_enums::Country::WesternSahara => dir::enums::Country::WesternSahara, api_enums::Country::Yemen => dir::enums::Country::Yemen, api_enums::Country::Zambia => dir::enums::Country::Zambia, api_enums::Country::Zimbabwe => dir::enums::Country::Zimbabwe, } } pub fn business_country_to_dir_value(c: api_enums::Country) -> dir::DirValue { dir::DirValue::BusinessCountry(get_dir_country_dir_value(c)) } pub fn billing_country_to_dir_value(c: api_enums::Country) -> dir::DirValue { dir::DirValue::BillingCountry(get_dir_country_dir_value(c)) }
crates/kgraph_utils/src/transformers.rs
kgraph_utils::src::transformers
12,783
true
// File: crates/kgraph_utils/src/lib.rs // Module: kgraph_utils::src::lib pub mod error; pub mod mca; pub mod transformers; pub mod types;
crates/kgraph_utils/src/lib.rs
kgraph_utils::src::lib
39
true
// File: crates/kgraph_utils/src/mca.rs // Module: kgraph_utils::src::mca #[cfg(feature = "v1")] use std::str::FromStr; #[cfg(feature = "v1")] use api_models::payment_methods::RequestPaymentMethodTypes; use api_models::{admin as admin_api, enums as api_enums, refunds::MinorUnit}; use euclid::{ dirval, frontend::{ast, dir}, types::{NumValue, NumValueRefinement}, }; use hyperswitch_constraint_graph as cgraph; use strum::IntoEnumIterator; use crate::{error::KgraphError, transformers::IntoDirValue, types as kgraph_types}; pub const DOMAIN_IDENTIFIER: &str = "payment_methods_enabled_for_merchantconnectoraccount"; // #[cfg(feature = "v1")] fn get_dir_value_payment_method( from: api_enums::PaymentMethodType, ) -> Result<dir::DirValue, KgraphError> { match from { api_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)), api_enums::PaymentMethodType::Skrill => Ok(dirval!(WalletType = Skrill)), api_enums::PaymentMethodType::Paysera => Ok(dirval!(WalletType = Paysera)), api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)), api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)), #[cfg(feature = "v2")] api_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)), api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)), api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)), api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)), api_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)), api_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)), api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)), api_enums::PaymentMethodType::Flexiti => Ok(dirval!(PayLaterType = Flexiti)), api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)), api_enums::PaymentMethodType::AfterpayClearpay => { Ok(dirval!(PayLaterType = AfterpayClearpay)) } api_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)), api_enums::PaymentMethodType::Bluecode => Ok(dirval!(WalletType = Bluecode)), api_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)), api_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)), api_enums::PaymentMethodType::CryptoCurrency => Ok(dirval!(CryptoType = CryptoCurrency)), api_enums::PaymentMethodType::Ach => Ok(dirval!(BankDebitType = Ach)), api_enums::PaymentMethodType::Bacs => Ok(dirval!(BankDebitType = Bacs)), api_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)), api_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)), api_enums::PaymentMethodType::SepaGuarenteedDebit => { Ok(dirval!(BankDebitType = SepaGuarenteedDebit)) } api_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)), api_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)), api_enums::PaymentMethodType::BancontactCard => { Ok(dirval!(BankRedirectType = BancontactCard)) } api_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)), api_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)), api_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)), api_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)), api_enums::PaymentMethodType::Multibanco => Ok(dirval!(BankTransferType = Multibanco)), api_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)), api_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)), api_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)), api_enums::PaymentMethodType::OnlineBankingCzechRepublic => { Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic)) } api_enums::PaymentMethodType::OnlineBankingFinland => { Ok(dirval!(BankRedirectType = OnlineBankingFinland)) } api_enums::PaymentMethodType::OnlineBankingPoland => { Ok(dirval!(BankRedirectType = OnlineBankingPoland)) } api_enums::PaymentMethodType::OnlineBankingSlovakia => { Ok(dirval!(BankRedirectType = OnlineBankingSlovakia)) } api_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)), api_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)), api_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)), api_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)), api_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)), api_enums::PaymentMethodType::Przelewy24 => Ok(dirval!(BankRedirectType = Przelewy24)), api_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)), api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)), api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)), api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)), api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)), api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)), api_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)), api_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)), api_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)), api_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)), api_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)), api_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)), api_enums::PaymentMethodType::OnlineBankingFpx => { Ok(dirval!(BankRedirectType = OnlineBankingFpx)) } api_enums::PaymentMethodType::OnlineBankingThailand => { Ok(dirval!(BankRedirectType = OnlineBankingThailand)) } api_enums::PaymentMethodType::LocalBankRedirect => { Ok(dirval!(BankRedirectType = LocalBankRedirect)) } api_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)), api_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)), api_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)), api_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)), api_enums::PaymentMethodType::PagoEfectivo => Ok(dirval!(VoucherType = PagoEfectivo)), api_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)), api_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)), api_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)), api_enums::PaymentMethodType::BcaBankTransfer => { Ok(dirval!(BankTransferType = BcaBankTransfer)) } api_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)), api_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)), api_enums::PaymentMethodType::Breadpay => Ok(dirval!(PayLaterType = Breadpay)), api_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)), api_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)), api_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)), api_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)), api_enums::PaymentMethodType::LocalBankTransfer => { Ok(dirval!(BankTransferType = LocalBankTransfer)) } api_enums::PaymentMethodType::InstantBankTransfer => { Ok(dirval!(BankTransferType = InstantBankTransfer)) } api_enums::PaymentMethodType::InstantBankTransferFinland => { Ok(dirval!(BankTransferType = InstantBankTransferFinland)) } api_enums::PaymentMethodType::InstantBankTransferPoland => { Ok(dirval!(BankTransferType = InstantBankTransferPoland)) } api_enums::PaymentMethodType::SepaBankTransfer => { Ok(dirval!(BankTransferType = SepaBankTransfer)) } api_enums::PaymentMethodType::PermataBankTransfer => { Ok(dirval!(BankTransferType = PermataBankTransfer)) } api_enums::PaymentMethodType::IndonesianBankTransfer => { Ok(dirval!(BankTransferType = IndonesianBankTransfer)) } api_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)), api_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)), api_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)), api_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)), api_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)), api_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)), api_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)), api_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)), api_enums::PaymentMethodType::BhnCardNetwork => Ok(dirval!(GiftCardType = BhnCardNetwork)), api_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)), api_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)), api_enums::PaymentMethodType::OpenBankingUk => { Ok(dirval!(BankRedirectType = OpenBankingUk)) } api_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)), api_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)), api_enums::PaymentMethodType::CardRedirect => Ok(dirval!(CardRedirectType = CardRedirect)), api_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)), api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)), api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)), api_enums::PaymentMethodType::UpiQr => Ok(dirval!(UpiType = UpiQr)), api_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)), api_enums::PaymentMethodType::Fps => Ok(dirval!(RealTimePaymentType = Fps)), api_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)), api_enums::PaymentMethodType::PromptPay => Ok(dirval!(RealTimePaymentType = PromptPay)), api_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)), api_enums::PaymentMethodType::OpenBankingPIS => { Ok(dirval!(OpenBankingType = OpenBankingPIS)) } api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)), api_enums::PaymentMethodType::DirectCarrierBilling => { Ok(dirval!(MobilePaymentType = DirectCarrierBilling)) } api_enums::PaymentMethodType::RevolutPay => Ok(dirval!(WalletType = RevolutPay)), } } #[cfg(feature = "v2")] fn compile_request_pm_types( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, pm_types: common_types::payment_methods::RequestPaymentMethodTypes, pm: api_enums::PaymentMethod, ) -> Result<cgraph::NodeId, KgraphError> { let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); let pmt_info = "PaymentMethodType"; let pmt_id = builder.make_value_node( (pm_types.payment_method_subtype, pm) .into_dir_value() .map(Into::into)?, Some(pmt_info), None::<()>, ); agg_nodes.push(( pmt_id, cgraph::Relation::Positive, match pm_types.payment_method_subtype { api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => { cgraph::Strength::Weak } _ => cgraph::Strength::Strong, }, )); if let Some(card_networks) = pm_types.card_networks { if !card_networks.is_empty() { let dir_vals: Vec<dir::DirValue> = card_networks .into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>()?; let card_network_info = "Card Networks"; let card_network_id = builder .make_in_aggregator(dir_vals, Some(card_network_info), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( card_network_id, cgraph::Relation::Positive, cgraph::Strength::Weak, )); } } let currencies_data = pm_types .accepted_currencies .and_then(|accepted_currencies| match accepted_currencies { common_types::payment_methods::AcceptedCurrencies::EnableOnly(curr) if !curr.is_empty() => { Some(( curr.into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>() .ok()?, cgraph::Relation::Positive, )) } common_types::payment_methods::AcceptedCurrencies::DisableOnly(curr) if !curr.is_empty() => { Some(( curr.into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>() .ok()?, cgraph::Relation::Negative, )) } _ => None, }); if let Some((currencies, relation)) = currencies_data { let accepted_currencies_info = "Accepted Currencies"; let accepted_currencies_id = builder .make_in_aggregator(currencies, Some(accepted_currencies_info), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push((accepted_currencies_id, relation, cgraph::Strength::Strong)); } let mut amount_nodes = Vec::with_capacity(2); if let Some(min_amt) = pm_types.minimum_amount { let num_val = NumValue { number: min_amt, refinement: Some(NumValueRefinement::GreaterThanEqual), }; let min_amt_info = "Minimum Amount"; let min_amt_id = builder.make_value_node( dir::DirValue::PaymentAmount(num_val).into(), Some(min_amt_info), None::<()>, ); amount_nodes.push(min_amt_id); } if let Some(max_amt) = pm_types.maximum_amount { let num_val = NumValue { number: max_amt, refinement: Some(NumValueRefinement::LessThanEqual), }; let max_amt_info = "Maximum Amount"; let max_amt_id = builder.make_value_node( dir::DirValue::PaymentAmount(num_val).into(), Some(max_amt_info), None::<()>, ); amount_nodes.push(max_amt_id); } if !amount_nodes.is_empty() { let zero_num_val = NumValue { number: MinorUnit::zero(), refinement: None, }; let zero_amt_id = builder.make_value_node( dir::DirValue::PaymentAmount(zero_num_val).into(), Some("zero_amount"), None::<()>, ); let or_node_neighbor_id = if amount_nodes.len() == 1 { amount_nodes .first() .copied() .ok_or(KgraphError::IndexingError)? } else { let nodes = amount_nodes .iter() .copied() .map(|node_id| { ( node_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ) }) .collect::<Vec<_>>(); builder .make_all_aggregator( &nodes, Some("amount_constraint_aggregator"), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)? }; let any_aggregator = builder .make_any_aggregator( &[ ( zero_amt_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ( or_node_neighbor_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ], Some("zero_plus_limits_amount_aggregator"), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( any_aggregator, cgraph::Relation::Positive, cgraph::Strength::Strong, )); } let pmt_all_aggregator_info = "All Aggregator for PaymentMethodType"; builder .make_all_aggregator(&agg_nodes, Some(pmt_all_aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError) } #[cfg(feature = "v1")] fn compile_request_pm_types( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, pm_types: RequestPaymentMethodTypes, pm: api_enums::PaymentMethod, ) -> Result<cgraph::NodeId, KgraphError> { let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); let pmt_info = "PaymentMethodType"; let pmt_id = builder.make_value_node( (pm_types.payment_method_type, pm) .into_dir_value() .map(Into::into)?, Some(pmt_info), None::<()>, ); agg_nodes.push(( pmt_id, cgraph::Relation::Positive, match pm_types.payment_method_type { api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => { cgraph::Strength::Weak } _ => cgraph::Strength::Strong, }, )); if let Some(card_networks) = pm_types.card_networks { if !card_networks.is_empty() { let dir_vals: Vec<dir::DirValue> = card_networks .into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>()?; let card_network_info = "Card Networks"; let card_network_id = builder .make_in_aggregator(dir_vals, Some(card_network_info), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( card_network_id, cgraph::Relation::Positive, cgraph::Strength::Weak, )); } } let currencies_data = pm_types .accepted_currencies .and_then(|accepted_currencies| match accepted_currencies { admin_api::AcceptedCurrencies::EnableOnly(curr) if !curr.is_empty() => Some(( curr.into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>() .ok()?, cgraph::Relation::Positive, )), admin_api::AcceptedCurrencies::DisableOnly(curr) if !curr.is_empty() => Some(( curr.into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<_, _>>() .ok()?, cgraph::Relation::Negative, )), _ => None, }); if let Some((currencies, relation)) = currencies_data { let accepted_currencies_info = "Accepted Currencies"; let accepted_currencies_id = builder .make_in_aggregator(currencies, Some(accepted_currencies_info), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push((accepted_currencies_id, relation, cgraph::Strength::Strong)); } let mut amount_nodes = Vec::with_capacity(2); if let Some(min_amt) = pm_types.minimum_amount { let num_val = NumValue { number: min_amt, refinement: Some(NumValueRefinement::GreaterThanEqual), }; let min_amt_info = "Minimum Amount"; let min_amt_id = builder.make_value_node( dir::DirValue::PaymentAmount(num_val).into(), Some(min_amt_info), None::<()>, ); amount_nodes.push(min_amt_id); } if let Some(max_amt) = pm_types.maximum_amount { let num_val = NumValue { number: max_amt, refinement: Some(NumValueRefinement::LessThanEqual), }; let max_amt_info = "Maximum Amount"; let max_amt_id = builder.make_value_node( dir::DirValue::PaymentAmount(num_val).into(), Some(max_amt_info), None::<()>, ); amount_nodes.push(max_amt_id); } if !amount_nodes.is_empty() { let zero_num_val = NumValue { number: MinorUnit::zero(), refinement: None, }; let zero_amt_id = builder.make_value_node( dir::DirValue::PaymentAmount(zero_num_val).into(), Some("zero_amount"), None::<()>, ); let or_node_neighbor_id = if amount_nodes.len() == 1 { amount_nodes .first() .copied() .ok_or(KgraphError::IndexingError)? } else { let nodes = amount_nodes .iter() .copied() .map(|node_id| { ( node_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ) }) .collect::<Vec<_>>(); builder .make_all_aggregator( &nodes, Some("amount_constraint_aggregator"), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)? }; let any_aggregator = builder .make_any_aggregator( &[ ( zero_amt_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ( or_node_neighbor_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ], Some("zero_plus_limits_amount_aggregator"), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( any_aggregator, cgraph::Relation::Positive, cgraph::Strength::Strong, )); } let pmt_all_aggregator_info = "All Aggregator for PaymentMethodType"; builder .make_all_aggregator(&agg_nodes, Some(pmt_all_aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError) } #[cfg(feature = "v2")] fn compile_payment_method_enabled( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, enabled: common_types::payment_methods::PaymentMethodsEnabled, ) -> Result<Option<cgraph::NodeId>, KgraphError> { let agg_id = if !enabled .payment_method_subtypes .as_ref() .map(|v| v.is_empty()) .unwrap_or(true) { let pm_info = "PaymentMethod"; let pm_id = builder.make_value_node( enabled .payment_method_type .into_dir_value() .map(Into::into)?, Some(pm_info), None::<()>, ); let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); if let Some(pm_types) = enabled.payment_method_subtypes { for pm_type in pm_types { let node_id = compile_request_pm_types(builder, pm_type, enabled.payment_method_type)?; agg_nodes.push(( node_id, cgraph::Relation::Positive, cgraph::Strength::Strong, )); } } let any_aggregator_info = "Any aggregation for PaymentMethodsType"; let pm_type_agg_id = builder .make_any_aggregator(&agg_nodes, Some(any_aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError)?; let all_aggregator_info = "All aggregation for PaymentMethod"; let enabled_pm_agg_id = builder .make_all_aggregator( &[ (pm_id, cgraph::Relation::Positive, cgraph::Strength::Strong), ( pm_type_agg_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ], Some(all_aggregator_info), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)?; Some(enabled_pm_agg_id) } else { None }; Ok(agg_id) } #[cfg(feature = "v1")] fn compile_payment_method_enabled( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, enabled: admin_api::PaymentMethodsEnabled, ) -> Result<Option<cgraph::NodeId>, KgraphError> { let agg_id = if !enabled .payment_method_types .as_ref() .map(|v| v.is_empty()) .unwrap_or(true) { let pm_info = "PaymentMethod"; let pm_id = builder.make_value_node( enabled.payment_method.into_dir_value().map(Into::into)?, Some(pm_info), None::<()>, ); let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); if let Some(pm_types) = enabled.payment_method_types { for pm_type in pm_types { let node_id = compile_request_pm_types(builder, pm_type, enabled.payment_method)?; agg_nodes.push(( node_id, cgraph::Relation::Positive, cgraph::Strength::Strong, )); } } let any_aggregator_info = "Any aggregation for PaymentMethodsType"; let pm_type_agg_id = builder .make_any_aggregator(&agg_nodes, Some(any_aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError)?; let all_aggregator_info = "All aggregation for PaymentMethod"; let enabled_pm_agg_id = builder .make_all_aggregator( &[ (pm_id, cgraph::Relation::Positive, cgraph::Strength::Strong), ( pm_type_agg_id, cgraph::Relation::Positive, cgraph::Strength::Strong, ), ], Some(all_aggregator_info), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)?; Some(enabled_pm_agg_id) } else { None }; Ok(agg_id) } macro_rules! collect_global_variants { ($parent_enum:ident) => { &mut dir::enums::$parent_enum::iter() .map(dir::DirValue::$parent_enum) .collect::<Vec<_>>() }; } // #[cfg(feature = "v1")] fn global_vec_pmt( enabled_pmt: Vec<dir::DirValue>, builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, ) -> Vec<cgraph::NodeId> { let mut global_vector: Vec<dir::DirValue> = Vec::new(); global_vector.append(collect_global_variants!(PayLaterType)); global_vector.append(collect_global_variants!(WalletType)); global_vector.append(collect_global_variants!(BankRedirectType)); global_vector.append(collect_global_variants!(BankDebitType)); global_vector.append(collect_global_variants!(CryptoType)); global_vector.append(collect_global_variants!(RewardType)); global_vector.append(collect_global_variants!(RealTimePaymentType)); global_vector.append(collect_global_variants!(UpiType)); global_vector.append(collect_global_variants!(VoucherType)); global_vector.append(collect_global_variants!(GiftCardType)); global_vector.append(collect_global_variants!(BankTransferType)); global_vector.append(collect_global_variants!(CardRedirectType)); global_vector.append(collect_global_variants!(OpenBankingType)); global_vector.append(collect_global_variants!(MobilePaymentType)); global_vector.push(dir::DirValue::PaymentMethod( dir::enums::PaymentMethod::Card, )); let global_vector = global_vector .into_iter() .filter(|global_value| !enabled_pmt.contains(global_value)) .collect::<Vec<_>>(); global_vector .into_iter() .map(|dir_v| { builder.make_value_node( cgraph::NodeValue::Value(dir_v), Some("Payment Method Type"), None::<()>, ) }) .collect::<Vec<_>>() } fn compile_graph_for_countries_and_currencies( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, config: &kgraph_types::CurrencyCountryFlowFilter, payment_method_type_node: cgraph::NodeId, ) -> Result<cgraph::NodeId, KgraphError> { let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); agg_nodes.push(( payment_method_type_node, cgraph::Relation::Positive, cgraph::Strength::Normal, )); if let Some(country) = config.country.clone() { let node_country = country .into_iter() .map(|country| dir::DirValue::BillingCountry(api_enums::Country::from_alpha2(country))) .collect(); let country_agg = builder .make_in_aggregator(node_country, Some("Configs for Country"), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( country_agg, cgraph::Relation::Positive, cgraph::Strength::Weak, )) } if let Some(currency) = config.currency.clone() { let node_currency = currency .into_iter() .map(IntoDirValue::into_dir_value) .collect::<Result<Vec<_>, _>>()?; let currency_agg = builder .make_in_aggregator(node_currency, Some("Configs for Currency"), None::<()>) .map_err(KgraphError::GraphConstructionError)?; agg_nodes.push(( currency_agg, cgraph::Relation::Positive, cgraph::Strength::Normal, )) } if let Some(capture_method) = config .not_available_flows .and_then(|naf| naf.capture_method) { let make_capture_node = builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(capture_method)), Some("Configs for CaptureMethod"), None::<()>, ); agg_nodes.push(( make_capture_node, cgraph::Relation::Negative, cgraph::Strength::Normal, )) } builder .make_all_aggregator( &agg_nodes, Some("Country & Currency Configs With Payment Method Type"), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError) } // #[cfg(feature = "v1")] fn compile_config_graph( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, config: &kgraph_types::CountryCurrencyFilter, connector: api_enums::RoutableConnectors, ) -> Result<cgraph::NodeId, KgraphError> { let mut agg_node_id: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); let mut pmt_enabled: Vec<dir::DirValue> = Vec::new(); if let Some(pmt) = config .connector_configs .get(&connector) .or(config.default_configs.as_ref()) .map(|inner| inner.0.clone()) { for pm_filter_key in pmt { match pm_filter_key { (kgraph_types::PaymentMethodFilterKey::PaymentMethodType(pm), filter) => { let dir_val_pm = get_dir_value_payment_method(pm)?; let pm_node = if pm == api_enums::PaymentMethodType::Credit || pm == api_enums::PaymentMethodType::Debit { pmt_enabled .push(dir::DirValue::PaymentMethod(api_enums::PaymentMethod::Card)); builder.make_value_node( cgraph::NodeValue::Value(dir::DirValue::PaymentMethod( dir::enums::PaymentMethod::Card, )), Some("PaymentMethod"), None::<()>, ) } else { pmt_enabled.push(dir_val_pm.clone()); builder.make_value_node( cgraph::NodeValue::Value(dir_val_pm), Some("PaymentMethodType"), None::<()>, ) }; let node_config = compile_graph_for_countries_and_currencies(builder, &filter, pm_node)?; agg_node_id.push(( node_config, cgraph::Relation::Positive, cgraph::Strength::Normal, )); } (kgraph_types::PaymentMethodFilterKey::CardNetwork(cn), filter) => { let dir_val_cn = cn.clone().into_dir_value()?; pmt_enabled.push(dir_val_cn); let cn_node = builder.make_value_node( cn.clone().into_dir_value().map(Into::into)?, Some("CardNetwork"), None::<()>, ); let node_config = compile_graph_for_countries_and_currencies(builder, &filter, cn_node)?; agg_node_id.push(( node_config, cgraph::Relation::Positive, cgraph::Strength::Normal, )); } } } } let global_vector_pmt: Vec<cgraph::NodeId> = global_vec_pmt(pmt_enabled, builder); let any_agg_pmt: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = global_vector_pmt .into_iter() .map(|node| (node, cgraph::Relation::Positive, cgraph::Strength::Normal)) .collect::<Vec<_>>(); let any_agg_node = builder .make_any_aggregator( &any_agg_pmt, Some("Any Aggregator For Payment Method Types"), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)?; agg_node_id.push(( any_agg_node, cgraph::Relation::Positive, cgraph::Strength::Normal, )); builder .make_any_aggregator(&agg_node_id, Some("Configs"), None::<()>, None) .map_err(KgraphError::GraphConstructionError) } #[cfg(feature = "v2")] fn compile_merchant_connector_graph( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, mca: admin_api::MerchantConnectorResponse, config: &kgraph_types::CountryCurrencyFilter, ) -> Result<(), KgraphError> { let connector = common_enums::RoutableConnectors::try_from(mca.connector_name) .map_err(|_| KgraphError::InvalidConnectorName(mca.connector_name))?; let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); if let Some(pms_enabled) = mca.payment_methods_enabled.clone() { for pm_enabled in pms_enabled { let maybe_pm_enabled_id = compile_payment_method_enabled(builder, pm_enabled)?; if let Some(pm_enabled_id) = maybe_pm_enabled_id { agg_nodes.push(( pm_enabled_id, cgraph::Relation::Positive, cgraph::Strength::Strong, )); } } } let aggregator_info = "Available Payment methods for connector"; let pms_enabled_agg_id = builder .make_any_aggregator(&agg_nodes, Some(aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError)?; let config_info = "Config for respective PaymentMethodType for the connector"; let config_enabled_agg_id = compile_config_graph(builder, config, connector)?; let domain_level_node_id = builder .make_all_aggregator( &[ ( config_enabled_agg_id, cgraph::Relation::Positive, cgraph::Strength::Normal, ), ( pms_enabled_agg_id, cgraph::Relation::Positive, cgraph::Strength::Normal, ), ], Some(config_info), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)?; let connector_dir_val = dir::DirValue::Connector(Box::new(ast::ConnectorChoice { connector })); let connector_info = "Connector"; let connector_node_id = builder.make_value_node(connector_dir_val.into(), Some(connector_info), None::<()>); builder .make_edge( domain_level_node_id, connector_node_id, cgraph::Strength::Normal, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .map_err(KgraphError::GraphConstructionError)?; Ok(()) } #[cfg(feature = "v1")] fn compile_merchant_connector_graph( builder: &mut cgraph::ConstraintGraphBuilder<dir::DirValue>, mca: admin_api::MerchantConnectorResponse, config: &kgraph_types::CountryCurrencyFilter, ) -> Result<(), KgraphError> { let connector = common_enums::RoutableConnectors::from_str(&mca.connector_name) .map_err(|_| KgraphError::InvalidConnectorName(mca.connector_name.clone()))?; let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new(); if let Some(pms_enabled) = mca.payment_methods_enabled.clone() { for pm_enabled in pms_enabled { let maybe_pm_enabled_id = compile_payment_method_enabled(builder, pm_enabled)?; if let Some(pm_enabled_id) = maybe_pm_enabled_id { agg_nodes.push(( pm_enabled_id, cgraph::Relation::Positive, cgraph::Strength::Strong, )); } } } let aggregator_info = "Available Payment methods for connector"; let pms_enabled_agg_id = builder .make_any_aggregator(&agg_nodes, Some(aggregator_info), None::<()>, None) .map_err(KgraphError::GraphConstructionError)?; let config_info = "Config for respective PaymentMethodType for the connector"; let config_enabled_agg_id = compile_config_graph(builder, config, connector)?; let domain_level_node_id = builder .make_all_aggregator( &[ ( config_enabled_agg_id, cgraph::Relation::Positive, cgraph::Strength::Normal, ), ( pms_enabled_agg_id, cgraph::Relation::Positive, cgraph::Strength::Normal, ), ], Some(config_info), None::<()>, None, ) .map_err(KgraphError::GraphConstructionError)?; let connector_dir_val = dir::DirValue::Connector(Box::new(ast::ConnectorChoice { connector })); let connector_info = "Connector"; let connector_node_id = builder.make_value_node(connector_dir_val.into(), Some(connector_info), None::<()>); builder .make_edge( domain_level_node_id, connector_node_id, cgraph::Strength::Normal, cgraph::Relation::Positive, None::<cgraph::DomainId>, ) .map_err(KgraphError::GraphConstructionError)?; Ok(()) } // #[cfg(feature = "v1")] pub fn make_mca_graph( accts: Vec<admin_api::MerchantConnectorResponse>, config: &kgraph_types::CountryCurrencyFilter, ) -> Result<cgraph::ConstraintGraph<dir::DirValue>, KgraphError> { let mut builder = cgraph::ConstraintGraphBuilder::new(); let _domain = builder.make_domain( DOMAIN_IDENTIFIER.to_string(), "Payment methods enabled for MerchantConnectorAccount", ); for acct in accts { compile_merchant_connector_graph(&mut builder, acct, config)?; } Ok(builder.build()) } #[cfg(feature = "v1")] #[cfg(test)] mod tests { #![allow(clippy::expect_used)] use std::collections::{HashMap, HashSet}; use api_models::enums as api_enums; use euclid::{ dirval, dssa::graph::{AnalysisContext, CgraphExt}, }; use hyperswitch_constraint_graph::{ConstraintGraph, CycleCheck, Memoization}; use super::*; use crate::types as kgraph_types; fn build_test_data() -> ConstraintGraph<dir::DirValue> { use api_models::{admin::*, payment_methods::*}; let profile_id = common_utils::generate_profile_id_of_default_length(); // #[cfg(feature = "v2")] // let stripe_account = MerchantConnectorResponse { // connector_type: api_enums::ConnectorType::FizOperations, // connector_name: "stripe".to_string(), // id: common_utils::generate_merchant_connector_account_id_of_default_length(), // connector_label: Some("something".to_string()), // connector_account_details: masking::Secret::new(serde_json::json!({})), // disabled: None, // metadata: None, // payment_methods_enabled: Some(vec![PaymentMethodsEnabled { // payment_method: api_enums::PaymentMethod::Card, // payment_method_types: Some(vec![ // RequestPaymentMethodTypes { // payment_method_type: api_enums::PaymentMethodType::Credit, // payment_experience: None, // card_networks: Some(vec![ // api_enums::CardNetwork::Visa, // api_enums::CardNetwork::Mastercard, // ]), // accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![ // api_enums::Currency::INR, // ])), // accepted_countries: None, // minimum_amount: Some(MinorUnit::new(10)), // maximum_amount: Some(MinorUnit::new(1000)), // recurring_enabled: true, // installment_payment_enabled: true, // }, // RequestPaymentMethodTypes { // payment_method_type: api_enums::PaymentMethodType::Debit, // payment_experience: None, // card_networks: Some(vec![ // api_enums::CardNetwork::Maestro, // api_enums::CardNetwork::JCB, // ]), // accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![ // api_enums::Currency::GBP, // ])), // accepted_countries: None, // minimum_amount: Some(MinorUnit::new(10)), // maximum_amount: Some(MinorUnit::new(1000)), // recurring_enabled: true, // installment_payment_enabled: true, // }, // ]), // }]), // frm_configs: None, // connector_webhook_details: None, // profile_id, // applepay_verified_domains: None, // pm_auth_config: None, // status: api_enums::ConnectorStatus::Inactive, // additional_merchant_data: None, // connector_wallets_details: None, // }; #[cfg(feature = "v1")] let stripe_account = MerchantConnectorResponse { connector_type: api_enums::ConnectorType::FizOperations, connector_name: "stripe".to_string(), merchant_connector_id: common_utils::generate_merchant_connector_account_id_of_default_length(), business_country: Some(api_enums::CountryAlpha2::US), connector_label: Some("something".to_string()), business_label: Some("food".to_string()), business_sub_label: None, connector_account_details: masking::Secret::new(serde_json::json!({})), test_mode: None, disabled: None, metadata: None, payment_methods_enabled: Some(vec![PaymentMethodsEnabled { payment_method: api_enums::PaymentMethod::Card, payment_method_types: Some(vec![ RequestPaymentMethodTypes { payment_method_type: api_enums::PaymentMethodType::Credit, payment_experience: None, card_networks: Some(vec![ api_enums::CardNetwork::Visa, api_enums::CardNetwork::Mastercard, ]), accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![ api_enums::Currency::INR, ])), accepted_countries: None, minimum_amount: Some(MinorUnit::new(10)), maximum_amount: Some(MinorUnit::new(1000)), recurring_enabled: Some(true), installment_payment_enabled: Some(true), }, RequestPaymentMethodTypes { payment_method_type: api_enums::PaymentMethodType::Debit, payment_experience: None, card_networks: Some(vec![ api_enums::CardNetwork::Maestro, api_enums::CardNetwork::JCB, ]), accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![ api_enums::Currency::GBP, ])), accepted_countries: None, minimum_amount: Some(MinorUnit::new(10)), maximum_amount: Some(MinorUnit::new(1000)), recurring_enabled: Some(true), installment_payment_enabled: Some(true), }, ]), }]), frm_configs: None, connector_webhook_details: None, profile_id, applepay_verified_domains: None, pm_auth_config: None, status: api_enums::ConnectorStatus::Inactive, additional_merchant_data: None, connector_wallets_details: None, }; let config_map = kgraph_types::CountryCurrencyFilter { connector_configs: HashMap::from([( api_enums::RoutableConnectors::Stripe, kgraph_types::PaymentMethodFilters(HashMap::from([ ( kgraph_types::PaymentMethodFilterKey::PaymentMethodType( api_enums::PaymentMethodType::Credit, ), kgraph_types::CurrencyCountryFlowFilter { currency: Some(HashSet::from([ api_enums::Currency::INR, api_enums::Currency::USD, ])), country: Some(HashSet::from([api_enums::CountryAlpha2::IN])), not_available_flows: Some(kgraph_types::NotAvailableFlows { capture_method: Some(api_enums::CaptureMethod::Manual), }), }, ), ( kgraph_types::PaymentMethodFilterKey::PaymentMethodType( api_enums::PaymentMethodType::Debit, ), kgraph_types::CurrencyCountryFlowFilter { currency: Some(HashSet::from([ api_enums::Currency::GBP, api_enums::Currency::PHP, ])), country: Some(HashSet::from([api_enums::CountryAlpha2::IN])), not_available_flows: Some(kgraph_types::NotAvailableFlows { capture_method: Some(api_enums::CaptureMethod::Manual), }), }, ), ])), )]), default_configs: None, }; make_mca_graph(vec![stripe_account], &config_map).expect("Failed graph construction") } #[test] fn test_credit_card_success_case() { let graph = build_test_data(); let result = graph.key_value_analysis( dirval!(Connector = Stripe), &AnalysisContext::from_dir_values([ dirval!(Connector = Stripe), dirval!(PaymentMethod = Card), dirval!(CardType = Credit), dirval!(CardNetwork = Visa), dirval!(PaymentCurrency = INR), dirval!(PaymentAmount = 101), ]), &mut Memoization::new(), &mut CycleCheck::new(), None, ); assert!(result.is_ok()); } #[test] fn test_debit_card_success_case() { let graph = build_test_data(); let result = graph.key_value_analysis( dirval!(Connector = Stripe), &AnalysisContext::from_dir_values([ dirval!(Connector = Stripe), dirval!(PaymentMethod = Card), dirval!(CardType = Debit), dirval!(CardNetwork = Maestro), dirval!(PaymentCurrency = GBP), dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), &mut CycleCheck::new(), None, ); assert!(result.is_ok()); } #[test] fn test_single_mismatch_failure_case() { let graph = build_test_data(); let result = graph.key_value_analysis( dirval!(Connector = Stripe), &AnalysisContext::from_dir_values([ dirval!(Connector = Stripe), dirval!(PaymentMethod = Card), dirval!(CardType = Debit), dirval!(CardNetwork = Maestro), dirval!(PaymentCurrency = PHP), dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), &mut CycleCheck::new(), None, ); assert!(result.is_err()); } #[test] fn test_amount_mismatch_failure_case() { let graph = build_test_data(); let result = graph.key_value_analysis( dirval!(Connector = Stripe), &AnalysisContext::from_dir_values([ dirval!(Connector = Stripe), dirval!(PaymentMethod = Card), dirval!(CardType = Debit), dirval!(CardNetwork = Visa), dirval!(PaymentCurrency = GBP), dirval!(PaymentAmount = 7), ]), &mut Memoization::new(), &mut CycleCheck::new(), None, ); assert!(result.is_err()); } #[test] fn test_incomplete_data_failure_case() { let graph = build_test_data(); let result = graph.key_value_analysis( dirval!(Connector = Stripe), &AnalysisContext::from_dir_values([ dirval!(Connector = Stripe), dirval!(PaymentMethod = Card), dirval!(CardType = Debit), dirval!(PaymentCurrency = GBP), dirval!(PaymentAmount = 7), ]), &mut Memoization::new(), &mut CycleCheck::new(), None, ); //println!("{:#?}", result); //println!("{}", serde_json::to_string_pretty(&result).expect("Hello")); assert!(result.is_err()); } #[test] fn test_incomplete_data_failure_case2() { let graph = build_test_data(); let result = graph.key_value_analysis( dirval!(Connector = Stripe), &AnalysisContext::from_dir_values([ dirval!(Connector = Stripe), dirval!(CardType = Debit), dirval!(CardNetwork = Visa), dirval!(PaymentCurrency = GBP), dirval!(PaymentAmount = 100), ]), &mut Memoization::new(), &mut CycleCheck::new(), None, ); //println!("{:#?}", result); //println!("{}", serde_json::to_string_pretty(&result).expect("Hello")); assert!(result.is_err()); } #[test] fn test_sandbox_applepay_bug_usecase() { let value = serde_json::json!([ { "connector_type": "payment_processor", "connector_name": "bluesnap", "merchant_connector_id": "REDACTED", "status": "inactive", "connector_account_details": { "auth_type": "BodyKey", "api_key": "REDACTED", "key1": "REDACTED" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Mastercard", "Visa", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Mastercard", "Visa", "Interac", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": {}, "business_country": "US", "business_label": "default", "business_sub_label": null, "frm_configs": null }, { "connector_type": "payment_processor", "connector_name": "stripe", "merchant_connector_id": "REDACTED", "status": "inactive", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "REDACTED" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Mastercard", "Visa", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Mastercard", "Visa", "Interac", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [] } ], "metadata": {}, "business_country": "US", "business_label": "default", "business_sub_label": null, "frm_configs": null } ]); let data: Vec<admin_api::MerchantConnectorResponse> = serde_json::from_value(value).expect("data"); let config = kgraph_types::CountryCurrencyFilter { connector_configs: HashMap::new(), default_configs: None, }; let graph = make_mca_graph(data, &config).expect("graph"); let context = AnalysisContext::from_dir_values([ dirval!(Connector = Stripe), dirval!(PaymentAmount = 212), dirval!(PaymentCurrency = ILS), dirval!(PaymentMethod = Wallet), dirval!(WalletType = ApplePay), ]); let result = graph.key_value_analysis( dirval!(Connector = Stripe), &context, &mut Memoization::new(), &mut CycleCheck::new(), None, ); assert!(result.is_ok(), "stripe validation failed"); let result = graph.key_value_analysis( dirval!(Connector = Bluesnap), &context, &mut Memoization::new(), &mut CycleCheck::new(), None, ); assert!(result.is_err(), "bluesnap validation failed"); } }
crates/kgraph_utils/src/mca.rs
kgraph_utils::src::mca
13,116
true
// File: crates/external_services/build.rs // Module: external_services::build #[allow(clippy::expect_used)] fn main() -> Result<(), Box<dyn std::error::Error>> { // Compilation for revenue recovery protos #[cfg(feature = "revenue_recovery")] { let proto_base_path = router_env::workspace_path().join("proto"); let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?); let recovery_proto_files = [proto_base_path.join("recovery_decider.proto")]; tonic_build::configure() .out_dir(&out_dir) .compile_well_known_types(true) .extern_path(".google.protobuf.Timestamp", "::prost_types::Timestamp") .compile_protos(&recovery_proto_files, &[&proto_base_path]) .expect("Failed to compile revenue-recovery proto files"); } // Compilation for dynamic_routing protos #[cfg(feature = "dynamic_routing")] { // Get the directory of the current crate let proto_path = router_env::workspace_path().join("proto"); let success_rate_proto_file = proto_path.join("success_rate.proto"); let contract_routing_proto_file = proto_path.join("contract_routing.proto"); let elimination_proto_file = proto_path.join("elimination_rate.proto"); let health_check_proto_file = proto_path.join("health_check.proto"); let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?); // Compile the .proto file tonic_build::configure() .out_dir(out_dir) .compile_protos( &[ success_rate_proto_file, health_check_proto_file, elimination_proto_file, contract_routing_proto_file, ], &[proto_path], ) .expect("Failed to compile proto files"); } Ok(()) }
crates/external_services/build.rs
external_services::build
399
true
// File: crates/external_services/src/superposition.rs // Module: external_services::src::superposition //! Superposition client for dynamic configuration management /// Type definitions for Superposition integration pub mod types; use std::collections::HashMap; use common_utils::errors::CustomResult; use error_stack::report; use masking::ExposeInterface; pub use self::types::{ConfigContext, SuperpositionClientConfig, SuperpositionError}; fn convert_open_feature_value(value: open_feature::Value) -> Result<serde_json::Value, String> { match value { open_feature::Value::String(s) => Ok(serde_json::Value::String(s)), open_feature::Value::Bool(b) => Ok(serde_json::Value::Bool(b)), open_feature::Value::Int(n) => Ok(serde_json::Value::Number(serde_json::Number::from(n))), open_feature::Value::Float(f) => serde_json::Number::from_f64(f) .map(serde_json::Value::Number) .ok_or_else(|| format!("Invalid number: {f}")), open_feature::Value::Struct(sv) => Ok(types::JsonValue::try_from(sv)?.into_inner()), open_feature::Value::Array(values) => Ok(serde_json::Value::Array( values .into_iter() .map(convert_open_feature_value) .collect::<Result<Vec<_>, _>>()?, )), } } /// Superposition client wrapper // Debug trait cannot be derived because open_feature::Client doesn't implement Debug #[allow(missing_debug_implementations)] pub struct SuperpositionClient { client: open_feature::Client, } impl SuperpositionClient { /// Create a new Superposition client pub async fn new(config: SuperpositionClientConfig) -> CustomResult<Self, SuperpositionError> { let provider_options = superposition_provider::SuperpositionProviderOptions { endpoint: config.endpoint.clone(), token: config.token.expose(), org_id: config.org_id.clone(), workspace_id: config.workspace_id.clone(), fallback_config: None, evaluation_cache: None, refresh_strategy: superposition_provider::RefreshStrategy::Polling( superposition_provider::PollingStrategy { interval: config.polling_interval, timeout: config.request_timeout, }, ), experimentation_options: None, }; // Create provider and set up OpenFeature let provider = superposition_provider::SuperpositionProvider::new(provider_options); // Initialize OpenFeature API and set provider let mut api = open_feature::OpenFeature::singleton_mut().await; api.set_provider(provider).await; // Create client let client = api.create_client(); router_env::logger::info!("Superposition client initialized successfully"); Ok(Self { client }) } /// Build evaluation context for Superposition requests fn build_evaluation_context( &self, context: Option<&ConfigContext>, ) -> open_feature::EvaluationContext { open_feature::EvaluationContext { custom_fields: context.map_or(HashMap::new(), |ctx| { ctx.values .iter() .map(|(k, v)| { ( k.clone(), open_feature::EvaluationContextFieldValue::String(v.clone()), ) }) .collect() }), targeting_key: None, } } /// Get a boolean configuration value from Superposition pub async fn get_bool_value( &self, key: &str, context: Option<&ConfigContext>, ) -> CustomResult<bool, SuperpositionError> { let evaluation_context = self.build_evaluation_context(context); self.client .get_bool_value(key, Some(&evaluation_context), None) .await .map_err(|e| { report!(SuperpositionError::ClientError(format!( "Failed to get bool value for key '{key}': {e:?}" ))) }) } /// Get a string configuration value from Superposition pub async fn get_string_value( &self, key: &str, context: Option<&ConfigContext>, ) -> CustomResult<String, SuperpositionError> { let evaluation_context = self.build_evaluation_context(context); self.client .get_string_value(key, Some(&evaluation_context), None) .await .map_err(|e| { report!(SuperpositionError::ClientError(format!( "Failed to get string value for key '{key}': {e:?}" ))) }) } /// Get an integer configuration value from Superposition pub async fn get_int_value( &self, key: &str, context: Option<&ConfigContext>, ) -> CustomResult<i64, SuperpositionError> { let evaluation_context = self.build_evaluation_context(context); self.client .get_int_value(key, Some(&evaluation_context), None) .await .map_err(|e| { report!(SuperpositionError::ClientError(format!( "Failed to get int value for key '{key}': {e:?}" ))) }) } /// Get a float configuration value from Superposition pub async fn get_float_value( &self, key: &str, context: Option<&ConfigContext>, ) -> CustomResult<f64, SuperpositionError> { let evaluation_context = self.build_evaluation_context(context); self.client .get_float_value(key, Some(&evaluation_context), None) .await .map_err(|e| { report!(SuperpositionError::ClientError(format!( "Failed to get float value for key '{key}': {e:?}" ))) }) } /// Get an object configuration value from Superposition pub async fn get_object_value( &self, key: &str, context: Option<&ConfigContext>, ) -> CustomResult<serde_json::Value, SuperpositionError> { let evaluation_context = self.build_evaluation_context(context); let json_result = self .client .get_struct_value::<types::JsonValue>(key, Some(&evaluation_context), None) .await .map_err(|e| { report!(SuperpositionError::ClientError(format!( "Failed to get object value for key '{key}': {e:?}" ))) })?; Ok(json_result.into_inner()) } }
crates/external_services/src/superposition.rs
external_services::src::superposition
1,361
true